From 69d6e495f750913bba7a60482b028076b3e27f0c Mon Sep 17 00:00:00 2001 From: tomolimo Date: Thu, 25 Jul 2019 15:43:17 +0200 Subject: [PATCH] Fixed copy/paste issue with suggest boxes Typo fixes in EOL Set version to 3.3.0-community-RE-1.5 --- gulliver/methods/defaultAjax.php | 2 +- shared/remove.txt | 6 +- .../MichelangeloFE/build/js/designer.js | 34196 ++--- vendor/colosa/MichelangeloFE/build/js/mafe.js | 56196 ++++---- .../lib/wz_jsgraphics/wz_jsgraphics.js | 2216 +- .../colosa/MichelangeloFE/src/LabelControl.js | 72 +- .../src/applications/contextMenu.js | 3584 +- .../src/applications/dynaformsModule.js | 666 +- .../src/applications/granularProcessExport.js | 338 +- .../src/applications/intro_helper.js | 166 +- .../applications/pm_criteria_user_field.js | 252 +- .../src/applications/routingRule.js | 1758 +- .../src/applications/startMessageModule.js | 828 +- .../src/applications/startTimerModule.js | 1982 +- .../src/applications/triggersModule.js | 3854 +- .../colosa/MichelangeloFE/src/codeMirror.js | 324 +- .../src/command_default_flow.js | 98 +- .../MichelangeloFE/src/create_shape_helper.js | 114 +- .../MichelangeloFE/src/css/dynaform.css | 54 +- .../colosa/MichelangeloFE/src/css/trigger.css | 102 +- vendor/colosa/MichelangeloFE/src/iframe.js | 150 +- .../src/import/BpmnTreeWalker.js | 736 +- .../MichelangeloFE/src/import/Importer.js | 1884 +- .../MichelangeloFE/src/import/collection.js | 160 +- .../colosa/MichelangeloFE/src/import/refs.js | 360 +- .../colosa/MichelangeloFE/src/labelField.js | 108 +- .../MichelangeloFE/src/moddle/bpmn-moddle.js | 11276 +- .../colosa/MichelangeloFE/src/moddle/sax.js | 2818 +- .../src/modeling/BpmnFactory.js | 154 +- .../src/participant_resize_behavior.js | 58 +- .../src/pm_activity_container_behavior.js | 132 +- .../src/pm_activity_drop_behavior.js | 360 +- vendor/colosa/MichelangeloFE/src/pm_canvas.js | 4130 +- .../src/pm_canvas_container_behavior.js | 160 +- .../src/pm_command_change_event_marker.js | 162 +- .../src/pm_command_create_lane.js | 94 +- .../MichelangeloFE/src/pm_command_delete.js | 618 +- .../src/pm_command_lane_resize.js | 72 +- .../src/pm_command_pool_resize.js | 232 +- .../src/pm_container_drop_behavior.js | 336 +- vendor/colosa/MichelangeloFE/src/pm_lane.js | 1098 +- .../src/pm_lane_container_behavior.js | 66 +- .../src/pm_lane_resize_behavior.js | 116 +- vendor/colosa/MichelangeloFE/src/pm_marker.js | 356 +- .../MichelangeloFE/src/pm_participant.js | 658 +- vendor/colosa/MichelangeloFE/src/pm_pool.js | 2078 +- .../src/pm_pool_resize_behavior.js | 316 +- .../colosa/MichelangeloFE/src/pm_project.js | 1890 +- .../MichelangeloFE/src/pm_validator_marker.js | 596 +- .../src/pool_container_behavior.js | 240 +- .../src/restclient/rest_client.js | 144 +- .../MichelangeloFE/src/sass/corona.scss | 260 +- .../MichelangeloFE/src/sass/dynaform.scss | 66 +- .../src/sass/formDesigner_1.scss | 1998 +- .../src/sass/propertiesTable.scss | 120 +- .../MichelangeloFE/src/sass/stepOfTask.scss | 234 +- .../MichelangeloFE/src/sass/trigger.scss | 146 +- .../MichelangeloFE/src/separatorLine.js | 146 +- .../MichelangeloFE/src/separatorLineField.js | 112 +- .../colosa/MichelangeloFE/src/suggestField.js | 864 +- .../MichelangeloFE/themes/mafe/config.json | 8 +- .../themes/mafe/var/_designer.scss | 260 +- .../themes/mafe/var/_varsMafe.scss | 348 +- .../themes/mafe/var/_varsMafe2.scss | 1314 +- vendor/colosa/pmUI/build/js/pmui-0.1.1.js | 218 +- .../libraries/jquery.layout/jquery.layout.js | 11876 +- .../libraries/wz_jsgraphics/wz_jsgraphics.js | 2216 +- vendor/colosa/pmUI/themes/mafe/config.json | 8 +- .../pmUI/themes/mafe/var/_varsMafe.scss | 130 +- .../pmUI/themes/mafe/var/_varsMafe2.scss | 626 +- vendor/dapphp/securimage/securimage.php | 6928 +- vendor/libchart/libchart/build.xml | 134 +- .../libchart/Libchart/Model/ChartConfig.php | 222 +- .../libchart/Libchart/Model/DataSet.php | 54 +- .../libchart/Libchart/Model/XYDataSet.php | 110 +- .../Libchart/Model/XYSeriesDataSet.php | 150 +- .../libchart/Libchart/View/Axis/Bound.php | 310 +- .../libchart/Libchart/View/Chart/BarChart.php | 20 +- .../View/Chart/HorizontalBarChart.php | 8 +- .../libchart/Libchart/View/Chart/PieChart.php | 12 +- .../Libchart/View/Chart/VerticalBarChart.php | 8 +- .../libchart/Libchart/View/Color/ColorSet.php | 10 +- .../View/Label/DefaultLabelGenerator.php | 4 +- .../Libchart/View/Label/LabelGenerator.php | 4 +- .../libchart/Libchart/View/Plot/Plot.php | 56 +- .../Libchart/View/Primitive/Rectangle.php | 10 +- .../libchart/libchart/doc/DEJAVU_LICENSE | 102 +- .../test/actual/customlabelgenerator1.php | 4 +- .../test/actual/customlabelgenerator2.php | 4 +- .../libchart/libchart/test/actual/decimal.php | 4 +- .../libchart/libchart/test/actual/divby0.php | 4 +- .../libchart/libchart/test/actual/divby1.php | 4 +- .../libchart/libchart/test/actual/divby2.php | 4 +- .../libchart/libchart/test/actual/divby3.php | 4 +- .../libchart/test/actual/example1.php | 4 +- .../libchart/test/actual/example2.php | 4 +- .../libchart/test/actual/example3.php | 4 +- .../test/actual/horizontalbarnegative.php | 4 +- .../libchart/test/actual/issue0001.2.php | 36 +- .../libchart/test/actual/linenegative.php | 4 +- .../libchart/libchart/test/actual/nologo.php | 4 +- .../libchart/test/actual/novalue1.php | 6 +- .../libchart/test/actual/novalue2.php | 6 +- .../libchart/test/actual/piedisablesort1.php | 4 +- .../libchart/test/actual/piedisablesort2.php | 4 +- .../test/actual/verticalbarnegative.php | 4 +- vendor/libchart/libchart/test/index.html | 10 +- .../_008_documentation/explorer/index.html | 188 +- .../explorer/lib/jquery-1.8.0.min.js | 2 +- .../_008_documentation/explorer/swagger-ui.js | 322 +- .../_009_rate_limiting/explorer/index.html | 188 +- .../explorer/lib/jquery-1.8.0.min.js | 2 +- .../_009_rate_limiting/explorer/swagger-ui.js | 322 +- .../_010_access_control/explorer/index.html | 188 +- .../explorer/lib/jquery-1.8.0.min.js | 2 +- .../explorer/swagger-ui.js | 322 +- .../_011_versioning/explorer/index.html | 188 +- .../explorer/lib/jquery-1.8.0.min.js | 2 +- .../_011_versioning/explorer/swagger-ui.js | 322 +- .../examples/_013_html/explorer/index.html | 188 +- .../explorer/lib/jquery-1.8.0.min.js | 2 +- .../examples/_013_html/explorer/swagger-ui.js | 322 +- .../public/examples/_013_html/script.js | 314 +- .../public/examples/_013_html/styles.css | 402 +- .../_014_oauth2_client/OAuth2/Client.php | 146 + .../_014_oauth2_client/OAuth2/Curl.php | 146 + .../_015_oauth2_server/OAuth2/Server.php | 126 + .../public/tests/param/explorer/index.html | 188 +- .../param/explorer/lib/jquery-1.8.0.min.js | 2 +- .../public/tests/param/explorer/swagger-ui.js | 322 +- .../tests/request_data/explorer/index.html | 188 +- .../explorer/lib/jquery-1.8.0.min.js | 2 +- .../tests/request_data/explorer/swagger-ui.js | 322 +- .../pear/archive_tar/tests/dirtraversal.phpt | 48 +- vendor/vendor/google/apiclient/.gitignore | 14 +- vendor/vendor/google/apiclient/.travis.yml | 86 +- .../src/Google/Auth/AssertionCredentials.php | 296 +- .../apiclient/src/Google/Cache/File.php | 424 +- .../apiclient/src/Google/Http/Request.php | 1036 +- workflow/engine/classes/WsBase.php | 40 +- .../engine/config/execute-query-blacklist.ini | 28 +- workflow/engine/js/labels/remove.txt | 6 +- workflow/engine/js/src/PM.js | 10 +- workflow/engine/js/src/Register.js | 4 +- workflow/engine/js/src/Sessions.js | 276 +- .../engine/methods/login/version-pmos.php | 4 +- .../methods/processes/processObjects.php | 8 +- .../processes/processes_DeleteCases.php | 50 +- .../BusinessModel/BpmnProcess.php | 64 +- .../BusinessModel/BpmnProject.php | 26 +- .../ProcessMaker/Util/ElementTranslation.php | 204 +- .../webentry/cases_ScreenDerivation.html | 10 +- .../glpi-project/php-library-glpi/.atoum.php | 30 +- .../glpi-project/php-library-glpi/.gitignore | 70 +- .../glpi-project/php-library-glpi/.travis.yml | 102 +- .../php-library-glpi/CODE_OF_CONDUCT.md | 22 +- .../php-library-glpi/CONTRIBUTING.md | 210 +- .../glpi-project/php-library-glpi/LICENSE.md | 500 +- .../glpi-project/php-library-glpi/README.md | 230 +- .../php-library-glpi/composer.json | 112 +- .../php-library-glpi/example/README.md | 36 +- .../php-library-glpi/example/example.php | 118 +- .../example/magicCallExample.php | 124 +- .../src/Glpi/Api/Rest/Client.php | 474 +- .../src/Glpi/Api/Rest/EndPointHandler.php | 282 +- .../src/Glpi/Api/Rest/ErrorHandler.php | 140 +- .../Rest/Exception/BadEndpointException.php | 68 +- .../InsufficientArgumentsException.php | 68 +- .../src/Glpi/Api/Rest/ItemHandler.php | 1294 +- .../php-library-glpi/tests/BaseTestCase.php | 226 +- .../php-library-glpi/tests/bootstrap.php | 132 +- .../php-library-glpi/tests/unit/Client.php | 430 +- .../tests/unit/EndPointHandler.php | 302 +- .../tests/unit/ItemHandler.php | 830 +- workflow/public_html/glpi/app.php | 626 +- workflow/public_html/glpi/classlist.js | 108 +- workflow/public_html/glpi/fixfilter.js | 50 +- workflow/public_html/glpi/glpi_helpers.js | 442 +- .../public_html/glpi/glpi_helpers_bpmn.js | 642 +- .../public_html/glpi/jquery/jquery-1.10.2.js | 19586 +-- .../glpi/jquery/jquery-1.10.2.min.js | 12 +- .../public_html/glpi/jquery/noConflict.js | 8 +- workflow/public_html/glpi/object-watch.js | 188 +- .../lib/js/mafe-583402f-55d72ce.js | 110156 +++++++-------- .../lib/pmdynaform/build/form.html | 62 +- .../lib/pmdynaform/build/form2.html | 62 +- .../lib/pmdynaform/build/formRest.html | 62 +- .../lib/pmdynaform/build/gridRest.html | 62 +- .../lib/pmdynaform/build/js/PMDynaform.js | 1524 +- .../lib/pmdynaform/build/pmdynaform.html | 62 +- workflow/public_html/pmGmail/lostSession.php | 64 +- workflow/public_html/pmGmail/templateForm.php | 228 +- workflow/public_html/translations/remove.txt | 6 +- 193 files changed, 157550 insertions(+), 157132 deletions(-) create mode 100644 vendor/luracast/restler/public/examples/_014_oauth2_client/OAuth2/Client.php create mode 100644 vendor/luracast/restler/public/examples/_014_oauth2_client/OAuth2/Curl.php create mode 100644 vendor/luracast/restler/public/examples/_015_oauth2_server/OAuth2/Server.php diff --git a/gulliver/methods/defaultAjax.php b/gulliver/methods/defaultAjax.php index 2d43a5dfc..1aba7c44f 100755 --- a/gulliver/methods/defaultAjax.php +++ b/gulliver/methods/defaultAjax.php @@ -117,7 +117,7 @@ } else { foreach ($v[$_POST['row']] as $k1 => $v1) { $myDependentFields = subDependencies($k1, $G_FORM, $aux, $_POST['grid']); - $_SESSION[$G_FORM->id][$_POST['grid']] = []; + $_SESSION[$G_FORM->id][$_POST['grid']] = []; $_SESSION[$G_FORM->id][$_POST['grid']][$_POST['row']][$k1] = $v1; $G_FORM->values[$_POST['grid']][$_POST['row']][$k1] = $v1; } diff --git a/shared/remove.txt b/shared/remove.txt index 977321426..28138d7bd 100644 --- a/shared/remove.txt +++ b/shared/remove.txt @@ -1,3 +1,3 @@ -Vous pouvez effacer ce fichier sans dommages. - -You can safely remove this file. +Vous pouvez effacer ce fichier sans dommages. + +You can safely remove this file. diff --git a/vendor/colosa/MichelangeloFE/build/js/designer.js b/vendor/colosa/MichelangeloFE/build/js/designer.js index ad516a84a..6fb646a7c 100644 --- a/vendor/colosa/MichelangeloFE/build/js/designer.js +++ b/vendor/colosa/MichelangeloFE/build/js/designer.js @@ -1729,1943 +1729,2285 @@ ViewTaskInformation.prototype.showViewLegendsInformation = function () { }); }; +(function () { + /** + * @class PMUI.menu.ContextMenu + * Handles the context menu of designer + * contains all the menus for elements + * + * @extend PMUI.util.Factory + * @constructor + * This method creates a new instance of this object + * @param {Object} [settings] Constructor settings + */ + "use strict"; + var ContextMenu = function (settings) { + this.factory = null; + ContextMenu.prototype.init.call(this, settings); + }; + + ContextMenu.prototype.type = 'ContextMenu'; + + ContextMenu.prototype.family = 'ContextMenu'; + + /** + * Initializes the object. + * @param {Object} settings A JSON object with the config options. + * @private + */ + ContextMenu.prototype.init = function (settings) { + jQuery.extend(true, defaults, settings); + this.factory = new PMUI.util.Factory(defaults.factory); + }; + + /** + * Register a new context menu object into a product. + * + * Usage example: + * @example + * //Remember, this is an abstract class so it shouldn't be instantiate, + * //anyway we are instantiating it just for this example + * var additionalMenu = { + * id: "additionalMenu", + * text: "New Menu", + * onClick: function () { + * PMDesigner.msgWinWarning('This is a new Menu'); + * } + * }; + * // Assuming that you're using PMDesigner.contextMenuFactory as the default contextMenuFactory + * PMDesigner.contextMenuFactory.registerMenu("CANVAS", additionalMenu); + * + * @param {String} productName Name of the shape or product in factory. + * @param {Object} menu Object with menu values and actions. + * @private + */ + ContextMenu.prototype.registerMenu = function (productName, menu) { + if (typeof this.factory.products[productName] === 'undefined') { + console.log('Context Menu Warning: Cannot add Menu into: ' + productName + '. Please, review name.'); + } else { + if (this.factory.products[productName].items instanceof Array) { + this.factory.products[productName].items.push(menu); + } + } + }; + + /** + * Removes context menu object from product. + * + * Usage example: + * @example + * // Assuming that you're using PMDesigner.contextMenuFactory as the default contextMenuFactory + * // this example removes Canvas gridLines option + * PMDesigner.contextMenuFactory.removeMenu("CANVAS", "id", "menuGridLines"); + * + * @param {String} product Name of the shape or product in factory. + * @param {String} id Key to look through product. + * @param {String} value Name of the elementValue. + * @private + */ + ContextMenu.prototype.removeMenu = function (product, id, value) { + if (typeof this.factory.products[product] !== 'undefined') { + this.factory.products[product].items = _.reject(this.factory.products[product].items, function (menuValue) { + return menuValue[id] === value; + }); + } else { + console.log('Context Menu Warning: Cannot find ' + product + ' Menu. Please, review name.'); + } + }; + + /** + * Returns specific product. + * @param {String} type Name of product. + * @private + */ + ContextMenu.prototype.getProduct = function (type) { + return this.factory.products[type]; + }; + + var menuMessages = { + 'START': { + 'TIMER': 'Please configure cron to create cases.'.translate(), + 'CONDITIONAL': 'Please configure cron to create cases in base to a condition.'.translate(), + 'SIGNALCATCH': 'Please configure cron to create cases in base to a signal.'.translate() + }, + 'INTERMEDIATE': { + 'CATCH': { + 'TIMER': 'Please configure cron to wait for time event.'.translate(), + 'CONDITIONAL': 'Please configure cron to wait for time condition.'.translate(), + 'SIGNALCATCH': 'Please configure script to wait for a signal.'.translate() + }, + 'THROW': { + 'SIGNALTHROW': 'Please configure a script to send a signal.'.translate() + } + }, + 'END': { + 'ERRORTHROW': 'Please configure script to end with error status.'.translate(), + 'SIGNALTHROW': 'Please configure script to send a signal.'.translate(), + 'TERMINATETHROW': 'Please configure script to terminate case.'.translate() + } + }, + menu = {}, + rootMenu, + elementActivite, + typeMenu = { + text: "Gateway Type".translate(), + icon: "mafe-menu-properties-action", + id: "gatewaytype", + items: [ + { + id: "gatewayexclusive", + text: "Exclusive (XOR) Gateway".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeTypeTo('EXCLUSIVE'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "gatewayparallel", + text: "Parallel (AND) Gateway".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeTypeTo('PARALLEL'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "gatewayinclusive", + text: "Inclusive (OR) Gateway".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeTypeTo('INCLUSIVE'); + PMDesigner.project.updateElement([]); + } + } + ] + }, + endMarker = { + text: "End Event Type".translate(), + icon: "mafe-menu-properties-action", + id: "result", + items: [ + { + id: "endempty", + text: "Empty".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('EMPTY', 'Empty'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "endemail", + text: "Email Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('EMAIL', 'Email Message'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "endmessagethrow", + text: "Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('MESSAGETHROW', 'Message'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "enderrorthrow", + text: "Error".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('ERRORTHROW', 'Error'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "endsignalthrow", + text: "Signal".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('SIGNALTHROW', 'Signal'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "endterminatethrow", + text: "Terminate".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('TERMINATETHROW', 'Terminate'); + PMDesigner.project.updateElement([]); + } + } + ] + }, + intermediateCatchMarker = { + text: "Intermediate Event Type".translate(), + icon: "mafe-menu-properties-action", + id: "trigger", + items: [ + { + id: "intermediatemessagecatch", + text: "Receive Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('MESSAGECATCH', 'Receive Message'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "intermediatetimer", + text: "Timer".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('TIMER', 'Timer'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "intermediateconditional", + text: "Conditional".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('CONDITIONAL', 'Conditional'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "intermediatesignalcatch", + text: "Signal".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('SIGNALCATCH', 'Signal'); + PMDesigner.project.updateElement([]); + } + } + ] + }, + boundaryCatchMarker = { + text: "Boundary Event Type".translate(), + icon: "mafe-menu-properties-action", + id: "eventType", + items: [ + { + id: "messageCatch", + text: "Receive Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('MESSAGECATCH', 'Receive Message'); + } + }, + { + id: "boundaryTimer", + text: "Timer".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('TIMER', 'Timer'); + } + }, + { + id: "BoudaryConditional", + text: "Conditional".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('CONDITIONAL', 'Conditional'); + } + }, + { + id: "BoudarySignal", + text: "Signal".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('SIGNALCATCH', 'Signal'); + } + }, + { + id: "BoudaryError", + text: "Error".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('ERRORCATCH', 'Error'); + } + } + ] + }, + intermediateThrowMarker = { + text: "Intermediate Event Type".translate(), + icon: "mafe-menu-properties-action", + id: "result", + items: [ + { + id: "intermediateemail", + text: "Email Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('EMAIL', 'Email Message'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "intermediatemessagethrow", + text: "Send Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('MESSAGETHROW', 'Send Message'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "intermediatesignalthrow", + text: "Signal".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('SIGNALTHROW', 'Signal'); + PMDesigner.project.updateElement([]); + } + } + ] + }, + startCatchMarker = { + text: "Start Event Type".translate(), + icon: "mafe-menu-properties-action", + id: "trigger", + items: [ + { + id: "startempty", + text: "Empty".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('EMPTY', 'Empty'); + PMDesigner.project.updateElement([]); + } + }, + { + id: "startmessagecatch", + text: "Receive Message".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('MESSAGECATCH', 'Receive Message'); + rootMenu = menuOption.getRootMenu(); + rootMenu.getItems()[3].disable(); + PMDesigner.project.updateElement([]); + } + }, + { + id: "starttimer", + text: "Timer".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('TIMER', 'Timer'); + rootMenu = menuOption.getRootMenu(); + rootMenu.getItems()[3].disable(); + PMDesigner.project.updateElement([]); + } + }, + { + id: "startconditional", + text: "Conditional".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('CONDITIONAL', 'Conditional'); + rootMenu = menuOption.getRootMenu(); + rootMenu.getItems()[3].disable(); + PMDesigner.project.updateElement([]); + } + }, + { + id: "startsignalcatch", + text: "Signal".translate(), + onClick: function (menuOption) { + var targetElement = menuOption + .getMenuTargetElement(); + targetElement.changeMarkerTo('SIGNALCATCH', 'Signal'); + rootMenu = menuOption.getRootMenu(); + rootMenu.getItems()[3].disable(); + PMDesigner.project.updateElement([]); + } + } + ] + }, + canvas = { + id: "menuCanvas", + width: 150, + items: [ + { + id: "menuEditProcess", + text: "Edit Process".translate(), + onClick: function (menuOption) { + PMDesigner.propertiesProcess(); + } + }, + { + id: "menuGridLines", + text: "Enable Grid Lines".translate(), + onClick: function () { + var canvas = PMUI.getActiveCanvas(); + if (canvas.toogleGridLine()) { + this.setText("Disable Grid Lines".translate()); + } else { + this.setText("Enable Grid Lines".translate()); + } + } + } + ], + onShow: function (menu) { + var canvas = PMUI.getActiveCanvas(); + if (canvas.currentConnection) { + canvas.currentConnection.hidePortsAndHandlers(); + } + if (canvas.isGridLine) { + menu.items.find('id', 'menuGridLines').setText("Disable Grid Lines".translate()); + } + + } + }, + task = { + id: "menuTask", + items: [ + { + id: "taskType", + text: "Task Type".translate(), + items: [ + { + id: "empty", + text: "Empty Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "sendtask", + text: "Send Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "receivetask", + text: "Receive Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "usertask", + text: "User Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "servicetask", + text: "Service Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "scripttask", + text: "Script Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "manualtask", + text: "Manual Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + }, + { + id: "businessrule", + text: "Business Rule Task".translate(), + onClick: function (menuOption) { + handlerMarkerType(menuOption); + } + } + ] + }, + { + id: "loopType", + text: "Marker Type".translate(), + items: [ + { + id: "empty", + text: "None".translate(), + onClick: function (menuOption) { + handlerMarkerLoopType(menuOption); + } + }, + { + id: "loop", + text: "Loop".translate(), + onClick: function (menuOption) { + handlerMarkerLoopType(menuOption); + } + }, + { + id: "parallel", + text: "Parallel".translate(), + onClick: function (menuOption) { + handlerMarkerLoopType(menuOption); + } + }, + { + id: "sequential", + text: "Sequential".translate(), + onClick: function (menuOption) { + handlerMarkerLoopType(menuOption); + } + } + ] + }, + { + id: "menuTaskSteps", + text: "Steps".translate(), + icon: "mafe-menu-task-steps", + onClick: function (menuOption) { + var splitedID = menuOption.getMenuTargetElement().getID().split("-"); + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.act_name = menuOption.getMenuTargetElement().act_name; + PMDesigner.act_uid = menuOption.getMenuTargetElement().act_uid; + PMDesigner.stepsTask = new stepsTask(); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.act_name = menuOption.getMenuTargetElement().act_name; + PMDesigner.act_uid = menuOption.getMenuTargetElement().act_uid; + PMDesigner.stepsTask = new stepsTask(); + } + } + }, + { + id: "menuTaskAssignedRules", + text: "Assignment Rules".translate(), + icon: "mafe-menu-users-action", + onClick: function (menuOption) { + var splitedID = menuOption.getMenuTargetElement().getID().split("-"); + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.assigmentRules(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.assigmentRules(menuOption.getMenuTargetElement()); + } + } + }, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.parent.hide(); + + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + menuOption.parent.hide(); + + PMUI.getActiveCanvas().removeElements(); + } + }, + { + id: "menuTaskProperties", + text: "Properties".translate(), + icon: "mafe-menu-properties-action", + onClick: function (menuOption) { + var splitedID = menuOption.getMenuTargetElement().getID().split("-"); + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.activityProperties(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.activityProperties(menuOption.getMenuTargetElement()); + } + } + } + ], + onShow: function (menu) { + var targetElement = menu.getTargetElement(); + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(targetElement); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection + .hidePortsAndHandlers(); + } + + if (targetElement.act_task_type == "SCRIPTTASK") { + menu.getItems()[1].setVisible(false); + menu.getItems()[2].setVisible(false); + menu.getItems()[3].setVisible(false); + } else { + menu.getItems()[1].setVisible(true); + menu.getItems()[2].setVisible(true); + menu.getItems()[3].setVisible(true); + } + + if (targetElement.act_task_type == "MANUALTASK" || targetElement.act_task_type == "USERTASK" || targetElement.act_task_type == "EMPTY") { + menu.getItems()[1].getItems()[2].setVisible(true); + } else { + menu.getItems()[1].getItems()[2].setVisible(false); + } + } + }, + subProcess = { + id: "menuSubProcess", + items: [ + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.parent.hide(); + + menuOption.getMenuTargetElement().label.canvas + .hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete Routing Rule".translate(), + icon: "mafe-menu-delete-rules-action", + onClick: function (menuOption) { + var splitedID = menuOption.getMenuTargetElement().getID().split("-"); + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.RoutingRuleDeleteAllFlow(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.RoutingRuleDeleteAllFlow(menuOption.getMenuTargetElement()); + } + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + menuOption.parent.hide(); + + PMUI.getActiveCanvas().removeElements(); + } + }, + { + id: "menuSubProperties", + text: "Properties".translate(), + icon: "mafe-menu-properties-action", + onClick: function (menuOption) { + var splitedID = menuOption.getMenuTargetElement().getID().split("-"); + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.propertiesSubProcess(menuOption + .getMenuTargetElement(menuOption.getMenuTargetElement())); + + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.propertiesSubProcess(menuOption + .getMenuTargetElement(menuOption.getMenuTargetElement())); + + } + } + } + ], + onShow: function (menu) { + var targetElement = menu.getTargetElement(); + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(targetElement); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection + .hidePortsAndHandlers(); + } + } + }, + start = { + id: 'menuStart', + items: [ + startCatchMarker, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + }, + { + id: "menuStartWebEntry", + text: "Web Entry".translate(), + icon: "mafe-menu-start-message-view", + //visible: false, + onClick: function (menuOption) { + var splitedID = menuOption.getMenuTargetElement().getID().split("-"), webEntry; + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + var webEntry; + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + webEntry = new WebEntry(menuOption.getMenuTargetElement()); + webEntry.render(); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + webEntry = new WebEntry(menuOption.getMenuTargetElement()); + webEntry.render(); + } + } + }, + { + id: "menuStartProperties", + text: "Properties".translate(), + icon: "mafe-menu-start-message-view", + onClick: function (menuOption) { + var a = menuOption.getMenuTargetElement(), message_window, + splitedID = menuOption.getMenuTargetElement().getID().split("-"); + switch (a.getEventMarker()) { + case "TIMER": + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.timerEventProperties(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.timerEventProperties(menuOption.getMenuTargetElement()); + } + break; + default : + var messageEventDefinition, + eventCurrent = menuOption.getMenuTargetElement(); + if (menuMessages[eventCurrent.evn_type][eventCurrent.evn_marker] !== undefined) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + width: 490, + title: 'Information'.translate(), + windowMessageType: 'info', + bodyHeight: 'auto', + message: menuMessages[eventCurrent.evn_type][eventCurrent.evn_marker], + footerItems: [ + { + text: 'Ok'.translate(), + handler: function () { + message_window.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + messageEventDefinition = new MessageEventDefinition(eventCurrent); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + messageEventDefinition = new MessageEventDefinition(eventCurrent); + } + } + } + } + } + ], + onShow: function (menu) { + var targetElement = menu.getTargetElement(), + shape, + propertyMap = ['MESSAGECATCH', 'TIMER']; + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(targetElement); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + if (targetElement.evn_marker == 'TIMER') { + } + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + if (targetElement.evn_marker === 'MESSAGECATCH') { + var dt = menu.getItems(); + for (var i = 0; i < dt.length; i += 1) { + if (dt[i].id === 'idReceiveMessage') { + dt[i].setVisible(true); + } + } + } + //disabled weebentry for others pmEvent no support + if (targetElement.getPorts().asArray().length) { + shape = targetElement.getPorts().getFirst().getConnection().getDestPort().parent; + if (shape && (shape instanceof PMActivity) && targetElement.evn_marker === "EMPTY") { + menu.items.find('id', 'menuStartWebEntry').enable(); + } else if (shape && (shape instanceof PMEvent) && shape.evn_marker === "EMAIL" + && targetElement.evn_marker === "EMPTY") { + menu.items.find('id', 'menuStartWebEntry').enable(); + } else { + menu.items.find('id', 'menuStartWebEntry').disable(); + } + } else { + menu.items.find('id', 'menuStartWebEntry').disable(); + } + + //Enable && Disabled - Properties + if (targetElement.evn_type === "START" && propertyMap.indexOf(targetElement.evn_marker) >= 0) { + menu.items.find('id', 'menuStartProperties').enable(); + } else { + menu.items.find('id', 'menuStartProperties').disable(); + } + }, + onHide: function (menu) { + var dt = menu.getItems(), i; + for (i = 0; i < dt.length; i += 1) { + if (dt[i].id === 'idReceiveMessage') { + dt[i].setVisible(false); + } + } + } + }, + end = { + id: 'menuEnd', + items: [ + endMarker, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + }, + { + id: "menuEndProperties", + text: "Properties".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + var a = menuOption.getMenuTargetElement(), message_window, + splitedID = menuOption.getMenuTargetElement().getID().split("-"); + switch (a.getEventMarker()) { + case "EMAIL": + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.emailEventProperties(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.emailEventProperties(menuOption.getMenuTargetElement()); + } + break; + default : + var messageEventDefinition, + eventCurrent = menuOption.getMenuTargetElement(); + if (menuMessages[eventCurrent.evn_type][eventCurrent.evn_marker] !== undefined) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + width: 490, + title: 'Information'.translate(), + windowMessageType: 'info', + bodyHeight: 'auto', + message: menuMessages[eventCurrent.evn_type][eventCurrent.evn_marker], + footerItems: [ + { + text: 'Ok'.translate(), + handler: function () { + message_window.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + messageEventDefinition = new MessageEventDefinition(eventCurrent); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + messageEventDefinition = new MessageEventDefinition(eventCurrent); + } + } + } + } + } + ], + onShow: function (menu) { + var propertyMap = ['MESSAGETHROW', 'EMAIL'], + targetElement = menu.getTargetElement(); + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(targetElement); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + + + //Enable && Disabled - Properties + if (targetElement.evn_type === "END" && propertyMap.indexOf(targetElement.evn_marker) >= 0) { + menu.items.find('id', 'menuEndProperties').enable(); + } else { + menu.items.find('id', 'menuEndProperties').disable(); + } + } + }, + selection = { + id: 'menuSelection', + items: [ + { + text: "Properties".translate(), + icon: "mafe-menu-properties-action" + }, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action" + } + ] + }, + evaluation = { + id: 'menuEvaluation', + items: [ + + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + alert("Working on this feature..."); + } + }, + { + text: "Properties".translate(), + icon: "mafe-menu-properties-action", + onClick: function (menuOption) { + alert("Working on this feature..."); + } + } + ] + }, + parallel = { + id: 'menuParallel', + items: [ + typeMenu, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + listeners: {}, + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + } + }, + exclusive = { + id: 'menuExclusive', + items: [ + typeMenu, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: "Delete".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + }, + { + text: "Properties".translate(), + icon: "mafe-menu-properties-action", + onClick: function (menuOption) { + PMDesigner.RoutingRule(menuOption.getMenuTargetElement()); + } + } + ], + onShow: function (menu) { + var element = menu.getTargetElement(), propertyOption; + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(element); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + if (menu.items) { + if (element && element.gat_direction) { + propertyOption = menu.items.find("text", "Properties"); + if (propertyOption) { + if (element.gat_direction === 'CONVERGING') { + propertyOption.disable(); + } else { + propertyOption.enable(); + + } + } + } + } + + } + }, + inclusive = { + id: 'menuInclusive', + items: [ + typeMenu, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + }, + { + text: 'Properties'.translate(), + icon: 'mafe-menu-properties-action', + onClick: function (menuOption) { + PMDesigner.RoutingRule(menuOption.getMenuTargetElement()); + } + } + ], + onShow: function (menu) { + var element = menu.getTargetElement(), propertyOption; + PMUI.getActiveCanvas().addToSelection(element); + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + + if (menu.items) { + if (element && element.gat_direction) { + propertyOption = menu.items.find("text", "Properties"); + if (propertyOption) { + if (element.gat_direction === 'CONVERGING') { + propertyOption.disable(); + } else { + propertyOption.enable(); + + } + } + } + } + } + }, + complex = { + id: 'menuComplex', + items: [ + typeMenu, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + }, + { + text: "Properties".translate(), + icon: "mafe-menu-properties-action", + onClick: function (menuOption) { + PMDesigner.complexRoutingRule(menuOption.getMenuTargetElement()); + } + } + ], + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + } + }, + group = { + id: 'menuLine', + items: [ + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + } + }, + dataObject = { + id: 'menuDataObject', + items: [ + { + id: "dataType", + text: "Data Type".translate(), + items: [ + { + id: "dataobject", + text: "Data Empty".translate(), + onClick: function (menuOption) { + menuOption.getMenuTargetElement().switchDataType('DATAOBJECT'); + } + }, + { + id: "datainput", + text: "Data Input".translate(), + onClick: function (menuOption) { + menuOption.getMenuTargetElement().switchDataType('DATAINPUT'); + } + }, + { + id: "dataoutput", + text: "Data Output".translate(), + onClick: function (menuOption) { + menuOption.getMenuTargetElement().switchDataType('DATAOUTPUT'); + } + } + ] + }, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + } + }, + dataStore = { + id: 'menuDataObject', + items: [ + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + } + }, + textAnnotation = { + id: 'menuDataObject', + items: [ + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + } + }, + intermediate = { + id: 'intermediate', + items: [ + intermediateCatchMarker, + intermediateThrowMarker, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + }, + { + id: "intermediateProperties", + text: "Properties".translate(), + icon: "mafe-menu-delete-action", + onClick: function (menuOption) { + var a = menuOption.getMenuTargetElement(), message_window, + splitedID = menuOption.getMenuTargetElement().getID().split("-"); + switch (a.getEventMarker()) { + case "EMAIL": + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.emailEventProperties(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.emailEventProperties(menuOption.getMenuTargetElement()); + } + break; + case "TIMER": + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + PMDesigner.timerEventProperties(menuOption.getMenuTargetElement()); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + PMDesigner.timerEventProperties(menuOption.getMenuTargetElement()); + } + break; + default : + var messageEventDefinition, + eventCurrent = menuOption.getMenuTargetElement(); + if (menuMessages[eventCurrent.evn_type][eventCurrent.evn_behavior][eventCurrent.evn_marker] !== undefined) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + width: 490, + title: 'Information'.translate(), + windowMessageType: 'info', + bodyHeight: 'auto', + message: menuMessages[eventCurrent.evn_type][eventCurrent.evn_behavior][eventCurrent.evn_marker], + footerItems: [ + { + text: 'Ok'.translate(), + handler: function () { + message_window.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + menuOption.parent.hide(); + if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { + PMDesigner.restApi.execute({ + data: JSON.stringify(PMDesigner.project.getDirtyObject()), + method: "update", + url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, + success: function (data, textStatus, xhr) { + PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); + PMDesigner.project.isSave = false; + //open property form + messageEventDefinition = new MessageEventDefinition(eventCurrent); + }, + error: function (xhr, textStatus, errorThrown) { + PMDesigner.project.listeners.failure(that, textStatus, xhr); + PMDesigner.project.isSave = false; + } + }); + } else { + messageEventDefinition = new MessageEventDefinition(eventCurrent); + } + } + } + + } + } + ], + onShow: function (menu) { + var targetElement = menu.getTargetElement(), + propertyEnabled = ['MESSAGECATCH', 'MESSAGETHROW', 'EMAIL', 'TIMER']; + + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + + if (targetElement.evn_behavior === 'CATCH') { + targetElement.menu.getItems()[0].setVisible(true); + targetElement.menu.getItems()[1].setVisible(false); + } else { + targetElement.menu.getItems()[0].setVisible(false); + targetElement.menu.getItems()[1].setVisible(true); + } + + //Enable && Disabled - Properties + if (propertyEnabled.indexOf(targetElement.evn_marker) >= 0) { + + menu.items.find('id', 'intermediateProperties').enable(); + } else { + menu.items.find('id', 'intermediateProperties').disable(); + } + } + }, + boundary = { + id: 'menuDataObject', + items: [ + boundaryCatchMarker, + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + onShow: function (menu) { + var targetElement = menu.getTargetElement(); + + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + + } + }, + participant = { + id: 'menuDataObject', + items: [ + { + text: "Edit Label".translate(), + icon: "mafe-menu-edit-label-action", + onClick: function (menuOption) { + menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); + menuOption.getMenuTargetElement().label.getFocus(); + } + }, + { + text: 'Delete'.translate(), + icon: 'mafe-menu-delete-action', + onClick: function (menuOption) { + PMUI.getActiveCanvas().removeElements(); + } + } + ], + onShow: function (menu) { + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); + if (PMUI.getActiveCanvas().currentConnection) { + PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); + } + PMUI.getActiveCanvas().hideDragConnectHandlers(); + PMUI.getActiveCanvas().hideAllFocusLabels(); + } + }; + var defaults = { + factory: { + products: { + 'CANVAS': canvas, + 'TASK': task, + 'SUB_PROCESS': subProcess, + 'START': start, + 'END': end, + 'SELECTION': selection, + 'EVALUATION': evaluation, + 'PARALLEL': parallel, + 'EXCLUSIVE': exclusive, + 'EVENTBASED': exclusive, + 'EXCLUSIVEEVENTBASED': exclusive, + 'PARALLELEVENTBASED': exclusive, + 'INCLUSIVE': inclusive, + 'COMPLEX': complex, + 'VERTICAL_LINE': group, + 'HORIZONTAL_LINE': group, + 'GROUP': group, + 'LANE': participant, + 'DATAOBJECT': dataObject, + 'DATASTORE': dataStore, + 'TEXT_ANNOTATION': textAnnotation, + 'V_LABEL': textAnnotation, + 'H_LABEL': textAnnotation, + 'INTERMEDIATE': intermediate, + 'BOUNDARY': boundary, + 'PARTICIPANT': participant, + 'POOL': participant + }, + + defaultProduct: 'START' + } + }; + + PMDesigner.contextMenuFactory = new ContextMenu(defaults.factory); + PMDesigner.getMenuFactory = function (type) { + if (prj_readonly === 'true') { + return {}; + } + return PMDesigner.contextMenuFactory.getProduct(type); + }; + /** + * Change task type marker + * @param menuOption + */ + function handlerMarkerType(menuOption) { + var result = true, + tempType = menuOption.getMenuTargetElement().getTaskType(); + menuOption.parent.hide(); + + menuOption.getMenuTargetElement().switchTaskType(menuOption.id.toUpperCase()); + + //validate if act loop type is parallel + if (menuOption.getMenuTargetElement().act_loop_type === "PARALLEL") { + handlerMarkerLoopType(menuOption, tempType) + } + + //to enable save button + PMDesigner.project.updateElement([]); + + } + + /** + * Change marker loop type + * @param menuOption + * @param type + * @returns {boolean} + */ + function handlerMarkerLoopType(menuOption, type) { + var message_window, + loopType = menuOption.id.toUpperCase(), + taskType = menuOption.getMenuTargetElement().act_task_type; + if (typeof type !== 'undefined' && type !== null) { + taskType = type; + } + + if (menuOption.getMenuTargetElement().act_loop_type === "PARALLEL") { + + message_window = new PMUI.ui.MessageWindow({ + id: "handlerMarkerType", + width: 490, + title: 'Parallel Marker Type'.translate(), + windowMessageType: 'warning', + bodyHeight: 'auto', + message: "The configuring of multiple instances will be lost".translate(), + footerItems: [ + { + text: 'Cancel'.translate(), + handler: function () { + menuOption.getMenuTargetElement().switchLoopType('PARALLEL'); + menuOption.getMenuTargetElement().switchTaskType(taskType); + message_window.close(); + return false; + }, + buttonType: "error" + }, + { + text: 'Continue'.translate(), + handler: function () { + try { + if (loopType == "loop" || loopType == "sequential") { + menuOption.getMenuTargetElement().switchLoopType(loopType.toUpperCase()); + } else { + menuOption.getMenuTargetElement().switchLoopType('EMPTY'); + } + PMDesigner.project.updateElement([]); + } catch (e) { + console.error("loop marker error", e.message); + } + message_window.close(); + return true; + }, + buttonType: "success" + } + + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + menuOption.parent.hide(); + menuOption.getMenuTargetElement().switchLoopType(loopType.toUpperCase()); + PMDesigner.project.updateElement([]); + return true; + } + } + +}()); + (function () { - /** - * @class PMUI.menu.ContextMenu - * Handles the context menu of designer - * contains all the menus for elements - * - * @extend PMUI.util.Factory - * @constructor - * This method creates a new instance of this object - * @param {Object} [settings] Constructor settings - */ - "use strict"; - var ContextMenu = function (settings) { - this.factory = null; - ContextMenu.prototype.init.call(this, settings); - }; + PMDesigner.shapeFactory = function (type, options) { + var customshape = null, + menuShape, + defaultOptions = null, + canvasName, + name, + id, + classEvent = "start", + pmCanvas = this.canvas, + corona = PMDesigner.defaultCrown, + wildcard; - ContextMenu.prototype.type = 'ContextMenu'; + canvasName = new IncrementNameCanvas(pmCanvas); + name = canvasName.get(type); - ContextMenu.prototype.family = 'ContextMenu'; + if (typeof options === 'undefined') { + options = {}; + if (type === 'START_MESSAGE') { + type = 'START'; + classEvent = "message"; + options.evn_marker = 'MESSAGECATCH'; + } + if (type === 'START_TIMER') { + type = 'START'; + classEvent = "timer"; + options.evn_marker = 'TIMER'; + } - /** - * Initializes the object. - * @param {Object} settings A JSON object with the config options. - * @private - */ - ContextMenu.prototype.init = function (settings) { - jQuery.extend(true, defaults, settings); - this.factory = new PMUI.util.Factory(defaults.factory); - }; + if (type === 'END_MESSAGE') { + type = 'END'; + classEvent = "message"; + options.evn_marker = 'MESSAGETHROW'; + } + if (type === 'END_EMAIL') { + type = 'END'; + classEvent = "email"; + options.evn_marker = 'EMAIL'; + options.evn_behavior = 'THROW'; + } + if (type === 'INTERMEDIATE_SENDMESSAGE') { + type = 'INTERMEDIATE'; + classEvent = "sendmessage"; + options.evn_marker = 'MESSAGETHROW'; + options.evn_behavior = 'THROW'; + } + if (type === 'INTERMEDIATE_RECEIVEMESSAGE') { + type = 'INTERMEDIATE'; + classEvent = "receivemessage"; + options.evn_marker = 'MESSAGECATCH'; + options.evn_behavior = 'CATCH'; + } + if (type === 'INTERMEDIATE_EMAIL') { + type = 'INTERMEDIATE'; + classEvent = "email"; + options.evn_marker = 'EMAIL'; + options.evn_behavior = 'THROW'; + } + if (type === 'INTERMEDIATE_TIMER') { + type = 'INTERMEDIATE'; + classEvent = "timer"; + options.evn_marker = 'TIMER'; + } + if (type === 'BOUNDARY_EVENT') { + type = 'BOUNDARY'; + classEvent = "receivemessage"; + options.evn_marker = 'EMPTY'; + options.evn_behavior = 'CATCH'; + } - /** - * Register a new context menu object into a product. - * - * Usage example: - * @example - * //Remember, this is an abstract class so it shouldn't be instantiate, - * //anyway we are instantiating it just for this example - * var additionalMenu = { - * id: "additionalMenu", - * text: "New Menu", - * onClick: function () { - * PMDesigner.msgWinWarning('This is a new Menu'); - * } - * }; - * // Assuming that you're using PMDesigner.contextMenuFactory as the default contextMenuFactory - * PMDesigner.contextMenuFactory.registerMenu("CANVAS", additionalMenu); - * - * @param {String} productName Name of the shape or product in factory. - * @param {Object} menu Object with menu values and actions. - * @private - */ - ContextMenu.prototype.registerMenu = function (productName, menu) { - if (typeof this.factory.products[productName] === 'undefined') { - console.log('Context Menu Warning: Cannot add Menu into: ' + productName + '. Please, review name.'); - } else { - if (this.factory.products[productName].items instanceof Array) { - this.factory.products[productName].items.push(menu); + switch (type) { + case 'COMPLEX': + case 'PARALLEL': + case 'EXCLUSIVE': + case 'EVENTBASED': + case 'EXCLUSIVEEVENTBASED': + case 'PARALLELEVENTBASED': + case 'INCLUSIVE': + options.gat_type = type; + break; } } - }; - - /** - * Removes context menu object from product. - * - * Usage example: - * @example - * // Assuming that you're using PMDesigner.contextMenuFactory as the default contextMenuFactory - * // this example removes Canvas gridLines option - * PMDesigner.contextMenuFactory.removeMenu("CANVAS", "id", "menuGridLines"); - * - * @param {String} product Name of the shape or product in factory. - * @param {String} id Key to look through product. - * @param {String} value Name of the elementValue. - * @private - */ - ContextMenu.prototype.removeMenu = function (product, id, value) { - if (typeof this.factory.products[product] !== 'undefined') { - this.factory.products[product].items = _.reject(this.factory.products[product].items, function (menuValue) { - return menuValue[id] === value; - }); - } else { - console.log('Context Menu Warning: Cannot find ' + product + ' Menu. Please, review name.'); + if (type === 'DATAOBJECT') { + type = 'DATAOBJECT'; + options.dat_object_type = 'dataobject'; + } + if (type === 'DATAINPUT') { + type = 'DATAOBJECT'; + options.dat_object_type = 'datainput'; + } + if (type === 'DATAOUTPUT') { + type = 'DATAOBJECT'; + options.dat_object_type = 'dataoutput'; } - }; - - /** - * Returns specific product. - * @param {String} type Name of product. - * @private - */ - ContextMenu.prototype.getProduct = function (type) { - return this.factory.products[type]; - }; - var menuMessages = { - 'START': { - 'TIMER': 'Please configure cron to create cases.'.translate(), - 'CONDITIONAL': 'Please configure cron to create cases in base to a condition.'.translate(), - 'SIGNALCATCH': 'Please configure cron to create cases in base to a signal.'.translate() - }, - 'INTERMEDIATE': { - 'CATCH': { - 'TIMER': 'Please configure cron to wait for time event.'.translate(), - 'CONDITIONAL': 'Please configure cron to wait for time condition.'.translate(), - 'SIGNALCATCH': 'Please configure script to wait for a signal.'.translate() - }, - 'THROW': { - 'SIGNALTHROW': 'Please configure a script to send a signal.'.translate() - } - }, - 'END': { - 'ERRORTHROW': 'Please configure script to end with error status.'.translate(), - 'SIGNALTHROW': 'Please configure script to send a signal.'.translate(), - 'TERMINATETHROW': 'Please configure script to terminate case.'.translate() + wildcard = [ + { + name: 'wildcard'.translate(), + className: 'mafe-wildcard', + onClick: null, + column: 2 } - }, - menu = {}, - rootMenu, - elementActivite, - typeMenu = { - text: "Gateway Type".translate(), - icon: "mafe-menu-properties-action", - id: "gatewaytype", - items: [ - { - id: "gatewayexclusive", - text: "Exclusive (XOR) Gateway".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeTypeTo('EXCLUSIVE'); - PMDesigner.project.updateElement([]); - } - }, - { - id: "gatewayparallel", - text: "Parallel (AND) Gateway".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeTypeTo('PARALLEL'); - PMDesigner.project.updateElement([]); - } - }, - { - id: "gatewayinclusive", - text: "Inclusive (OR) Gateway".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeTypeTo('INCLUSIVE'); - PMDesigner.project.updateElement([]); - } - } - ] - }, - endMarker = { - text: "End Event Type".translate(), - icon: "mafe-menu-properties-action", - id: "result", - items: [ - { - id: "endempty", - text: "Empty".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('EMPTY', 'Empty'); - PMDesigner.project.updateElement([]); - } - }, - { - id: "endemail", - text: "Email Message".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('EMAIL', 'Email Message'); - PMDesigner.project.updateElement([]); - } - }, - { - id: "endmessagethrow", - text: "Message".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('MESSAGETHROW', 'Message'); - PMDesigner.project.updateElement([]); - } - }, - { - id: "enderrorthrow", - text: "Error".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('ERRORTHROW', 'Error'); - PMDesigner.project.updateElement([]); - } - }, - { - id: "endsignalthrow", - text: "Signal".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('SIGNALTHROW', 'Signal'); - PMDesigner.project.updateElement([]); - } - }, - { - id: "endterminatethrow", - text: "Terminate".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('TERMINATETHROW', 'Terminate'); - PMDesigner.project.updateElement([]); - } - } - ] - }, - intermediateCatchMarker = { - text: "Intermediate Event Type".translate(), - icon: "mafe-menu-properties-action", - id: "trigger", - items: [ - { - id: "intermediatemessagecatch", - text: "Receive Message".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('MESSAGECATCH', 'Receive Message'); - PMDesigner.project.updateElement([]); - } - }, - { - id: "intermediatetimer", - text: "Timer".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('TIMER', 'Timer'); - PMDesigner.project.updateElement([]); - } - }, - { - id: "intermediateconditional", - text: "Conditional".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('CONDITIONAL', 'Conditional'); - PMDesigner.project.updateElement([]); - } - }, - { - id: "intermediatesignalcatch", - text: "Signal".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('SIGNALCATCH', 'Signal'); - PMDesigner.project.updateElement([]); - } - } - ] - }, - boundaryCatchMarker = { - text: "Boundary Event Type".translate(), - icon: "mafe-menu-properties-action", - id: "eventType", - items: [ - { - id: "messageCatch", - text: "Receive Message".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('MESSAGECATCH', 'Receive Message'); - } - }, - { - id: "boundaryTimer", - text: "Timer".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('TIMER', 'Timer'); - } - }, - { - id: "BoudaryConditional", - text: "Conditional".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('CONDITIONAL', 'Conditional'); - } - }, - { - id: "BoudarySignal", - text: "Signal".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('SIGNALCATCH', 'Signal'); - } - }, - { - id: "BoudaryError", - text: "Error".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('ERRORCATCH', 'Error'); - } - } - ] - }, - intermediateThrowMarker = { - text: "Intermediate Event Type".translate(), - icon: "mafe-menu-properties-action", - id: "result", - items: [ - { - id: "intermediateemail", - text: "Email Message".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('EMAIL', 'Email Message'); - PMDesigner.project.updateElement([]); - } - }, - { - id: "intermediatemessagethrow", - text: "Send Message".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('MESSAGETHROW', 'Send Message'); - PMDesigner.project.updateElement([]); - } - }, - { - id: "intermediatesignalthrow", - text: "Signal".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('SIGNALTHROW', 'Signal'); - PMDesigner.project.updateElement([]); - } - } - ] - }, - startCatchMarker = { - text: "Start Event Type".translate(), - icon: "mafe-menu-properties-action", - id: "trigger", - items: [ - { - id: "startempty", - text: "Empty".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('EMPTY', 'Empty'); - PMDesigner.project.updateElement([]); - } - }, - { - id: "startmessagecatch", - text: "Receive Message".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('MESSAGECATCH', 'Receive Message'); - rootMenu = menuOption.getRootMenu(); - rootMenu.getItems()[3].disable(); - PMDesigner.project.updateElement([]); - } - }, - { - id: "starttimer", - text: "Timer".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('TIMER', 'Timer'); - rootMenu = menuOption.getRootMenu(); - rootMenu.getItems()[3].disable(); - PMDesigner.project.updateElement([]); - } - }, - { - id: "startconditional", - text: "Conditional".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('CONDITIONAL', 'Conditional'); - rootMenu = menuOption.getRootMenu(); - rootMenu.getItems()[3].disable(); - PMDesigner.project.updateElement([]); - } - }, - { - id: "startsignalcatch", - text: "Signal".translate(), - onClick: function (menuOption) { - var targetElement = menuOption - .getMenuTargetElement(); - targetElement.changeMarkerTo('SIGNALCATCH', 'Signal'); - rootMenu = menuOption.getRootMenu(); - rootMenu.getItems()[3].disable(); - PMDesigner.project.updateElement([]); - } - } - ] - }, - canvas = { - id: "menuCanvas", - width: 150, - items: [ - { - id: "menuEditProcess", - text: "Edit Process".translate(), - onClick: function (menuOption) { - PMDesigner.propertiesProcess(); - } - }, - { - id: "menuGridLines", - text: "Enable Grid Lines".translate(), - onClick: function () { - var canvas = PMUI.getActiveCanvas(); - if (canvas.toogleGridLine()) { - this.setText("Disable Grid Lines".translate()); - } else { - this.setText("Enable Grid Lines".translate()); - } - } - } - ], - onShow: function (menu) { - var canvas = PMUI.getActiveCanvas(); - if (canvas.currentConnection) { - canvas.currentConnection.hidePortsAndHandlers(); - } - if (canvas.isGridLine) { - menu.items.find('id', 'menuGridLines').setText("Disable Grid Lines".translate()); - } + ]; - } - }, - task = { - id: "menuTask", - items: [ - { - id: "taskType", - text: "Task Type".translate(), - items: [ - { - id: "empty", - text: "Empty Task".translate(), - onClick: function (menuOption) { - handlerMarkerType(menuOption); - } - }, - { - id: "sendtask", - text: "Send Task".translate(), - onClick: function (menuOption) { - handlerMarkerType(menuOption); - } - }, + switch (type) { + case 'TASK': + defaultOptions = { + canvas: pmCanvas, + width: 150, + height: 75, + act_type: 'TASK', + act_name: name, + act_task_type: 'EMPTY', + act_loop_type: 'EMPTY', + minHeight: 30, + minWidth: 150, + maxHeight: 50, + maxWidth: 170, + container: "activity", + labels: [ { - id: "receivetask", - text: "Receive Task".translate(), - onClick: function (menuOption) { - handlerMarkerType(menuOption); - } - }, + message: name, + width: 0, + height: 0, + position: { + location: 'center', + diffX: 0, + diffY: 0 + }, + attachEvents: false + } + ], + layers: [ { - id: "usertask", - text: "User Task".translate(), - onClick: function (menuOption) { - handlerMarkerType(menuOption); + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [ + 'mafe-activity-task' + ] } }, { - id: "servicetask", - text: "Service Task".translate(), - onClick: function (menuOption) { - handlerMarkerType(menuOption); + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] } - }, - { - id: "scripttask", - text: "Script Task".translate(), - onClick: function (menuOption) { - handlerMarkerType(menuOption); + } + + ], + connectAtMiddlePoints: true, + resizeBehavior: 'activityResize', + resizeHandlers: { + type: "Rectangle", + total: 8, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' } }, - { - id: "manualtask", - text: "Manual Task".translate(), - onClick: function (menuOption) { - handlerMarkerType(menuOption); + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' } + } + }, + "drop": { + type: "pmactivitydrop", + selectors: [ + "#BOUNDARY_EVENT", + ".mafe-event-boundary", + ".dragConnectHandler" + ] + }, + markers: [ + { + markerType: 'USERTASK', + x: 10, + y: 10, + position: 0, + markerZoomClasses: [] }, { - id: "businessrule", - text: "Business Rule Task".translate(), - onClick: function (menuOption) { - handlerMarkerType(menuOption); + markerType: 'EMPTY', + x: 10, + y: 10, + position: 4, + markerZoomClasses: [] + } + ], + validatorMarker: { + width: 12, + height: 12, + position: 2, + errors: { + style: { + markerZoomClassesError: [ + "mafe-style-error-marker-7", + "mafe-style-error-marker-10", + "mafe-style-error-marker-14", + "mafe-style-error-marker-17", + "mafe-style-error-marker-21" + ], + markerZoomClassesWarning: [ + "mafe-style-warning-marker-7", + "mafe-style-warning-marker-10", + "mafe-style-warning-marker-14", + "mafe-style-warning-marker-17", + "mafe-style-warning-marker-21" + ] } } - ] - }, - { - id: "loopType", - text: "Marker Type".translate(), - items: [ + }, + corona: corona, + focusLabel: true + }; + jQuery.extend(true, defaultOptions, options); + defaultOptions.markers[0] + .markerZoomClasses = PMDesigner.updateMarkerLayerClasses(defaultOptions); + defaultOptions.markers[1] + .markerZoomClasses = PMDesigner.updateLoopLayerClasses(defaultOptions); + customshape = new PMActivity(defaultOptions); + break; + case 'SUB_PROCESS': + defaultOptions = { + canvas: pmCanvas, + width: 150, + height: 75, + act_type: 'SUB_PROCESS', + act_loop_type: 'EMPTY', + act_name: name, + act_task_type: 'COLLAPSED', + minHeight: 30, + minWidth: 150, + maxHeight: 50, + maxWidth: 170, + container: "activity", + labels: [ { - id: "empty", - text: "None".translate(), - onClick: function (menuOption) { - handlerMarkerLoopType(menuOption); - } - }, + message: name, + position: { + location: 'center', + diffX: 0, + diffY: 0 + }, + attachEvents: false + } + ], + layers: [ { - id: "loop", - text: "Loop".translate(), - onClick: function (menuOption) { - handlerMarkerLoopType(menuOption); + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [ + 'mafe-activity-subprocess' + ] } }, { - id: "parallel", - text: "Parallel".translate(), - onClick: function (menuOption) { - handlerMarkerLoopType(menuOption); + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + + ], + connectAtMiddlePoints: true, + resizeBehavior: 'activityResize', + resizeHandlers: { + type: "Rectangle", + total: 8, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' } }, - { - id: "sequential", - text: "Sequential".translate(), - onClick: function (menuOption) { - handlerMarkerLoopType(menuOption); + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' } } - ] - }, - { - id: "menuTaskSteps", - text: "Steps".translate(), - icon: "mafe-menu-task-steps", - onClick: function (menuOption) { - var splitedID = menuOption.getMenuTargetElement().getID().split("-"); - menuOption.parent.hide(); - if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { - PMDesigner.restApi.execute({ - data: JSON.stringify(PMDesigner.project.getDirtyObject()), - method: "update", - url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, - success: function (data, textStatus, xhr) { - PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); - PMDesigner.project.isSave = false; - //open property form - PMDesigner.act_name = menuOption.getMenuTargetElement().act_name; - PMDesigner.act_uid = menuOption.getMenuTargetElement().act_uid; - PMDesigner.stepsTask = new stepsTask(); - }, - error: function (xhr, textStatus, errorThrown) { - PMDesigner.project.listeners.failure(that, textStatus, xhr); - PMDesigner.project.isSave = false; - } - }); - } else { - PMDesigner.act_name = menuOption.getMenuTargetElement().act_name; - PMDesigner.act_uid = menuOption.getMenuTargetElement().act_uid; - PMDesigner.stepsTask = new stepsTask(); - } - } - }, - { - id: "menuTaskAssignedRules", - text: "Assignment Rules".translate(), - icon: "mafe-menu-users-action", - onClick: function (menuOption) { - var splitedID = menuOption.getMenuTargetElement().getID().split("-"); - menuOption.parent.hide(); - if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { - PMDesigner.restApi.execute({ - data: JSON.stringify(PMDesigner.project.getDirtyObject()), - method: "update", - url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, - success: function (data, textStatus, xhr) { - PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); - PMDesigner.project.isSave = false; - //open property form - PMDesigner.assigmentRules(menuOption.getMenuTargetElement()); - }, - error: function (xhr, textStatus, errorThrown) { - PMDesigner.project.listeners.failure(that, textStatus, xhr); - PMDesigner.project.isSave = false; - } - }); - } else { - PMDesigner.assigmentRules(menuOption.getMenuTargetElement()); - } - } - }, - { - text: "Edit Label".translate(), - icon: "mafe-menu-edit-label-action", - onClick: function (menuOption) { - menuOption.parent.hide(); - - menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); - menuOption.getMenuTargetElement().label.getFocus(); - } - }, - { - text: "Delete".translate(), - icon: "mafe-menu-delete-action", - onClick: function (menuOption) { - menuOption.parent.hide(); - - PMUI.getActiveCanvas().removeElements(); - } - }, - { - id: "menuTaskProperties", - text: "Properties".translate(), - icon: "mafe-menu-properties-action", - onClick: function (menuOption) { - var splitedID = menuOption.getMenuTargetElement().getID().split("-"); - menuOption.parent.hide(); - if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { - PMDesigner.restApi.execute({ - data: JSON.stringify(PMDesigner.project.getDirtyObject()), - method: "update", - url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, - success: function (data, textStatus, xhr) { - PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); - PMDesigner.project.isSave = false; - //open property form - PMDesigner.activityProperties(menuOption.getMenuTargetElement()); - }, - error: function (xhr, textStatus, errorThrown) { - PMDesigner.project.listeners.failure(that, textStatus, xhr); - PMDesigner.project.isSave = false; - } - }); - } else { - PMDesigner.activityProperties(menuOption.getMenuTargetElement()); + }, + "drop": { + type: "pmactivitydrop", + selectors: [ + "#BOUNDARY_EVENT", + ".mafe-event-boundary", + ".dragConnectHandler" + ] + }, + markers: [ + { + markerType: 'COLLAPSED', + x: 10, + y: 10, + position: 4, + markerZoomClasses: [ + "mafe-collapsed-marker-10", + "mafe-collapsed-marker-15", + "mafe-collapsed-marker-21", + "mafe-collapsed-marker-26", + "mafe-collapsed-marker-31" + ] } - } - } - ], - onShow: function (menu) { - var targetElement = menu.getTargetElement(); - PMUI.getActiveCanvas().emptyCurrentSelection(); - PMUI.getActiveCanvas().addToSelection(targetElement); - PMUI.getActiveCanvas().hideDragConnectHandlers(); - PMUI.getActiveCanvas().hideAllFocusLabels(); - if (PMUI.getActiveCanvas().currentConnection) { - PMUI.getActiveCanvas().currentConnection - .hidePortsAndHandlers(); - } - - if (targetElement.act_task_type == "SCRIPTTASK") { - menu.getItems()[1].setVisible(false); - menu.getItems()[2].setVisible(false); - menu.getItems()[3].setVisible(false); - } else { - menu.getItems()[1].setVisible(true); - menu.getItems()[2].setVisible(true); - menu.getItems()[3].setVisible(true); - } - - if (targetElement.act_task_type == "MANUALTASK" || targetElement.act_task_type == "USERTASK" || targetElement.act_task_type == "EMPTY") { - menu.getItems()[1].getItems()[2].setVisible(true); - } else { - menu.getItems()[1].getItems()[2].setVisible(false); - } - } - }, - subProcess = { - id: "menuSubProcess", - items: [ - { - text: "Edit Label".translate(), - icon: "mafe-menu-edit-label-action", - onClick: function (menuOption) { - menuOption.parent.hide(); - - menuOption.getMenuTargetElement().label.canvas - .hideAllFocusLabels(); - menuOption.getMenuTargetElement().label.getFocus(); - } - }, - { - text: "Delete Routing Rule".translate(), - icon: "mafe-menu-delete-rules-action", - onClick: function (menuOption) { - var splitedID = menuOption.getMenuTargetElement().getID().split("-"); - menuOption.parent.hide(); - if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { - PMDesigner.restApi.execute({ - data: JSON.stringify(PMDesigner.project.getDirtyObject()), - method: "update", - url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, - success: function (data, textStatus, xhr) { - PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); - PMDesigner.project.isSave = false; - //open property form - PMDesigner.RoutingRuleDeleteAllFlow(menuOption.getMenuTargetElement()); - }, - error: function (xhr, textStatus, errorThrown) { - PMDesigner.project.listeners.failure(that, textStatus, xhr); - PMDesigner.project.isSave = false; - } - }); - } else { - PMDesigner.RoutingRuleDeleteAllFlow(menuOption.getMenuTargetElement()); + ], + validatorMarker: { + width: 12, + height: 12, + position: 2, + errors: { + style: { + markerZoomClassesError: [ + "mafe-style-error-marker-7", + "mafe-style-error-marker-10", + "mafe-style-error-marker-14", + "mafe-style-error-marker-17", + "mafe-style-error-marker-21" + ] + } } - } - }, - { - text: "Delete".translate(), - icon: "mafe-menu-delete-action", - onClick: function (menuOption) { - menuOption.parent.hide(); - - PMUI.getActiveCanvas().removeElements(); - } - }, - { - id: "menuSubProperties", - text: "Properties".translate(), - icon: "mafe-menu-properties-action", - onClick: function (menuOption) { - var splitedID = menuOption.getMenuTargetElement().getID().split("-"); - menuOption.parent.hide(); - if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { - PMDesigner.restApi.execute({ - data: JSON.stringify(PMDesigner.project.getDirtyObject()), - method: "update", - url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, - success: function (data, textStatus, xhr) { - PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); - PMDesigner.project.isSave = false; - //open property form - PMDesigner.propertiesSubProcess(menuOption - .getMenuTargetElement(menuOption.getMenuTargetElement())); - - }, - error: function (xhr, textStatus, errorThrown) { - PMDesigner.project.listeners.failure(that, textStatus, xhr); - PMDesigner.project.isSave = false; - } - }); - } else { - PMDesigner.propertiesSubProcess(menuOption - .getMenuTargetElement(menuOption.getMenuTargetElement())); - - } - } - } - ], - onShow: function (menu) { - var targetElement = menu.getTargetElement(); - PMUI.getActiveCanvas().emptyCurrentSelection(); - PMUI.getActiveCanvas().addToSelection(targetElement); - PMUI.getActiveCanvas().hideDragConnectHandlers(); - PMUI.getActiveCanvas().hideAllFocusLabels(); - if (PMUI.getActiveCanvas().currentConnection) { - PMUI.getActiveCanvas().currentConnection - .hidePortsAndHandlers(); - } - } - }, - start = { - id: 'menuStart', - items: [ - startCatchMarker, - { - text: "Edit Label".translate(), - icon: "mafe-menu-edit-label-action", - onClick: function (menuOption) { - menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); - menuOption.getMenuTargetElement().label.getFocus(); - } - }, - { - text: "Delete".translate(), - icon: "mafe-menu-delete-action", - onClick: function (menuOption) { - PMUI.getActiveCanvas().removeElements(); - } - }, - { - id: "menuStartWebEntry", - text: "Web Entry".translate(), - icon: "mafe-menu-start-message-view", - //visible: false, - onClick: function (menuOption) { - var splitedID = menuOption.getMenuTargetElement().getID().split("-"), webEntry; - menuOption.parent.hide(); - if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { - PMDesigner.restApi.execute({ - data: JSON.stringify(PMDesigner.project.getDirtyObject()), - method: "update", - url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, - success: function (data, textStatus, xhr) { - var webEntry; - PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); - PMDesigner.project.isSave = false; - //open property form - webEntry = new WebEntry(menuOption.getMenuTargetElement()); - webEntry.render(); - }, - error: function (xhr, textStatus, errorThrown) { - PMDesigner.project.listeners.failure(that, textStatus, xhr); - PMDesigner.project.isSave = false; - } - }); - } else { - webEntry = new WebEntry(menuOption.getMenuTargetElement()); - webEntry.render(); - } - } - }, - { - id: "menuStartProperties", - text: "Properties".translate(), - icon: "mafe-menu-start-message-view", - onClick: function (menuOption) { - var a = menuOption.getMenuTargetElement(), message_window, - splitedID = menuOption.getMenuTargetElement().getID().split("-"); - switch (a.getEventMarker()) { - case "TIMER": - menuOption.parent.hide(); - if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { - PMDesigner.restApi.execute({ - data: JSON.stringify(PMDesigner.project.getDirtyObject()), - method: "update", - url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, - success: function (data, textStatus, xhr) { - PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); - PMDesigner.project.isSave = false; - //open property form - PMDesigner.timerEventProperties(menuOption.getMenuTargetElement()); - }, - error: function (xhr, textStatus, errorThrown) { - PMDesigner.project.listeners.failure(that, textStatus, xhr); - PMDesigner.project.isSave = false; - } - }); - } else { - PMDesigner.timerEventProperties(menuOption.getMenuTargetElement()); - } - break; - default : - var messageEventDefinition, - eventCurrent = menuOption.getMenuTargetElement(); - if (menuMessages[eventCurrent.evn_type][eventCurrent.evn_marker] !== undefined) { - message_window = new PMUI.ui.MessageWindow({ - id: "cancelMessageTriggers", - width: 490, - title: 'Information'.translate(), - windowMessageType: 'info', - bodyHeight: 'auto', - message: menuMessages[eventCurrent.evn_type][eventCurrent.evn_marker], - footerItems: [ - { - text: 'Ok'.translate(), - handler: function () { - message_window.close(); - }, - buttonType: "success" - } - ] - }); - message_window.open(); - message_window.showFooter(); - } else { - menuOption.parent.hide(); - if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { - PMDesigner.restApi.execute({ - data: JSON.stringify(PMDesigner.project.getDirtyObject()), - method: "update", - url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, - success: function (data, textStatus, xhr) { - PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); - PMDesigner.project.isSave = false; - //open property form - messageEventDefinition = new MessageEventDefinition(eventCurrent); - }, - error: function (xhr, textStatus, errorThrown) { - PMDesigner.project.listeners.failure(that, textStatus, xhr); - PMDesigner.project.isSave = false; - } - }); - } else { - messageEventDefinition = new MessageEventDefinition(eventCurrent); - } - } - } - } - } - ], - onShow: function (menu) { - var targetElement = menu.getTargetElement(), - shape, - propertyMap = ['MESSAGECATCH', 'TIMER']; - PMUI.getActiveCanvas().emptyCurrentSelection(); - PMUI.getActiveCanvas().addToSelection(targetElement); - PMUI.getActiveCanvas().hideDragConnectHandlers(); - PMUI.getActiveCanvas().hideAllFocusLabels(); - if (targetElement.evn_marker == 'TIMER') { - } - if (PMUI.getActiveCanvas().currentConnection) { - PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); - } - if (targetElement.evn_marker === 'MESSAGECATCH') { - var dt = menu.getItems(); - for (var i = 0; i < dt.length; i += 1) { - if (dt[i].id === 'idReceiveMessage') { - dt[i].setVisible(true); - } - } - } - //disabled weebentry for others pmEvent no support - if (targetElement.getPorts().asArray().length) { - shape = targetElement.getPorts().getFirst().getConnection().getDestPort().parent; - if (shape && (shape instanceof PMActivity) && targetElement.evn_marker === "EMPTY") { - menu.items.find('id', 'menuStartWebEntry').enable(); - } else if (shape && (shape instanceof PMEvent) && shape.evn_marker === "EMAIL" - && targetElement.evn_marker === "EMPTY") { - menu.items.find('id', 'menuStartWebEntry').enable(); - } else { - menu.items.find('id', 'menuStartWebEntry').disable(); - } - } else { - menu.items.find('id', 'menuStartWebEntry').disable(); - } - - //Enable && Disabled - Properties - if (targetElement.evn_type === "START" && propertyMap.indexOf(targetElement.evn_marker) >= 0) { - menu.items.find('id', 'menuStartProperties').enable(); - } else { - menu.items.find('id', 'menuStartProperties').disable(); - } - }, - onHide: function (menu) { - var dt = menu.getItems(), i; - for (i = 0; i < dt.length; i += 1) { - if (dt[i].id === 'idReceiveMessage') { - dt[i].setVisible(false); - } - } - } - }, - end = { - id: 'menuEnd', - items: [ - endMarker, - { - text: "Edit Label".translate(), - icon: "mafe-menu-edit-label-action", - onClick: function (menuOption) { - menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); - menuOption.getMenuTargetElement().label.getFocus(); - } - }, - { - text: "Delete".translate(), - icon: "mafe-menu-delete-action", - onClick: function (menuOption) { - PMUI.getActiveCanvas().removeElements(); - } - }, - { - id: "menuEndProperties", - text: "Properties".translate(), - icon: "mafe-menu-delete-action", - onClick: function (menuOption) { - var a = menuOption.getMenuTargetElement(), message_window, - splitedID = menuOption.getMenuTargetElement().getID().split("-"); - switch (a.getEventMarker()) { - case "EMAIL": - menuOption.parent.hide(); - if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { - PMDesigner.restApi.execute({ - data: JSON.stringify(PMDesigner.project.getDirtyObject()), - method: "update", - url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, - success: function (data, textStatus, xhr) { - PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); - PMDesigner.project.isSave = false; - //open property form - PMDesigner.emailEventProperties(menuOption.getMenuTargetElement()); - }, - error: function (xhr, textStatus, errorThrown) { - PMDesigner.project.listeners.failure(that, textStatus, xhr); - PMDesigner.project.isSave = false; - } - }); - } else { - PMDesigner.emailEventProperties(menuOption.getMenuTargetElement()); - } - break; - default : - var messageEventDefinition, - eventCurrent = menuOption.getMenuTargetElement(); - if (menuMessages[eventCurrent.evn_type][eventCurrent.evn_marker] !== undefined) { - message_window = new PMUI.ui.MessageWindow({ - id: "cancelMessageTriggers", - width: 490, - title: 'Information'.translate(), - windowMessageType: 'info', - bodyHeight: 'auto', - message: menuMessages[eventCurrent.evn_type][eventCurrent.evn_marker], - footerItems: [ - { - text: 'Ok'.translate(), - handler: function () { - message_window.close(); - }, - buttonType: "success" - } - ] - }); - message_window.open(); - message_window.showFooter(); - } else { - if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { - PMDesigner.restApi.execute({ - data: JSON.stringify(PMDesigner.project.getDirtyObject()), - method: "update", - url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, - success: function (data, textStatus, xhr) { - PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); - PMDesigner.project.isSave = false; - //open property form - messageEventDefinition = new MessageEventDefinition(eventCurrent); - }, - error: function (xhr, textStatus, errorThrown) { - PMDesigner.project.listeners.failure(that, textStatus, xhr); - PMDesigner.project.isSave = false; - } - }); - } else { - messageEventDefinition = new MessageEventDefinition(eventCurrent); - } - } - } - } - } - ], - onShow: function (menu) { - var propertyMap = ['MESSAGETHROW', 'EMAIL'], - targetElement = menu.getTargetElement(); - PMUI.getActiveCanvas().emptyCurrentSelection(); - PMUI.getActiveCanvas().addToSelection(targetElement); - PMUI.getActiveCanvas().hideDragConnectHandlers(); - PMUI.getActiveCanvas().hideAllFocusLabels(); - if (PMUI.getActiveCanvas().currentConnection) { - PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); - } - - - //Enable && Disabled - Properties - if (targetElement.evn_type === "END" && propertyMap.indexOf(targetElement.evn_marker) >= 0) { - menu.items.find('id', 'menuEndProperties').enable(); - } else { - menu.items.find('id', 'menuEndProperties').disable(); - } - } - }, - selection = { - id: 'menuSelection', - items: [ - { - text: "Properties".translate(), - icon: "mafe-menu-properties-action" - }, - { - text: "Edit Label".translate(), - icon: "mafe-menu-edit-label-action", - onClick: function (menuOption) { - menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); - menuOption.getMenuTargetElement().label.getFocus(); - } - }, - { - text: "Delete".translate(), - icon: "mafe-menu-delete-action" - } - ] - }, - evaluation = { - id: 'menuEvaluation', - items: [ - - { - text: "Edit Label".translate(), - icon: "mafe-menu-edit-label-action", - onClick: function (menuOption) { - menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); - menuOption.getMenuTargetElement().label.getFocus(); - } - }, - { - text: "Delete".translate(), - icon: "mafe-menu-delete-action", - onClick: function (menuOption) { - alert("Working on this feature..."); - } - }, - { - text: "Properties".translate(), - icon: "mafe-menu-properties-action", - onClick: function (menuOption) { - alert("Working on this feature..."); - } - } - ] - }, - parallel = { - id: 'menuParallel', - items: [ - typeMenu, - { - text: "Edit Label".translate(), - icon: "mafe-menu-edit-label-action", - onClick: function (menuOption) { - menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); - menuOption.getMenuTargetElement().label.getFocus(); - } - }, - { - text: 'Delete'.translate(), - icon: 'mafe-menu-delete-action', - onClick: function (menuOption) { - PMUI.getActiveCanvas().removeElements(); - } - } - ], - listeners: {}, - onShow: function (menu) { - PMUI.getActiveCanvas().emptyCurrentSelection(); - PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); - PMUI.getActiveCanvas().hideDragConnectHandlers(); - PMUI.getActiveCanvas().hideAllFocusLabels(); - if (PMUI.getActiveCanvas().currentConnection) { - PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); - } - } - }, - exclusive = { - id: 'menuExclusive', - items: [ - typeMenu, - { - text: "Edit Label".translate(), - icon: "mafe-menu-edit-label-action", - onClick: function (menuOption) { - menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); - menuOption.getMenuTargetElement().label.getFocus(); - } - }, - { - text: "Delete".translate(), - icon: "mafe-menu-delete-action", - onClick: function (menuOption) { - PMUI.getActiveCanvas().removeElements(); - } - }, - { - text: "Properties".translate(), - icon: "mafe-menu-properties-action", - onClick: function (menuOption) { - PMDesigner.RoutingRule(menuOption.getMenuTargetElement()); - } - } - ], - onShow: function (menu) { - var element = menu.getTargetElement(), propertyOption; - PMUI.getActiveCanvas().emptyCurrentSelection(); - PMUI.getActiveCanvas().addToSelection(element); - PMUI.getActiveCanvas().hideDragConnectHandlers(); - PMUI.getActiveCanvas().hideAllFocusLabels(); - if (PMUI.getActiveCanvas().currentConnection) { - PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); - } - if (menu.items) { - if (element && element.gat_direction) { - propertyOption = menu.items.find("text", "Properties"); - if (propertyOption) { - if (element.gat_direction === 'CONVERGING') { - propertyOption.disable(); - } else { - propertyOption.enable(); - - } - } - } - } - - } - }, - inclusive = { - id: 'menuInclusive', - items: [ - typeMenu, - { - text: "Edit Label".translate(), - icon: "mafe-menu-edit-label-action", - onClick: function (menuOption) { - menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); - menuOption.getMenuTargetElement().label.getFocus(); - } - }, - { - text: 'Delete'.translate(), - icon: 'mafe-menu-delete-action', - onClick: function (menuOption) { - PMUI.getActiveCanvas().removeElements(); - } - }, - { - text: 'Properties'.translate(), - icon: 'mafe-menu-properties-action', - onClick: function (menuOption) { - PMDesigner.RoutingRule(menuOption.getMenuTargetElement()); - } - } - ], - onShow: function (menu) { - var element = menu.getTargetElement(), propertyOption; - PMUI.getActiveCanvas().addToSelection(element); - PMUI.getActiveCanvas().hideDragConnectHandlers(); - PMUI.getActiveCanvas().hideAllFocusLabels(); - - if (menu.items) { - if (element && element.gat_direction) { - propertyOption = menu.items.find("text", "Properties"); - if (propertyOption) { - if (element.gat_direction === 'CONVERGING') { - propertyOption.disable(); - } else { - propertyOption.enable(); - + }, + corona: corona, + focusLabel: true + }; + jQuery.extend(true, defaultOptions, options); + defaultOptions.markers[0] + .markerZoomClasses = PMDesigner.updateMarkerLayerClasses(defaultOptions); + customshape = new PMActivity(defaultOptions); + break; + case 'START': + defaultOptions = { + canvas: pmCanvas, + width: 33, + height: 33, + evn_type: 'START', + evn_name: '', + evn_marker: 'EMPTY', + evn_behavior: 'catch', + evn_message: 'LEAD', + labels: [ + { + message: '', + visible: true, + width: 100, + position: { + location: 'bottom', + diffX: 0, + diffY: 13 } } - } - } - } - }, - complex = { - id: 'menuComplex', - items: [ - typeMenu, - { - text: "Edit Label".translate(), - icon: "mafe-menu-edit-label-action", - onClick: function (menuOption) { - menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); - menuOption.getMenuTargetElement().label.getFocus(); - } - }, - { - text: 'Delete'.translate(), - icon: 'mafe-menu-delete-action', - onClick: function (menuOption) { - PMUI.getActiveCanvas().removeElements(); - } - }, - { - text: "Properties".translate(), - icon: "mafe-menu-properties-action", - onClick: function (menuOption) { - PMDesigner.complexRoutingRule(menuOption.getMenuTargetElement()); - } - } - ], - onShow: function (menu) { - PMUI.getActiveCanvas().emptyCurrentSelection(); - PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); - if (PMUI.getActiveCanvas().currentConnection) { - PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); - } - PMUI.getActiveCanvas().hideDragConnectHandlers(); - PMUI.getActiveCanvas().hideAllFocusLabels(); - } - }, - group = { - id: 'menuLine', - items: [ - { - text: "Edit Label".translate(), - icon: "mafe-menu-edit-label-action", - onClick: function (menuOption) { - menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); - menuOption.getMenuTargetElement().label.getFocus(); - } - }, - { - text: 'Delete'.translate(), - icon: 'mafe-menu-delete-action', - onClick: function (menuOption) { - PMUI.getActiveCanvas().removeElements(); - } - } - ], - onShow: function (menu) { - PMUI.getActiveCanvas().emptyCurrentSelection(); - PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); - if (PMUI.getActiveCanvas().currentConnection) { - PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); - } - PMUI.getActiveCanvas().hideDragConnectHandlers(); - PMUI.getActiveCanvas().hideAllFocusLabels(); - } - }, - dataObject = { - id: 'menuDataObject', - items: [ - { - id: "dataType", - text: "Data Type".translate(), - items: [ + ], + style: { + cssClasses: ['mafe-event-start'] + }, + layers: [ { - id: "dataobject", - text: "Data Empty".translate(), - onClick: function (menuOption) { - menuOption.getMenuTargetElement().switchDataType('DATAOBJECT'); - } + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [] + }, + zoomSprites: [ + 'mafe-event-start-empty-16', + 'mafe-event-start-empty-24', + 'mafe-event-start-empty-33', + 'mafe-event-start-empty-41', + 'mafe-event-start-empty-49' + ] }, { - id: "datainput", - text: "Data Input".translate(), - onClick: function (menuOption) { - menuOption.getMenuTargetElement().switchDataType('DATAINPUT'); + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, + style: { + cssClasses: [] + } + } + ], + connectAtMiddlePoints: true, + resizeBehavior: 'NoResize', + resizeHandlers: { + type: "Rectangle", + total: 4, + resizableStyle: { + cssProperties: { + 'background-color': "rgb(0, 255, 0)", + 'border': '1px solid black' } }, - { - id: "dataoutput", - text: "Data Output".translate(), - onClick: function (menuOption) { - menuOption.getMenuTargetElement().switchDataType('DATAOUTPUT'); + nonResizableStyle: { + cssProperties: { + 'background-color': "white", + 'border': '1px solid black' } } - ] - }, - { - text: "Edit Label".translate(), - icon: "mafe-menu-edit-label-action", - onClick: function (menuOption) { - menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); - menuOption.getMenuTargetElement().label.getFocus(); - } - }, - { - text: 'Delete'.translate(), - icon: 'mafe-menu-delete-action', - onClick: function (menuOption) { - PMUI.getActiveCanvas().removeElements(); - } - } - ], - onShow: function (menu) { - PMUI.getActiveCanvas().emptyCurrentSelection(); - PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); - if (PMUI.getActiveCanvas().currentConnection) { - PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); - } - PMUI.getActiveCanvas().hideDragConnectHandlers(); - PMUI.getActiveCanvas().hideAllFocusLabels(); - } - }, - dataStore = { - id: 'menuDataObject', - items: [ - { - text: "Edit Label".translate(), - icon: "mafe-menu-edit-label-action", - onClick: function (menuOption) { - menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); - menuOption.getMenuTargetElement().label.getFocus(); - } - }, - { - text: 'Delete'.translate(), - icon: 'mafe-menu-delete-action', - onClick: function (menuOption) { - PMUI.getActiveCanvas().removeElements(); - } - } - ], - onShow: function (menu) { - PMUI.getActiveCanvas().emptyCurrentSelection(); - PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); - if (PMUI.getActiveCanvas().currentConnection) { - PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); - } - PMUI.getActiveCanvas().hideDragConnectHandlers(); - PMUI.getActiveCanvas().hideAllFocusLabels(); - } - }, - textAnnotation = { - id: 'menuDataObject', - items: [ - { - text: "Edit Label".translate(), - icon: "mafe-menu-edit-label-action", - onClick: function (menuOption) { - menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); - menuOption.getMenuTargetElement().label.getFocus(); - } - }, - { - text: 'Delete'.translate(), - icon: 'mafe-menu-delete-action', - onClick: function (menuOption) { - PMUI.getActiveCanvas().removeElements(); - } - } - ], - onShow: function (menu) { - PMUI.getActiveCanvas().emptyCurrentSelection(); - PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); - if (PMUI.getActiveCanvas().currentConnection) { - PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); - } - PMUI.getActiveCanvas().hideDragConnectHandlers(); - PMUI.getActiveCanvas().hideAllFocusLabels(); - } - }, - intermediate = { - id: 'intermediate', - items: [ - intermediateCatchMarker, - intermediateThrowMarker, - { - text: "Edit Label".translate(), - icon: "mafe-menu-edit-label-action", - onClick: function (menuOption) { - menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); - menuOption.getMenuTargetElement().label.getFocus(); - } - }, - { - text: 'Delete'.translate(), - icon: 'mafe-menu-delete-action', - onClick: function (menuOption) { - PMUI.getActiveCanvas().removeElements(); - } - }, - { - id: "intermediateProperties", - text: "Properties".translate(), - icon: "mafe-menu-delete-action", - onClick: function (menuOption) { - var a = menuOption.getMenuTargetElement(), message_window, - splitedID = menuOption.getMenuTargetElement().getID().split("-"); - switch (a.getEventMarker()) { - case "EMAIL": - menuOption.parent.hide(); - if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { - PMDesigner.restApi.execute({ - data: JSON.stringify(PMDesigner.project.getDirtyObject()), - method: "update", - url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, - success: function (data, textStatus, xhr) { - PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); - PMDesigner.project.isSave = false; - //open property form - PMDesigner.emailEventProperties(menuOption.getMenuTargetElement()); - }, - error: function (xhr, textStatus, errorThrown) { - PMDesigner.project.listeners.failure(that, textStatus, xhr); - PMDesigner.project.isSave = false; - } - }); - } else { - PMDesigner.emailEventProperties(menuOption.getMenuTargetElement()); - } - break; - case "TIMER": - menuOption.parent.hide(); - if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { - PMDesigner.restApi.execute({ - data: JSON.stringify(PMDesigner.project.getDirtyObject()), - method: "update", - url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, - success: function (data, textStatus, xhr) { - PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); - PMDesigner.project.isSave = false; - //open property form - PMDesigner.timerEventProperties(menuOption.getMenuTargetElement()); - }, - error: function (xhr, textStatus, errorThrown) { - PMDesigner.project.listeners.failure(that, textStatus, xhr); - PMDesigner.project.isSave = false; - } - }); - } else { - PMDesigner.timerEventProperties(menuOption.getMenuTargetElement()); - } - break; - default : - var messageEventDefinition, - eventCurrent = menuOption.getMenuTargetElement(); - if (menuMessages[eventCurrent.evn_type][eventCurrent.evn_behavior][eventCurrent.evn_marker] !== undefined) { - message_window = new PMUI.ui.MessageWindow({ - id: "cancelMessageTriggers", - width: 490, - title: 'Information'.translate(), - windowMessageType: 'info', - bodyHeight: 'auto', - message: menuMessages[eventCurrent.evn_type][eventCurrent.evn_behavior][eventCurrent.evn_marker], - footerItems: [ - { - text: 'Ok'.translate(), - handler: function () { - message_window.close(); - }, - buttonType: "success" - } - ] - }); - message_window.open(); - message_window.showFooter(); - } else { - menuOption.parent.hide(); - if ((splitedID && splitedID[0] === 'pmui') || PMDesigner.project.isDirty()) { - PMDesigner.restApi.execute({ - data: JSON.stringify(PMDesigner.project.getDirtyObject()), - method: "update", - url: HTTP_SERVER_HOSTNAME + "/api/1.0/" + WORKSPACE + "/project/" + PMDesigner.project.id, - success: function (data, textStatus, xhr) { - PMDesigner.project.listeners.success(PMDesigner.project, textStatus, data); - PMDesigner.project.isSave = false; - //open property form - messageEventDefinition = new MessageEventDefinition(eventCurrent); - }, - error: function (xhr, textStatus, errorThrown) { - PMDesigner.project.listeners.failure(that, textStatus, xhr); - PMDesigner.project.isSave = false; - } - }); - } else { - messageEventDefinition = new MessageEventDefinition(eventCurrent); - } - } + }, + "drop": { + type: "pmconnection", + selectors: ['.dragConnectHandler'] + }, + validatorMarker: { + width: 12, + height: 12, + position: 2, + errors: { + style: { + markerZoomClassesError: [ + "mafe-style-error-marker-7", + "mafe-style-error-marker-10", + "mafe-style-error-marker-14", + "mafe-style-error-marker-17", + "mafe-style-error-marker-21" + ] + } } - - } - } - ], - onShow: function (menu) { - var targetElement = menu.getTargetElement(), - propertyEnabled = ['MESSAGECATCH', 'MESSAGETHROW', 'EMAIL', 'TIMER']; - - PMUI.getActiveCanvas().emptyCurrentSelection(); - PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); - if (PMUI.getActiveCanvas().currentConnection) { - PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); - } - PMUI.getActiveCanvas().hideDragConnectHandlers(); - PMUI.getActiveCanvas().hideAllFocusLabels(); - - if (targetElement.evn_behavior === 'CATCH') { - targetElement.menu.getItems()[0].setVisible(true); - targetElement.menu.getItems()[1].setVisible(false); - } else { - targetElement.menu.getItems()[0].setVisible(false); - targetElement.menu.getItems()[1].setVisible(true); - } - - //Enable && Disabled - Properties - if (propertyEnabled.indexOf(targetElement.evn_marker) >= 0) { - - menu.items.find('id', 'intermediateProperties').enable(); - } else { - menu.items.find('id', 'intermediateProperties').disable(); - } - } - }, - boundary = { - id: 'menuDataObject', - items: [ - boundaryCatchMarker, - { - text: "Edit Label".translate(), - icon: "mafe-menu-edit-label-action", - onClick: function (menuOption) { - menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); - menuOption.getMenuTargetElement().label.getFocus(); - } - }, - { - text: 'Delete'.translate(), - icon: 'mafe-menu-delete-action', - onClick: function (menuOption) { - PMUI.getActiveCanvas().removeElements(); - } - } - ], - onShow: function (menu) { - var targetElement = menu.getTargetElement(); - - PMUI.getActiveCanvas().emptyCurrentSelection(); - PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); - if (PMUI.getActiveCanvas().currentConnection) { - PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); - } - PMUI.getActiveCanvas().hideDragConnectHandlers(); - PMUI.getActiveCanvas().hideAllFocusLabels(); - - } - }, - participant = { - id: 'menuDataObject', - items: [ - { - text: "Edit Label".translate(), - icon: "mafe-menu-edit-label-action", - onClick: function (menuOption) { - menuOption.getMenuTargetElement().label.canvas.hideAllFocusLabels(); - menuOption.getMenuTargetElement().label.getFocus(); - } - }, - { - text: 'Delete'.translate(), - icon: 'mafe-menu-delete-action', - onClick: function (menuOption) { - PMUI.getActiveCanvas().removeElements(); - } - } - ], - onShow: function (menu) { - PMUI.getActiveCanvas().emptyCurrentSelection(); - PMUI.getActiveCanvas().addToSelection(menu.getTargetElement()); - if (PMUI.getActiveCanvas().currentConnection) { - PMUI.getActiveCanvas().currentConnection.hidePortsAndHandlers(); - } - PMUI.getActiveCanvas().hideDragConnectHandlers(); - PMUI.getActiveCanvas().hideAllFocusLabels(); - } - }; - var defaults = { - factory: { - products: { - 'CANVAS': canvas, - 'TASK': task, - 'SUB_PROCESS': subProcess, - 'START': start, - 'END': end, - 'SELECTION': selection, - 'EVALUATION': evaluation, - 'PARALLEL': parallel, - 'EXCLUSIVE': exclusive, - 'EVENTBASED': exclusive, - 'EXCLUSIVEEVENTBASED': exclusive, - 'PARALLELEVENTBASED': exclusive, - 'INCLUSIVE': inclusive, - 'COMPLEX': complex, - 'VERTICAL_LINE': group, - 'HORIZONTAL_LINE': group, - 'GROUP': group, - 'LANE': participant, - 'DATAOBJECT': dataObject, - 'DATASTORE': dataStore, - 'TEXT_ANNOTATION': textAnnotation, - 'V_LABEL': textAnnotation, - 'H_LABEL': textAnnotation, - 'INTERMEDIATE': intermediate, - 'BOUNDARY': boundary, - 'PARTICIPANT': participant, - 'POOL': participant - }, - - defaultProduct: 'START' - } - }; - - PMDesigner.contextMenuFactory = new ContextMenu(defaults.factory); - PMDesigner.getMenuFactory = function (type) { - if (prj_readonly === 'true') { - return {}; - } - return PMDesigner.contextMenuFactory.getProduct(type); - }; - /** - * Change task type marker - * @param menuOption - */ - function handlerMarkerType(menuOption) { - var result = true, - tempType = menuOption.getMenuTargetElement().getTaskType(); - menuOption.parent.hide(); - - menuOption.getMenuTargetElement().switchTaskType(menuOption.id.toUpperCase()); - - //validate if act loop type is parallel - if (menuOption.getMenuTargetElement().act_loop_type === "PARALLEL") { - handlerMarkerLoopType(menuOption, tempType) - } - - //to enable save button - PMDesigner.project.updateElement([]); - - } - - /** - * Change marker loop type - * @param menuOption - * @param type - * @returns {boolean} - */ - function handlerMarkerLoopType(menuOption, type) { - var message_window, - loopType = menuOption.id.toUpperCase(), - taskType = menuOption.getMenuTargetElement().act_task_type; - if (typeof type !== 'undefined' && type !== null) { - taskType = type; - } - - if (menuOption.getMenuTargetElement().act_loop_type === "PARALLEL") { - - message_window = new PMUI.ui.MessageWindow({ - id: "handlerMarkerType", - width: 490, - title: 'Parallel Marker Type'.translate(), - windowMessageType: 'warning', - bodyHeight: 'auto', - message: "The configuring of multiple instances will be lost".translate(), - footerItems: [ - { - text: 'Cancel'.translate(), - handler: function () { - menuOption.getMenuTargetElement().switchLoopType('PARALLEL'); - menuOption.getMenuTargetElement().switchTaskType(taskType); - message_window.close(); - return false; - }, - buttonType: "error" }, - { - text: 'Continue'.translate(), - handler: function () { - try { - if (loopType == "loop" || loopType == "sequential") { - menuOption.getMenuTargetElement().switchLoopType(loopType.toUpperCase()); - } else { - menuOption.getMenuTargetElement().switchLoopType('EMPTY'); - } - PMDesigner.project.updateElement([]); - } catch (e) { - console.error("loop marker error", e.message); - } - message_window.close(); - return true; - }, - buttonType: "success" - } - - ] - }); - message_window.open(); - message_window.showFooter(); - } else { - menuOption.parent.hide(); - menuOption.getMenuTargetElement().switchLoopType(loopType.toUpperCase()); - PMDesigner.project.updateElement([]); - return true; - } - } - -}()); - -(function () { - PMDesigner.shapeFactory = function (type, options) { - var customshape = null, - menuShape, - defaultOptions = null, - canvasName, - name, - id, - classEvent = "start", - pmCanvas = this.canvas, - corona = PMDesigner.defaultCrown, - wildcard; - - canvasName = new IncrementNameCanvas(pmCanvas); - name = canvasName.get(type); - - if (typeof options === 'undefined') { - options = {}; - if (type === 'START_MESSAGE') { - type = 'START'; - classEvent = "message"; - options.evn_marker = 'MESSAGECATCH'; - } - if (type === 'START_TIMER') { - type = 'START'; - classEvent = "timer"; - options.evn_marker = 'TIMER'; - } - - if (type === 'END_MESSAGE') { - type = 'END'; - classEvent = "message"; - options.evn_marker = 'MESSAGETHROW'; - } - if (type === 'END_EMAIL') { - type = 'END'; - classEvent = "email"; - options.evn_marker = 'EMAIL'; - options.evn_behavior = 'THROW'; - } - if (type === 'INTERMEDIATE_SENDMESSAGE') { - type = 'INTERMEDIATE'; - classEvent = "sendmessage"; - options.evn_marker = 'MESSAGETHROW'; - options.evn_behavior = 'THROW'; - } - if (type === 'INTERMEDIATE_RECEIVEMESSAGE') { - type = 'INTERMEDIATE'; - classEvent = "receivemessage"; - options.evn_marker = 'MESSAGECATCH'; - options.evn_behavior = 'CATCH'; - } - if (type === 'INTERMEDIATE_EMAIL') { - type = 'INTERMEDIATE'; - classEvent = "email"; - options.evn_marker = 'EMAIL'; - options.evn_behavior = 'THROW'; - } - if (type === 'INTERMEDIATE_TIMER') { - type = 'INTERMEDIATE'; - classEvent = "timer"; - options.evn_marker = 'TIMER'; - } - if (type === 'BOUNDARY_EVENT') { - type = 'BOUNDARY'; - classEvent = "receivemessage"; - options.evn_marker = 'EMPTY'; - options.evn_behavior = 'CATCH'; - } - - switch (type) { - case 'COMPLEX': - case 'PARALLEL': - case 'EXCLUSIVE': - case 'EVENTBASED': - case 'EXCLUSIVEEVENTBASED': - case 'PARALLELEVENTBASED': - case 'INCLUSIVE': - options.gat_type = type; - break; - } - } - if (type === 'DATAOBJECT') { - type = 'DATAOBJECT'; - options.dat_object_type = 'dataobject'; - } - if (type === 'DATAINPUT') { - type = 'DATAOBJECT'; - options.dat_object_type = 'datainput'; - } - if (type === 'DATAOUTPUT') { - type = 'DATAOBJECT'; - options.dat_object_type = 'dataoutput'; - } - - wildcard = [ - { - name: 'wildcard'.translate(), - className: 'mafe-wildcard', - onClick: null, - column: 2 - } - ]; - - switch (type) { - case 'TASK': - defaultOptions = { - canvas: pmCanvas, - width: 150, - height: 75, - act_type: 'TASK', - act_name: name, - act_task_type: 'EMPTY', - act_loop_type: 'EMPTY', - minHeight: 30, - minWidth: 150, - maxHeight: 50, - maxWidth: 170, - container: "activity", - labels: [ - { - message: name, - width: 0, - height: 0, - position: { - location: 'center', - diffX: 0, - diffY: 0 - }, - attachEvents: false - } - ], - layers: [ - { - x: 0, - y: 0, - layerName: "first-layer", - priority: 2, - visible: true, - style: { - cssClasses: [ - 'mafe-activity-task' - ] + corona: corona + }; + jQuery.extend(true, defaultOptions, options); + defaultOptions.layers[0] + .zoomSprites = PMDesigner.updateLayerClasses(defaultOptions); + customshape = new PMEvent(defaultOptions); + break; + case 'INTERMEDIATE': + defaultOptions = { + canvas: pmCanvas, + width: 33, + height: 33, + evn_type: 'INTERMEDIATE', + evn_name: '', + evn_marker: 'EMPTY', + evn_behavior: 'CATCH', + labels: [ + { + message: '', + visible: true, + position: { + location: 'bottom', + diffX: 0, + diffY: 13 } + } + ], + style: { + cssClasses: ['mafe-event-intermediate'] + }, + layers: [ + { + x: 0, + y: 0, + layerName: "first-layer", + priority: 2, + visible: true, + style: { + cssClasses: [] + }, + zoomSprites: [ + 'mafe-event-intermediate-16', + 'mafe-event-intermediate-24', + 'mafe-event-intermediate-33', + 'mafe-event-intermediate-41', + 'mafe-event-intermediate-49' + ] }, { x: 0, @@ -3677,13 +4019,12 @@ ViewTaskInformation.prototype.showViewLegendsInformation = function () { cssClasses: [] } } - ], connectAtMiddlePoints: true, - resizeBehavior: 'activityResize', + resizeBehavior: 'NoResize', resizeHandlers: { type: "Rectangle", - total: 8, + total: 4, resizableStyle: { cssProperties: { 'background-color': "rgb(0, 255, 0)", @@ -3698,29 +4039,9 @@ ViewTaskInformation.prototype.showViewLegendsInformation = function () { } }, "drop": { - type: "pmactivitydrop", - selectors: [ - "#BOUNDARY_EVENT", - ".mafe-event-boundary", - ".dragConnectHandler" - ] + type: "pmconnection", + selectors: ['.dragConnectHandler'] }, - markers: [ - { - markerType: 'USERTASK', - x: 10, - y: 10, - position: 0, - markerZoomClasses: [] - }, - { - markerType: 'EMPTY', - x: 10, - y: 10, - position: 4, - markerZoomClasses: [] - } - ], validatorMarker: { width: 12, height: 12, @@ -3733,52 +4054,40 @@ ViewTaskInformation.prototype.showViewLegendsInformation = function () { "mafe-style-error-marker-14", "mafe-style-error-marker-17", "mafe-style-error-marker-21" - ], - markerZoomClassesWarning: [ - "mafe-style-warning-marker-7", - "mafe-style-warning-marker-10", - "mafe-style-warning-marker-14", - "mafe-style-warning-marker-17", - "mafe-style-warning-marker-21" ] } } }, - corona: corona, - focusLabel: true + corona: corona }; jQuery.extend(true, defaultOptions, options); - defaultOptions.markers[0] - .markerZoomClasses = PMDesigner.updateMarkerLayerClasses(defaultOptions); - defaultOptions.markers[1] - .markerZoomClasses = PMDesigner.updateLoopLayerClasses(defaultOptions); - customshape = new PMActivity(defaultOptions); + defaultOptions.layers[0] + .zoomSprites = PMDesigner.updateLayerClasses(defaultOptions); + customshape = new PMEvent(defaultOptions); break; - case 'SUB_PROCESS': + case 'BOUNDARY': defaultOptions = { canvas: pmCanvas, - width: 150, - height: 75, - act_type: 'SUB_PROCESS', - act_loop_type: 'EMPTY', - act_name: name, - act_task_type: 'COLLAPSED', - minHeight: 30, - minWidth: 150, - maxHeight: 50, - maxWidth: 170, - container: "activity", + width: 33, + height: 33, + evn_type: 'BOUNDARY', + evn_name: '', + evn_marker: 'EMPTY', + evn_behavior: 'CATCH', labels: [ { - message: name, + message: '', + visible: true, position: { - location: 'center', + location: 'bottom', diffX: 0, diffY: 0 - }, - attachEvents: false + } } ], + style: { + cssClasses: ['mafe-event-boundary'] + }, layers: [ { x: 0, @@ -3786,29 +4095,23 @@ ViewTaskInformation.prototype.showViewLegendsInformation = function () { layerName: "first-layer", priority: 2, visible: true, - style: { - cssClasses: [ - 'mafe-activity-subprocess' - ] - } - }, - { - x: 0, - y: 0, - layerName: "second-layer", - priority: 2, - visible: false, style: { cssClasses: [] - } + }, + zoomSprites: [ + 'mafe-event-intermediate-16', + 'mafe-event-intermediate-24', + 'mafe-event-intermediate-33', + 'mafe-event-intermediate-41', + 'mafe-event-intermediate-49' + ] } - ], connectAtMiddlePoints: true, - resizeBehavior: 'activityResize', + resizeBehavior: 'NoResize', resizeHandlers: { type: "Rectangle", - total: 8, + total: 4, resizableStyle: { cssProperties: { 'background-color': "rgb(0, 255, 0)", @@ -3823,67 +4126,30 @@ ViewTaskInformation.prototype.showViewLegendsInformation = function () { } }, "drop": { - type: "pmactivitydrop", - selectors: [ - "#BOUNDARY_EVENT", - ".mafe-event-boundary", - ".dragConnectHandler" - ] + type: "pmconnection", + selectors: ['.dragConnectHandler'] }, - markers: [ - { - markerType: 'COLLAPSED', - x: 10, - y: 10, - position: 4, - markerZoomClasses: [ - "mafe-collapsed-marker-10", - "mafe-collapsed-marker-15", - "mafe-collapsed-marker-21", - "mafe-collapsed-marker-26", - "mafe-collapsed-marker-31" - ] - } - ], - validatorMarker: { - width: 12, - height: 12, - position: 2, - errors: { - style: { - markerZoomClassesError: [ - "mafe-style-error-marker-7", - "mafe-style-error-marker-10", - "mafe-style-error-marker-14", - "mafe-style-error-marker-17", - "mafe-style-error-marker-21" - ] - } - } - }, - corona: corona, - focusLabel: true + drag: 'nodrag' }; jQuery.extend(true, defaultOptions, options); - defaultOptions.markers[0] - .markerZoomClasses = PMDesigner.updateMarkerLayerClasses(defaultOptions); - customshape = new PMActivity(defaultOptions); + defaultOptions.layers[0] + .zoomSprites = PMDesigner.updateLayerClasses(defaultOptions); + customshape = new PMEvent(defaultOptions); break; - case 'START': + + case 'END': defaultOptions = { canvas: pmCanvas, width: 33, height: 33, - evn_type: 'START', + evn_type: 'END', evn_name: '', evn_marker: 'EMPTY', - evn_behavior: 'catch', - evn_message: 'LEAD', + evn_behavior: 'throw', labels: [ { message: '', visible: true, - width: 100, position: { location: 'bottom', diffX: 0, @@ -3892,7 +4158,7 @@ ViewTaskInformation.prototype.showViewLegendsInformation = function () { } ], style: { - cssClasses: ['mafe-event-start'] + cssClasses: ['mafe-event-end'] }, layers: [ { @@ -3905,11 +4171,11 @@ ViewTaskInformation.prototype.showViewLegendsInformation = function () { cssClasses: [] }, zoomSprites: [ - 'mafe-event-start-empty-16', - 'mafe-event-start-empty-24', - 'mafe-event-start-empty-33', - 'mafe-event-start-empty-41', - 'mafe-event-start-empty-49' + 'mafe-event-end-empty-16', + 'mafe-event-end-empty-24', + 'mafe-event-end-empty-33', + 'mafe-event-end-empty-41', + 'mafe-event-end-empty-49' ] }, { @@ -3968,19 +4234,20 @@ ViewTaskInformation.prototype.showViewLegendsInformation = function () { .zoomSprites = PMDesigner.updateLayerClasses(defaultOptions); customshape = new PMEvent(defaultOptions); break; - case 'INTERMEDIATE': + + case 'COMPLEX': + case 'PARALLEL': + case 'EXCLUSIVE': + case 'EVENTBASED': + case 'EXCLUSIVEEVENTBASED': + case 'PARALLELEVENTBASED': + case 'INCLUSIVE': defaultOptions = { - canvas: pmCanvas, - width: 33, - height: 33, - evn_type: 'INTERMEDIATE', - evn_name: '', - evn_marker: 'EMPTY', - evn_behavior: 'CATCH', labels: [ { message: '', visible: true, + width: 100, position: { location: 'bottom', diffX: 0, @@ -3988,9 +4255,11 @@ ViewTaskInformation.prototype.showViewLegendsInformation = function () { } } ], - style: { - cssClasses: ['mafe-event-intermediate'] - }, + canvas: pmCanvas, + width: 41, + height: 41, + gat_type: 'EXCLUSIVE', + gat_name: '', layers: [ { x: 0, @@ -4002,11 +4271,11 @@ ViewTaskInformation.prototype.showViewLegendsInformation = function () { cssClasses: [] }, zoomSprites: [ - 'mafe-event-intermediate-16', - 'mafe-event-intermediate-24', - 'mafe-event-intermediate-33', - 'mafe-event-intermediate-41', - 'mafe-event-intermediate-49' + 'mafe-gateway-exclusive-20', + 'mafe-gateway-exclusive-30', + 'mafe-gateway-exclusive-41', + 'mafe-gateway-exclusive-51', + 'mafe-gateway-exclusive-61' ] }, { @@ -4062,121 +4331,106 @@ ViewTaskInformation.prototype.showViewLegendsInformation = function () { }; jQuery.extend(true, defaultOptions, options); defaultOptions.layers[0] - .zoomSprites = PMDesigner.updateLayerClasses(defaultOptions); - customshape = new PMEvent(defaultOptions); + .zoomSprites = PMDesigner.updateGatewayLayerClasses(defaultOptions); + customshape = new PMGateway(defaultOptions); break; - case 'BOUNDARY': + case 'GROUP': defaultOptions = { + art_name: name, + art_type: 'GROUP', canvas: pmCanvas, - width: 33, - height: 33, - evn_type: 'BOUNDARY', - evn_name: '', - evn_marker: 'EMPTY', - evn_behavior: 'CATCH', - labels: [ - { - message: '', - visible: true, - position: { - location: 'bottom', - diffX: 0, - diffY: 0 - } - } - ], + width: 200, + height: 100, style: { - cssClasses: ['mafe-event-boundary'] + cssClasses: ['mafe-artifact-group'] }, layers: [ { x: 0, y: 0, - layerName: "first-layer", - priority: 2, + layerName: "background-layer", + priority: 1, visible: true, + style: { + cssClasses: [ + 'mafe-artifact-group' + ] + } + }, + { + x: 0, + y: 0, + layerName: "second-layer", + priority: 2, + visible: false, style: { cssClasses: [] - }, - zoomSprites: [ - 'mafe-event-intermediate-16', - 'mafe-event-intermediate-24', - 'mafe-event-intermediate-33', - 'mafe-event-intermediate-41', - 'mafe-event-intermediate-49' - ] + } } ], connectAtMiddlePoints: true, - resizeBehavior: 'NoResize', + resizeBehavior: 'annotationResize', resizeHandlers: { type: "Rectangle", - total: 4, + total: 8, resizableStyle: { cssProperties: { 'background-color': "rgb(0, 255, 0)", 'border': '1px solid black' } - }, - nonResizableStyle: { - cssProperties: { - 'background-color': "white", - 'border': '1px solid black' - } } }, + labels: [ + { + message: "", + width: 0, + height: 0, + position: { + location: 'top', + diffX: 2, + diffY: 0 + }, + attachEvents: false, + updateParent: true, + style: { + cssClasses: [ + 'mafe-label-annotation' + ] + } + } + ], "drop": { type: "pmconnection", selectors: ['.dragConnectHandler'] }, - drag: 'nodrag' + corona: corona, + focusLabel: true }; jQuery.extend(true, defaultOptions, options); - defaultOptions.layers[0] - .zoomSprites = PMDesigner.updateLayerClasses(defaultOptions); - customshape = new PMEvent(defaultOptions); + customshape = new PMArtifact(defaultOptions); break; - - case 'END': + case 'TEXT_ANNOTATION': defaultOptions = { + art_name: name, + art_type: 'TEXT_ANNOTATION', canvas: pmCanvas, - width: 33, - height: 33, - evn_type: 'END', - evn_name: '', - evn_marker: 'EMPTY', - evn_behavior: 'throw', - labels: [ - { - message: '', - visible: true, - position: { - location: 'bottom', - diffX: 0, - diffY: 13 - } - } - ], + width: 100, + height: 30, style: { - cssClasses: ['mafe-event-end'] + cssClasses: ['mafe-artifact-annotation'] }, layers: [ { x: 0, y: 0, - layerName: "first-layer", - priority: 2, + layerName: "background-layer", + priority: 1, visible: true, style: { - cssClasses: [] - }, - zoomSprites: [ - 'mafe-event-end-empty-16', - 'mafe-event-end-empty-24', - 'mafe-event-end-empty-33', - 'mafe-event-end-empty-41', - 'mafe-event-end-empty-49' - ] + cssClasses: [ + 'mafe-artifact-annotation' + ] + } }, { x: 0, @@ -4190,285 +4444,31 @@ ViewTaskInformation.prototype.showViewLegendsInformation = function () { } ], connectAtMiddlePoints: true, - resizeBehavior: 'NoResize', + resizeBehavior: 'annotationResize', resizeHandlers: { type: "Rectangle", - total: 4, + total: 8, resizableStyle: { cssProperties: { 'background-color': "rgb(0, 255, 0)", 'border': '1px solid black' } - }, - nonResizableStyle: { - cssProperties: { - 'background-color': "white", - 'border': '1px solid black' - } } }, - "drop": { - type: "pmconnection", - selectors: ['.dragConnectHandler'] - }, - validatorMarker: { - width: 12, - height: 12, - position: 2, - errors: { - style: { - markerZoomClassesError: [ - "mafe-style-error-marker-7", - "mafe-style-error-marker-10", - "mafe-style-error-marker-14", - "mafe-style-error-marker-17", - "mafe-style-error-marker-21" - ] - } - } - }, - corona: corona - }; - jQuery.extend(true, defaultOptions, options); - defaultOptions.layers[0] - .zoomSprites = PMDesigner.updateLayerClasses(defaultOptions); - customshape = new PMEvent(defaultOptions); - break; - - case 'COMPLEX': - case 'PARALLEL': - case 'EXCLUSIVE': - case 'EVENTBASED': - case 'EXCLUSIVEEVENTBASED': - case 'PARALLELEVENTBASED': - case 'INCLUSIVE': - defaultOptions = { - labels: [ - { - message: '', - visible: true, - width: 100, - position: { - location: 'bottom', - diffX: 0, - diffY: 13 - } - } - ], - canvas: pmCanvas, - width: 41, - height: 41, - gat_type: 'EXCLUSIVE', - gat_name: '', - layers: [ - { - x: 0, - y: 0, - layerName: "first-layer", - priority: 2, - visible: true, - style: { - cssClasses: [] - }, - zoomSprites: [ - 'mafe-gateway-exclusive-20', - 'mafe-gateway-exclusive-30', - 'mafe-gateway-exclusive-41', - 'mafe-gateway-exclusive-51', - 'mafe-gateway-exclusive-61' - ] - }, - { - x: 0, - y: 0, - layerName: "second-layer", - priority: 2, - visible: false, - style: { - cssClasses: [] - } - } - ], - connectAtMiddlePoints: true, - resizeBehavior: 'NoResize', - resizeHandlers: { - type: "Rectangle", - total: 4, - resizableStyle: { - cssProperties: { - 'background-color': "rgb(0, 255, 0)", - 'border': '1px solid black' - } - }, - nonResizableStyle: { - cssProperties: { - 'background-color': "white", - 'border': '1px solid black' - } - } - }, - "drop": { - type: "pmconnection", - selectors: ['.dragConnectHandler'] - }, - validatorMarker: { - width: 12, - height: 12, - position: 2, - errors: { - style: { - markerZoomClassesError: [ - "mafe-style-error-marker-7", - "mafe-style-error-marker-10", - "mafe-style-error-marker-14", - "mafe-style-error-marker-17", - "mafe-style-error-marker-21" - ] - } - } - }, - corona: corona - }; - jQuery.extend(true, defaultOptions, options); - defaultOptions.layers[0] - .zoomSprites = PMDesigner.updateGatewayLayerClasses(defaultOptions); - customshape = new PMGateway(defaultOptions); - break; - case 'GROUP': - defaultOptions = { - art_name: name, - art_type: 'GROUP', - canvas: pmCanvas, - width: 200, - height: 100, - style: { - cssClasses: ['mafe-artifact-group'] - }, - layers: [ - { - x: 0, - y: 0, - layerName: "background-layer", - priority: 1, - visible: true, - style: { - cssClasses: [ - 'mafe-artifact-group' - ] - } - }, - { - x: 0, - y: 0, - layerName: "second-layer", - priority: 2, - visible: false, - style: { - cssClasses: [] - } - } - ], - connectAtMiddlePoints: true, - resizeBehavior: 'annotationResize', - resizeHandlers: { - type: "Rectangle", - total: 8, - resizableStyle: { - cssProperties: { - 'background-color': "rgb(0, 255, 0)", - 'border': '1px solid black' - } - } - }, - labels: [ - { - message: "", - width: 0, - height: 0, - position: { - location: 'top', - diffX: 2, - diffY: 0 - }, - attachEvents: false, - updateParent: true, - style: { - cssClasses: [ - 'mafe-label-annotation' - ] - } - } - ], - "drop": { - type: "pmconnection", - selectors: ['.dragConnectHandler'] - }, - corona: corona, - focusLabel: true - }; - jQuery.extend(true, defaultOptions, options); - customshape = new PMArtifact(defaultOptions); - break; - case 'TEXT_ANNOTATION': - defaultOptions = { - art_name: name, - art_type: 'TEXT_ANNOTATION', - canvas: pmCanvas, - width: 100, - height: 30, - style: { - cssClasses: ['mafe-artifact-annotation'] - }, - layers: [ - { - x: 0, - y: 0, - layerName: "background-layer", - priority: 1, - visible: true, - style: { - cssClasses: [ - 'mafe-artifact-annotation' - ] - } - }, - { - x: 0, - y: 0, - layerName: "second-layer", - priority: 2, - visible: false, - style: { - cssClasses: [] - } - } - ], - connectAtMiddlePoints: true, - resizeBehavior: 'annotationResize', - resizeHandlers: { - type: "Rectangle", - total: 8, - resizableStyle: { - cssProperties: { - 'background-color': "rgb(0, 255, 0)", - 'border': '1px solid black' - } - } - }, - labels: [ - { - message: name, - width: 0, - height: 0, - position: { - location: 'center', - diffX: 0, - diffY: 0 - }, - attachEvents: false, - updateParent: true - } - ], + labels: [ + { + message: name, + width: 0, + height: 0, + position: { + location: 'center', + diffX: 0, + diffY: 0 + }, + attachEvents: false, + updateParent: true + } + ], "drop": { type: "pmconnection", selectors: ['.dragConnectHandler'] @@ -5201,339 +5201,339 @@ PMDesigner.sidebar.push( ] }) ); -ListDynaform = function () { - this.superTitle = 'Dynaforms'.translate(); - this.tableContainerHeight = 374; - this.buttonCreate = null; - this.onCreate = new Function(); - this.onShowId = new Function(); - this.onEdit = new Function(); - this.onDel = new Function(); - this.loaded = false; - this.clickedClose = true; - Mafe.Grid.call(this); - ListDynaform.prototype.init.call(this); -}; -ListDynaform.prototype = new Mafe.Grid(); -ListDynaform.prototype.init = function () { - var that = this; - that.buttonCreate = new PMUI.ui.Button({ - id: 'dynaformButtonNew', - text: 'Create'.translate(), - height: '36px', - width: 100, - style: {cssClasses: ['mafe-button-create']}, - handler: function (event) { - that.onCreate(event); - } - }); - that.buttonCreate.defineEvents(); - that.setID('idListDynaform'); - that.setColumns([{ - id: 'copyuid', - title: 'Show ID'.translate(), - dataType: 'button', - buttonLabel: 'Show ID'.translate(), - buttonStyle: {cssClasses: ['mafe-button-show']}, - onButtonClick: function (row, grid) { - that.onShowId(row, grid); - } - }, { - id: 'dynaformGridPanelTitle', - title: 'Title'.translate(), - dataType: 'string', - width: '460px', - alignmentCell: 'left', - sortable: true, - columnData: 'dyn_title' - }, { - id: 'dynaformGridPanelEdit', - title: '', - dataType: 'button', - buttonStyle: {cssClasses: ['mafe-button-edit']}, - buttonLabel: function (row, data) { - return 'Edit'.translate(); - }, - onButtonClick: function (row, grid) { - that.onEdit(row, grid); - } - }, { - id: 'dynaformGridPanelDelete', - title: '', - dataType: 'button', - buttonStyle: {cssClasses: ['mafe-button-delete']}, - buttonLabel: function (row, data) { - return 'Delete'.translate(); - }, - onButtonClick: function (row, grid) { - that.onDel(row, grid); - } - } - ]); -}; -ListDynaform.prototype.createHTML = function () { - Mafe.Grid.prototype.createHTML.call(this); - this.dom.toolbar.appendChild(this.buttonCreate.getHTML()); - return this.html; -}; -ListDynaform.prototype.load = function () { - var that = this; - that.clearItems(); - (new PMRestClient({ - endpoint: 'dynaforms', - typeRequest: 'get', - functionSuccess: function (xhr, response) { - that.setDataItems(response); - that.sort('dyn_title', 'asc'); - that.loaded = true; - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - - that.loaded = false; - }, - messageError: 'There are problems getting the list of dynaforms, please try again.'.translate() - })).executeRestClient(); -}; -ListDynaform.prototype.getSuperTitle = function () { - return this.superTitle; -}; - -BlankDynaform = function () { - this.superTitle = 'Create Blank Dynaform'.translate(); - this.onSave = new Function(); - this.onSaveOpen = new Function(); - this.onCancel = new Function(); - this.buttons = null; - Mafe.Form.call(this); - BlankDynaform.prototype.init.call(this); -}; -BlankDynaform.prototype = new Mafe.Form(); -BlankDynaform.prototype.init = function () { - var that = this; - that.setID('formDynaformInformation'); - that.setTitle('Dynaform Information'.translate()); - that.setItems([{ - id: 'formDynaformInformationTitle', - pmType: 'text', - label: 'Title'.translate(), - value: '', - maxLength: 255, - placeholder: 'The Dynaform title'.translate(), - name: 'dyn_title', - required: true, - controlsWidth: 303 - }, { - id: 'formDynaformInformationDescription', - pmType: 'textarea', - rows: 200, - name: 'dyn_description', - width: 200, - label: 'Description'.translate(), - style: {cssClasses: ['mafe-textarea-resize']} - } - ]); - that.buttons = [ - new PMUI.ui.Button({ - id: 'btnClose', - text: 'Cancel'.translate(), - buttonType: 'error', - handler: function () { - that.onCancel(); - } - }), - new PMUI.ui.Button({ - id: 'windowDynaformInformationSaveOpen', - text: 'Save & Open'.translate(), - buttonType: 'success', - handler: function () { - that.onSaveOpen(); - } - }), - new PMUI.ui.Button({ - id: 'windowDynaformInformationSave', - text: 'Save'.translate(), - buttonType: 'success', - handler: function () { - that.onSave(); - } - }) - ]; -}; -BlankDynaform.prototype.getButtons = function () { - return this.buttons; -}; -BlankDynaform.prototype.getSuperTitle = function () { - return this.superTitle; -}; - -Dynaform = function (settings) { - this.listDynaform = null; - this.blankDynaform = null; - Mafe.Window.call(this, settings); - Dynaform.prototype.init.call(this, settings); -}; -Dynaform.prototype = new Mafe.Window(); -Dynaform.prototype.init = function (settings) { - var that = this; - that.listDynaform = new ListDynaform(); - that.setOnBeforeCloseHandler(function () { - this.clickedClose = true; - if (!that.blankDynaform.isVisible()) { - that.close(); - } else { - that.blankDynaform.onCancel(); - } - }); - that.listDynaform.load(); - that.listDynaform.onShowId = function (row, grid) { - showUID(row.getData().dyn_uid); - }; - that.listDynaform.onCreate = function () { - that.resetView(); - that.setTitle(that.blankDynaform.getSuperTitle()); - that.blankDynaform.setVisible(true); - that.setButtons(that.blankDynaform.getButtons()); - }; - that.listDynaform.onEdit = function (row, grid) { - that.edit(row, grid); - }; - that.listDynaform.onDel = function (row, grid) { - that.del(row, grid); - }; - - that.blankDynaform = new BlankDynaform(); - that.blankDynaform.onSave = function () { - that.saveBlank(false); - }; - that.blankDynaform.onSaveOpen = function () { - that.saveBlank(true); - }; - that.blankDynaform.onCancel = function () { - $("input,select,textarea").blur(); - var title = ""; - that.blankDynaform.loseChanges(title); - }; - that.blankDynaform.onYesConfirmCancellation = function () { - if (that.clickedClose) { - that.close(); - } - that.resetView(); - that.setTitle(that.listDynaform.getSuperTitle()); - that.listDynaform.setVisible(true); - }; - - that.addItem(that.listDynaform); - that.addItem(that.blankDynaform); - - that.open(); - that.resetView(); - that.setTitle(that.listDynaform.getSuperTitle()); - that.listDynaform.setVisible(true); - - // hard coding dyn_title textfield because enter keypress reload the current page - if (that.blankDynaform.getItems()[0] - && that.blankDynaform.getItems()[0].controls[0] - && that.blankDynaform.getItems()[0].controls[0].html) { - $(that.blankDynaform.getItems()[0].controls[0].html).keypress(function (e) { - if (e.which == 13) { - e.preventDefault(); - } - }); - } -}; -Dynaform.prototype.saveBlank = function (open) { - var that = this, - data, - restClient, - flagAux; - - if (!that.blankDynaform.isValid()) { - flagAux = that.blankDynaform.visible; - } else { - flagAux = that.blankDynaform.isValid(); - } - - if (flagAux) { - if (getData2PMUI(that.blankDynaform.html).dyn_title == "") { - return false; - } - } - - data = getData2PMUI(that.blankDynaform.html); - data['dyn_version'] = 2; - data['dyn_type'] = 'xmlform'; - restClient = new PMRestClient({ - endpoint: 'dynaform', - typeRequest: 'post', - data: data, - functionSuccess: function (xhr, response) { - if (open) { - that.close(); - try { - PMUI.getActiveCanvas().emptyCurrentSelection(); - } catch (msg) { - } - PMDesigner.dynaformDesigner(response); - } else { - that.resetView(); - that.setTitle(that.listDynaform.getSuperTitle()); - that.listDynaform.setVisible(true); - that.listDynaform.load(); - } - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: 'There are problems creating the dynaform, please try again.'.translate(), - messageSuccess: 'Dynaform saved successfully'.translate(), - flashContainer: that.listDynaform - }); - restClient.executeRestClient(); -}; -Dynaform.prototype.edit = function (row, grid) { - this.close(); - try { - PMUI.getActiveCanvas().emptyCurrentSelection(); - } catch (msg) { - } - PMDesigner.dynaformDesigner(row.getData()); -}; -Dynaform.prototype.del = function (row, grid) { - var that = this, - confirmDeletion = new Mafe.ConfirmDeletion(); - confirmDeletion.setMessage('Do you want to delete this DynaForm?'.translate()); - confirmDeletion.setTitle("Dynaform".translate()); - confirmDeletion.onDelete = function () { - var restClient = new PMRestClient({ - endpoint: 'dynaform/' + row.getData().dyn_uid, - typeRequest: 'remove', - functionSuccess: function (xhr, response) { - that.listDynaform.load(); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: 'There are problems deleting the dynaform, please try again.'.translate(), - messageSuccess: 'Dynaform deleted successfully'.translate(), - flashContainer: that.listDynaform - }); - restClient.executeRestClient(); - }; -}; - -(function () { - PMDesigner.dynaform = function () { - var dynaform = new Dynaform(); - }; - PMDesigner.dynaform.create = function () { - var dynaform = new Dynaform(); - dynaform.resetView(); - dynaform.setTitle(dynaform.blankDynaform.getSuperTitle()); - dynaform.blankDynaform.setVisible(true); - dynaform.setButtons(dynaform.blankDynaform.getButtons()); - }; -}()); +ListDynaform = function () { + this.superTitle = 'Dynaforms'.translate(); + this.tableContainerHeight = 374; + this.buttonCreate = null; + this.onCreate = new Function(); + this.onShowId = new Function(); + this.onEdit = new Function(); + this.onDel = new Function(); + this.loaded = false; + this.clickedClose = true; + Mafe.Grid.call(this); + ListDynaform.prototype.init.call(this); +}; +ListDynaform.prototype = new Mafe.Grid(); +ListDynaform.prototype.init = function () { + var that = this; + that.buttonCreate = new PMUI.ui.Button({ + id: 'dynaformButtonNew', + text: 'Create'.translate(), + height: '36px', + width: 100, + style: {cssClasses: ['mafe-button-create']}, + handler: function (event) { + that.onCreate(event); + } + }); + that.buttonCreate.defineEvents(); + that.setID('idListDynaform'); + that.setColumns([{ + id: 'copyuid', + title: 'Show ID'.translate(), + dataType: 'button', + buttonLabel: 'Show ID'.translate(), + buttonStyle: {cssClasses: ['mafe-button-show']}, + onButtonClick: function (row, grid) { + that.onShowId(row, grid); + } + }, { + id: 'dynaformGridPanelTitle', + title: 'Title'.translate(), + dataType: 'string', + width: '460px', + alignmentCell: 'left', + sortable: true, + columnData: 'dyn_title' + }, { + id: 'dynaformGridPanelEdit', + title: '', + dataType: 'button', + buttonStyle: {cssClasses: ['mafe-button-edit']}, + buttonLabel: function (row, data) { + return 'Edit'.translate(); + }, + onButtonClick: function (row, grid) { + that.onEdit(row, grid); + } + }, { + id: 'dynaformGridPanelDelete', + title: '', + dataType: 'button', + buttonStyle: {cssClasses: ['mafe-button-delete']}, + buttonLabel: function (row, data) { + return 'Delete'.translate(); + }, + onButtonClick: function (row, grid) { + that.onDel(row, grid); + } + } + ]); +}; +ListDynaform.prototype.createHTML = function () { + Mafe.Grid.prototype.createHTML.call(this); + this.dom.toolbar.appendChild(this.buttonCreate.getHTML()); + return this.html; +}; +ListDynaform.prototype.load = function () { + var that = this; + that.clearItems(); + (new PMRestClient({ + endpoint: 'dynaforms', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + that.setDataItems(response); + that.sort('dyn_title', 'asc'); + that.loaded = true; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + + that.loaded = false; + }, + messageError: 'There are problems getting the list of dynaforms, please try again.'.translate() + })).executeRestClient(); +}; +ListDynaform.prototype.getSuperTitle = function () { + return this.superTitle; +}; + +BlankDynaform = function () { + this.superTitle = 'Create Blank Dynaform'.translate(); + this.onSave = new Function(); + this.onSaveOpen = new Function(); + this.onCancel = new Function(); + this.buttons = null; + Mafe.Form.call(this); + BlankDynaform.prototype.init.call(this); +}; +BlankDynaform.prototype = new Mafe.Form(); +BlankDynaform.prototype.init = function () { + var that = this; + that.setID('formDynaformInformation'); + that.setTitle('Dynaform Information'.translate()); + that.setItems([{ + id: 'formDynaformInformationTitle', + pmType: 'text', + label: 'Title'.translate(), + value: '', + maxLength: 255, + placeholder: 'The Dynaform title'.translate(), + name: 'dyn_title', + required: true, + controlsWidth: 303 + }, { + id: 'formDynaformInformationDescription', + pmType: 'textarea', + rows: 200, + name: 'dyn_description', + width: 200, + label: 'Description'.translate(), + style: {cssClasses: ['mafe-textarea-resize']} + } + ]); + that.buttons = [ + new PMUI.ui.Button({ + id: 'btnClose', + text: 'Cancel'.translate(), + buttonType: 'error', + handler: function () { + that.onCancel(); + } + }), + new PMUI.ui.Button({ + id: 'windowDynaformInformationSaveOpen', + text: 'Save & Open'.translate(), + buttonType: 'success', + handler: function () { + that.onSaveOpen(); + } + }), + new PMUI.ui.Button({ + id: 'windowDynaformInformationSave', + text: 'Save'.translate(), + buttonType: 'success', + handler: function () { + that.onSave(); + } + }) + ]; +}; +BlankDynaform.prototype.getButtons = function () { + return this.buttons; +}; +BlankDynaform.prototype.getSuperTitle = function () { + return this.superTitle; +}; + +Dynaform = function (settings) { + this.listDynaform = null; + this.blankDynaform = null; + Mafe.Window.call(this, settings); + Dynaform.prototype.init.call(this, settings); +}; +Dynaform.prototype = new Mafe.Window(); +Dynaform.prototype.init = function (settings) { + var that = this; + that.listDynaform = new ListDynaform(); + that.setOnBeforeCloseHandler(function () { + this.clickedClose = true; + if (!that.blankDynaform.isVisible()) { + that.close(); + } else { + that.blankDynaform.onCancel(); + } + }); + that.listDynaform.load(); + that.listDynaform.onShowId = function (row, grid) { + showUID(row.getData().dyn_uid); + }; + that.listDynaform.onCreate = function () { + that.resetView(); + that.setTitle(that.blankDynaform.getSuperTitle()); + that.blankDynaform.setVisible(true); + that.setButtons(that.blankDynaform.getButtons()); + }; + that.listDynaform.onEdit = function (row, grid) { + that.edit(row, grid); + }; + that.listDynaform.onDel = function (row, grid) { + that.del(row, grid); + }; + + that.blankDynaform = new BlankDynaform(); + that.blankDynaform.onSave = function () { + that.saveBlank(false); + }; + that.blankDynaform.onSaveOpen = function () { + that.saveBlank(true); + }; + that.blankDynaform.onCancel = function () { + $("input,select,textarea").blur(); + var title = ""; + that.blankDynaform.loseChanges(title); + }; + that.blankDynaform.onYesConfirmCancellation = function () { + if (that.clickedClose) { + that.close(); + } + that.resetView(); + that.setTitle(that.listDynaform.getSuperTitle()); + that.listDynaform.setVisible(true); + }; + + that.addItem(that.listDynaform); + that.addItem(that.blankDynaform); + + that.open(); + that.resetView(); + that.setTitle(that.listDynaform.getSuperTitle()); + that.listDynaform.setVisible(true); + + // hard coding dyn_title textfield because enter keypress reload the current page + if (that.blankDynaform.getItems()[0] + && that.blankDynaform.getItems()[0].controls[0] + && that.blankDynaform.getItems()[0].controls[0].html) { + $(that.blankDynaform.getItems()[0].controls[0].html).keypress(function (e) { + if (e.which == 13) { + e.preventDefault(); + } + }); + } +}; +Dynaform.prototype.saveBlank = function (open) { + var that = this, + data, + restClient, + flagAux; + + if (!that.blankDynaform.isValid()) { + flagAux = that.blankDynaform.visible; + } else { + flagAux = that.blankDynaform.isValid(); + } + + if (flagAux) { + if (getData2PMUI(that.blankDynaform.html).dyn_title == "") { + return false; + } + } + + data = getData2PMUI(that.blankDynaform.html); + data['dyn_version'] = 2; + data['dyn_type'] = 'xmlform'; + restClient = new PMRestClient({ + endpoint: 'dynaform', + typeRequest: 'post', + data: data, + functionSuccess: function (xhr, response) { + if (open) { + that.close(); + try { + PMUI.getActiveCanvas().emptyCurrentSelection(); + } catch (msg) { + } + PMDesigner.dynaformDesigner(response); + } else { + that.resetView(); + that.setTitle(that.listDynaform.getSuperTitle()); + that.listDynaform.setVisible(true); + that.listDynaform.load(); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems creating the dynaform, please try again.'.translate(), + messageSuccess: 'Dynaform saved successfully'.translate(), + flashContainer: that.listDynaform + }); + restClient.executeRestClient(); +}; +Dynaform.prototype.edit = function (row, grid) { + this.close(); + try { + PMUI.getActiveCanvas().emptyCurrentSelection(); + } catch (msg) { + } + PMDesigner.dynaformDesigner(row.getData()); +}; +Dynaform.prototype.del = function (row, grid) { + var that = this, + confirmDeletion = new Mafe.ConfirmDeletion(); + confirmDeletion.setMessage('Do you want to delete this DynaForm?'.translate()); + confirmDeletion.setTitle("Dynaform".translate()); + confirmDeletion.onDelete = function () { + var restClient = new PMRestClient({ + endpoint: 'dynaform/' + row.getData().dyn_uid, + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + that.listDynaform.load(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems deleting the dynaform, please try again.'.translate(), + messageSuccess: 'Dynaform deleted successfully'.translate(), + flashContainer: that.listDynaform + }); + restClient.executeRestClient(); + }; +}; + +(function () { + PMDesigner.dynaform = function () { + var dynaform = new Dynaform(); + }; + PMDesigner.dynaform.create = function () { + var dynaform = new Dynaform(); + dynaform.resetView(); + dynaform.setTitle(dynaform.blankDynaform.getSuperTitle()); + dynaform.blankDynaform.setVisible(true); + dynaform.setButtons(dynaform.blankDynaform.getButtons()); + }; +}()); /** * Updates the granular export feature after enabled features are loaded. @@ -7514,1678 +7514,1678 @@ InputDocument.prototype.build = function () { this.inputDocumentsGetRestProxy(); }; -(function () { +(function () { + + var loadValuesStartTimer, openForm, updateStatus; + + PMDesigner.startTimer = function (element) { + + var startTimer = element, + restClient, + loadServerData, + listUsers, + itemsDaly, + itemsWeekly, + loadOptionsRadio, + itemsMonthly, + itemsOneTime, + itemsEvery, + showProperties, + updateCaseScheduler, + buttonCancel, + loadUsers, + loadDataForm, + formCreateCaseScheduler, + schedulerListWindow, + buttonSave, + dataForm; + + loadValuesStartTimer = function ($flag) { + listUsers = []; + dataForm = []; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'activity/' + startTimer.ports.get(0).connection.flo_element_dest + '/assignee/all', + method: 'GET' + }, + { + url: 'case-scheduler/' + startTimer.evn_uid, + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + listUsers = response[0].response; + dataForm = response[1].response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: [null, 'There are problems loading the Start Timer, please try again.'.translate()] + }); + restClient.executeRestClient(); + if ($flag) { + return listUsers.length; + } + return true; + }; + + updateCaseScheduler = function (data) { + var restProxy = new PMRestClient({ + endpoint: 'case-scheduler/' + startTimer.evn_uid, + typeRequest: 'update', + data: data, + functionSuccess: function (xhr, response) { + formCreateCaseScheduler.reset(); + schedulerListWindow.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: 'Start Timer updated successfully'.translate(), + messageError: 'There are problems updating the Start Timer, please try again.'.translate(), + flashContainer: document.body + }); + restProxy.executeRestClient(); + }; + + updateStatus = function () { + var status = (typeof dataForm.sch_state !== 'undefined') ? ((dataForm.sch_state === 'ACTIVE') ? 'INACTIVE' : 'ACTIVE') : 'INACTIVE'; + dataForm.sch_state = status; + updateCaseScheduler(dataForm); + }; + + //Items for the form Create and edit Case Scheduler + itemsDaly = [ + { + pmType: 'panel', + layout: 'hbox', + items: [ + { + id: 'startDate', + pmType: 'datetime', + label: 'Start date'.translate(), + value: '', + returnFormat: 'yy-mm-dd', + required: true, + dateFormat: 'yy mm dd', + dateTime: false, + name: 'startDate', + valueType: 'date', + labelWidth: '26%' + }, + { + id: 'endDate', + pmType: 'datetime', + label: 'End date'.translate(), + value: '', + returnFormat: 'yy-mm-dd', + required: false, + dateFormat: 'yy mm dd', + dateTime: false, + name: 'endDate', + valueType: 'date' + } + ] + }, + { + id: 'execttime', + pmType: 'text', + label: 'Execution time'.translate(), + value: '', + required: true, + name: 'execttime', + placeholder: '(HH:MM) Format 24 hrs.'.translate(), + valueType: 'string', + validators: [{ + pmType: 'regexp', + criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, + errorMessage: 'Please enter a valid hour.'.translate() + } + ], + helper: 'Example: 1:00, 14:30, 00:00' + } + ]; + + itemsWeekly = [ + { + pmType: 'panel', + layout: 'hbox', + items: [ + { + id: 'startDate', + pmType: 'datetime', + label: 'Start date'.translate(), + value: '', + returnFormat: 'yy-mm-dd', + required: true, + dateFormat: 'yy mm dd', + dateTime: false, + name: 'startDate', + valueType: 'date', + labelWidth: '26%' + }, + { + id: 'endDate', + pmType: 'datetime', + label: 'End date'.translate(), + value: '', + returnFormat: 'yy-mm-dd', + required: false, + dateFormat: 'yy mm dd', + dateTime: false, + name: 'endDate', + valueType: 'date' + } + ] + }, + { + id: 'execttime', + pmType: 'text', + label: 'Execution time'.translate(), + value: '', + required: true, + name: 'execttime', + placeholder: '(HH:MM) Format 24 hrs.'.translate(), + valueType: 'string', + validators: [{ + pmType: 'regexp', + criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, + errorMessage: 'Please enter a valid hour.'.translate() + } + ], + helper: 'Example: 1:00, 14:30, 00:00' + }, + { + id: 'daysoftheweek', + pmType: 'checkbox', + label: 'Select the day(s) of the week below'.translate(), + value: '', + name: 'daysoftheweek', + required: false, + controlPositioning: 'horizontal', + maxDirectionOptions: 3, + options: [ + { + id: 'monday', + label: 'Monday'.translate(), + value: '1' + }, + { + id: 'tuesday', + label: 'Tuesday'.translate(), + value: '2' + }, + { + id: 'wednesday', + label: 'Wednesday'.translate(), + value: '3' + }, + { + id: 'thursday', + label: 'Thursday'.translate(), + value: '4' + }, + { + id: 'friday', + label: 'Friday'.translate(), + value: '5' + }, + { + id: 'saturday', + label: 'Saturday'.translate(), + value: '6' + }, + { + id: 'sunday', + label: 'Sunday'.translate(), + value: '7' + } + ] + } + ]; + + loadOptionsRadio = function (newVal) { + var paneldaysofMonth = formCreateCaseScheduler.getItems()[1].getItems()[2].getItems()[1]; + paneldaysofMonth.setVisible(true); + if (newVal === 'dayofmonth') { + paneldaysofMonth.getItems()[0].setVisible(true); + paneldaysofMonth.getItems()[1].setVisible(false); + } else if (newVal === 'day') { + paneldaysofMonth.getItems()[0].setVisible(false); + paneldaysofMonth.getItems()[1].setVisible(true); + } + }; + + itemsMonthly = [ + { + pmType: 'panel', + layout: 'hbox', + items: [ + { + id: 'startDate', + pmType: 'datetime', + label: 'Start date'.translate(), + value: '', + returnFormat: 'yy-mm-dd', + required: true, + dateFormat: 'yy mm dd', + datetime: false, + name: 'startDate', + valueType: 'date', + labelWidth: '26%' + }, + { + id: 'endDate', + pmType: 'datetime', + label: 'End date'.translate(), + value: '', + returnFormat: 'yy-mm-dd', + required: false, + dateFormat: 'yy mm dd', + datetime: false, + name: 'endDate', + valueType: 'date' + } + ] + }, + { + id: 'execttime', + pmType: 'text', + label: 'Execution time'.translate(), + value: '', + required: true, + name: 'execttime', + placeholder: '(HH:MM) Format 24 hrs.'.translate(), + valueType: 'string', + controlsWidth: 580, + validators: [{ + pmType: 'regexp', + criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, + errorMessage: 'Please enter a valid hour.'.translate() + } + ], + helper: 'Example: 1:00, 14:30, 00:00' + }, + { + pmType: 'panel', + id: 'panelDays', + layout: 'hbox', + items: [ + { + id: 'options', + pmType: 'radio', + label: '', + value: '', + name: 'options', + required: false, + controlPositioning: 'vertical', + maxDirectionOptions: 4, + options: [ + { + id: 'dayMonth', + label: 'Day of month'.translate(), + value: 'dayofmonth' + }, + { + id: 'day', + label: 'The day'.translate(), + value: 'day' + } + ], + onChange: function (newVal, oldVal) { + loadOptionsRadio(newVal); + }, + labelWidth: '46%' + }, + { + pmType: 'panel', + id: 'paneldaysofMonth', + layout: 'vbox', + items: [ + { + id: 'dayoftheMonth', + pmType: 'text', + label: '', + value: '', + placeholder: 'Day of the month (example: 1)'.translate(), + required: false, + name: 'dayMonth', + valueType: 'string' + }, + { + pmType: 'panel', + id: 'panelmonth', + layout: 'hbox', + items: [ + { + id: 'first', + pmType: 'dropdown', + label: '', + value: '', + required: false, + name: 'first', + valueType: 'string', + options: [ + { + label: 'First'.translate(), + value: '1' + }, + { + label: 'Second'.translate(), + value: '2' + }, + { + label: 'Third'.translate(), + value: '3' + }, + { + label: 'Fourth'.translate(), + value: '4' + }, + { + label: 'Last'.translate(), + value: '5' + } + ], + controlsWidth: 100 + }, + { + id: 'day', + pmType: 'dropdown', + label: '', + value: '', + required: false, + name: 'day', + valueType: 'string', + options: [ + { + label: 'Monday'.translate(), + value: '1' + }, + { + label: 'Tuesday'.translate(), + value: '2' + }, + { + label: 'Wednesday'.translate(), + value: '3' + }, + { + label: 'Thursday'.translate(), + value: '4' + }, + { + label: 'Friday'.translate(), + value: '5' + }, + { + label: 'Saturday'.translate(), + value: '6' + }, + { + label: 'Sunday'.translate(), + value: '7' + } + ], + controlsWidth: 100 + } + ] + } + ] + } + ] + }, + { + id: 'months', + pmType: 'checkbox', + label: 'Of the month(s)'.translate(), + value: '', + name: 'months', + required: false, + controlPositioning: 'horizontal', + maxDirectionOptions: 4, + options: [ + { + id: 'jan', + label: 'Jan'.translate(), + value: '1' + }, + { + id: 'feb', + label: 'Feb'.translate(), + value: '2' + }, + { + id: 'mar', + label: 'Mar'.translate(), + value: '3' + }, + { + id: 'apr', + label: 'Apr'.translate(), + value: '4' + }, + { + id: 'may', + label: 'May'.translate(), + value: '5' + }, + { + id: 'jun', + label: 'Jun'.translate(), + value: '6' + }, + { + id: 'jul', + label: 'Jul'.translate(), + value: '7' + }, + { + id: 'aug', + label: 'Aug'.translate(), + value: '8' + }, + { + id: 'sep', + label: 'Sep'.translate(), + value: '9' + }, + { + id: 'oct', + label: 'Oct'.translate(), + value: '10' + }, + { + id: 'nov', + label: 'Nov'.translate(), + value: '11' + }, + { + id: 'dec', + label: 'Dec'.translate(), + value: '12' + } + ] + } + ]; + + itemsOneTime = [{ + id: 'execttime', + pmType: 'text', + label: 'Execution time'.translate(), + value: '', + required: true, + name: 'execttime', + placeholder: '(HH:MM) Format 24 hrs.'.translate(), + valueType: 'string', + validators: [{ + pmType: 'regexp', + criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, + errorMessage: 'Please enter a valid hour.'.translate() + } + ], + helper: 'Example: 1:00, 14:30, 00:00' + }]; + + itemsEvery = [{ + id: 'execttime', + pmType: 'text', + label: 'Execute every Hour(s)'.translate(), + value: '', + required: true, + name: 'execttime', + valueType: 'string', + placeholder: '(HH:MM) Format 24 hrs.'.translate(), + validators: [{ + pmType: 'regexp', + criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, + errorMessage: 'Please enter a valid hour.'.translate() + } + ], + helper: 'Example: 1:00, 14:30, 00:00' + }]; + + showProperties = function (newValue) { + switch (newValue) { + case 'daily': + formCreateCaseScheduler.getItems()[1].clearItems(); + formCreateCaseScheduler.getItems()[1].setVisible(true); + formCreateCaseScheduler.getItems()[1].setItems(itemsDaly); + break; + case 'weekly': + formCreateCaseScheduler.getItems()[1].clearItems(); + formCreateCaseScheduler.getItems()[1].setVisible(true); + formCreateCaseScheduler.getItems()[1].setItems(itemsWeekly); + break; + case 'monthly': + formCreateCaseScheduler.getItems()[1].clearItems(); + formCreateCaseScheduler.getItems()[1].setVisible(true); + formCreateCaseScheduler.getItems()[1].setItems(itemsMonthly); + var paneldaysofMonth = formCreateCaseScheduler.getItems()[1].getItems()[2].getItems()[1]; + paneldaysofMonth.setVisible(false); + formCreateCaseScheduler.getItems()[1].getItems()[2].getItems()[0].hideColon(); + paneldaysofMonth.getItems()[0].hideColon(); + paneldaysofMonth.getItems()[1].getItems()[0].hideColon(); + paneldaysofMonth.getItems()[1].getItems()[1].hideColon(); + break; + case 'oneTime': + formCreateCaseScheduler.getItems()[1].clearItems(); + formCreateCaseScheduler.getItems()[1].setVisible(true); + formCreateCaseScheduler.getItems()[1].setItems(itemsOneTime); + break; + case 'every': + formCreateCaseScheduler.getItems()[1].clearItems(); + formCreateCaseScheduler.getItems()[1].setVisible(true); + formCreateCaseScheduler.getItems()[1].setItems(itemsEvery); + validateKeysField(formCreateCaseScheduler.getField('execttime').getControls()[0].getHTML(), ['isnumber', 'iscolon']); + break; + } + }; + + //Form to Edit and create the Case Scheduler + formCreateCaseScheduler = new PMUI.form.Form({ + id: 'formCreateCaseScheduler', + border: false, + visibleHeader: false, + width: '925px', + name: 'formcreate', + title: '', + items: [ + { + id: 'panelProperties', + pmType: 'panel', + layout: 'vbox', + fieldset: true, + height: '350px', + legend: 'Properties'.translate(), + items: [ + { + id: 'state', + pmType: 'dropdown', + label: 'Status'.translate(), + name: 'state', + required: true, + value: '', + controlsWidth: 150, + options: [ + { + value: 'ACTIVE', + label: 'Active'.translate() + }, + { + value: 'INACTIVE', + label: 'Inactive'.translate() + } + ] + }, + { + id: 'username', + pmType: 'dropdown', + label: 'User'.translate(), + name: 'username', + required: true, + controlsWidth: 300, + value: '', + options: [], + onChange: function (newValue, prevValue) { + } + }, + { + id: 'name', + pmType: 'text', + label: 'Name'.translate(), + value: startTimer.evn_name, + required: true, + name: 'name', + visible: false, + valueType: 'string' + }, + { + id: 'performTask', + pmType: 'dropdown', + label: 'Perform this task'.translate(), + name: 'performTask', + required: true, + value: '', + controlsWidth: 300, + options: [ + { + label: '- Select -'.translate(), + value: '', + disabled: true, + selected: true + }, + { + value: 'daily', + label: 'Daily'.translate() + }, + { + value: 'weekly', + label: 'Weekly'.translate() + }, + { + value: 'monthly', + label: 'Monthly'.translate() + }, + { + value: 'oneTime', + label: 'One Time Only'.translate() + }, + { + value: 'every', + label: 'Every'.translate() + } + ], + onChange: function (newValue, prevValue) { + showProperties(newValue); + } + } + ] + }, + { + id: 'panelSelectDate', + pmType: 'panel', + layout: 'vbox', + fieldset: true, + visible: false, + height: '350px', + legend: 'Select the date and time for case(s) to be initiated.'.translate(), + items: [] + } + ] + }); + + buttonCancel = new PMUI.ui.Button({ + id: 'cancelSchedulerButton', + text: 'Cancel'.translate(), + buttonType: 'error', + handler: function (event) { + if (formCreateCaseScheduler.isDirty()) { + var message_window = new PMUI.ui.MessageWindow({ + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + id: 'cancelMessageStartTimer', + title: 'Start Timer Event'.translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: 'No'.translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: 'Yes'.translate(), + handler: function () { + message_window.close(); + schedulerListWindow.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + formCreateCaseScheduler.reset(); + schedulerListWindow.close(); + } + } + }); + + //Window Buttons + buttonSave = new PMUI.ui.Button({ + id: 'saveSchedulerButton', + text: 'Save'.translate(), + height: 31, + buttonType: 'success', + handler: function (event) { + if (formCreateCaseScheduler.isValid()) { + var dataFormCreate = formCreateCaseScheduler.getData(); + + var dataToSend = { + sch_del_user_name: dataFormCreate.username, + sch_name: startTimer.evn_name, + tas_uid: startTimer.ports.get(0).connection.flo_element_dest, + sch_start_time: '', + sch_start_date: '', + sch_week_days: '', + sch_start_day: '', + sch_start_day_opt_1: '', + sch_start_day_opt_2: '', + sch_months: '', + sch_end_date: '', + sch_repeat_every: '', + sch_state: (dataFormCreate.state !== '') ? dataFormCreate.state : 'ACTIVE', + sch_option: '' + }; + + var perform = dataFormCreate.performTask; + switch (perform) { + case 'daily': + dataToSend.sch_option = '1'; + dataToSend.sch_start_time = dataFormCreate.execttime; + dataToSend.sch_start_date = dataFormCreate.startDate; + dataToSend.sch_end_date = dataFormCreate.endDate; + break; + case 'weekly': + var formdays = eval(dataFormCreate.daysoftheweek); + var days = ''; + for (i = 0; i < formdays.length; i += 1) { + if (i !== (formdays.length - 1)) { + days += formdays[i] + '|'; + } else { + days += formdays[i]; + } + } + + dataToSend.sch_option = '2'; + dataToSend.sch_start_time = dataFormCreate.execttime; + dataToSend.sch_start_date = dataFormCreate.startDate; + dataToSend.sch_end_date = dataFormCreate.endDate; + dataToSend.sch_week_days = days; + break; + case 'monthly': + dataToSend.sch_option = '3'; + dataToSend.sch_start_time = dataFormCreate.execttime; + dataToSend.sch_start_date = dataFormCreate.startDate; + dataToSend.sch_end_date = dataFormCreate.endDate; + if (dataFormCreate.options === 'dayofmonth') { + var formmonths = eval(dataFormCreate.months); + var months = ''; + for (i = 0; i < formmonths.length; i += 1) { + if (i !== (formmonths.length - 1)) { + months += formmonths[i] + '|'; + } else { + months += formmonths[i]; + } + } + dataToSend.sch_start_day = '1'; //Day of month + dataToSend.sch_start_day_opt_1 = dataFormCreate.dayMonth;//1 to 31 - day of the month + } else if (dataFormCreate.options === 'day') { + var opt2 = dataFormCreate.first + '|' + dataFormCreate.day; + var formmonths = eval(dataFormCreate.months); + var months = ''; + for (i = 0; i < formmonths.length; i += 1) { + if (i !== (formmonths.length - 1)) { + months += formmonths[i] + '|'; + } else { + months += formmonths[i]; + } + } + dataToSend.sch_start_day = '2'; //Day of month + dataToSend.sch_start_day_opt_2 = opt2;//1 to 31 - day of the month + + } + dataToSend.sch_months = months; + break; + case 'oneTime': + dataToSend.sch_option = '4'; + dataToSend.sch_start_time = dataFormCreate.execttime; + break; + case 'every': + dataToSend.sch_option = '5'; + dataToSend.sch_repeat_every = timeToDecimal(dataFormCreate.execttime).toFixed(2); + break; + } + updateCaseScheduler(dataToSend); + } + } + }); + + //load users + loadUsers = function () { + var field = formCreateCaseScheduler.getField('username'); + field.clearOptions(); + for (var i = 0; i < listUsers.length; i += 1) { + field.addOption({ + value: listUsers[i].aas_username, + label: listUsers[i].aas_name + ' ' + listUsers[i].aas_lastname + }); + } + }; + + loadDataForm = function () { + var loadTime, + option, + daysVal, + monthsVal, + monthsop, + days, + i, + startTime, + finallyST, + dataEdit; + + loadTime = function (dataEdit, dataForm) { + var starDate, + startTime, + finallyST, + endDate; + starDate = dataForm.sch_start_date ? dataForm.sch_start_date.split(' ') : ['']; + endDate = dataForm.sch_end_date ? dataForm.sch_end_date.split(' ') : ['']; + + startTime = dataForm.sch_start_time.split(' '); + startTime = startTime[1].split(':'); + finallyST = startTime[0] + ':' + startTime[1]; + dataEdit[4].setValue(starDate[0]); + dataEdit[5].setValue(endDate[0]); + dataEdit[6].setValue(finallyST); + }; + + dataEdit = formCreateCaseScheduler.getFields(); + + dataEdit[0].setValue(dataForm.sch_state); + dataEdit[1].setValue(dataForm.sch_del_user_name); + option = 'daily'; + switch (dataForm.sch_option) { + case '1': + option = 'daily'; + dataEdit[3].setValue(option); + showProperties(option); + dataEdit = formCreateCaseScheduler.getFields(); + loadTime(dataEdit, dataForm); + break; + case '2': + option = 'weekly'; + dataEdit[3].setValue(option); + showProperties(option); + dataEdit = formCreateCaseScheduler.getFields(); + loadTime(dataEdit, dataForm); + + daysVal = "[\""; + days = dataForm.sch_week_days.split('|'); + for (i = 0; i < days.length; i += 1) { + if (i !== (days.length - 1)) { + daysVal += days[i] + "\",\""; + } else { + daysVal += days[i] + "\"]"; + } + } + dataEdit[7].setValue(daysVal); + break; + case '3': + option = 'monthly'; + dataEdit[3].setValue(option); + showProperties(option); + dataEdit = formCreateCaseScheduler.getFields(); + loadTime(dataEdit, dataForm); + days = []; + if (dataForm.sch_start_day !== '') { + days = dataForm.sch_start_day.split('|'); + } + + if (days[0] === '1') { + dataEdit[7].setValue('dayofmonth'); + loadOptionsRadio('dayofmonth'); + dataEdit[8].setValue(days[1]); + } else if (days[0] === '2') { + dataEdit[7].setValue('day'); + loadOptionsRadio('day'); + dataEdit[9].setValue(days[1]); + dataEdit[10].setValue(days[2]); + } + monthsVal = "[\""; + monthsop = dataForm.sch_months.split('|'); + for (i = 0; i < monthsop.length; i += 1) { + if (i !== (monthsop.length - 1)) { + monthsVal += monthsop[i] + "\",\""; + } else { + monthsVal += monthsop[i] + "\"]"; + } + } + dataEdit[11].setValue(monthsVal); + break; + case '4': + option = 'oneTime'; + dataEdit[3].setValue(option); + showProperties(option); + dataEdit = formCreateCaseScheduler.getFields(); + startTime = dataForm.sch_start_time.split(' '); + startTime = startTime[1].split(':'); + finallyST = startTime[0] + ':' + startTime[1]; + dataEdit[4].setValue(finallyST); + break; + case '5': + option = 'every'; + dataEdit[3].setValue(option); + showProperties(option); + dataEdit = formCreateCaseScheduler.getFields(); + dataEdit[4].setValue(decimalToTime(parseFloat(dataForm.sch_repeat_every))); + break; + } + }; + + //Main window Case Scheduler + schedulerListWindow = new PMUI.ui.Window({ + id: 'schedulerListWindow', + title: 'Start Timer Event'.translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + buttonPanelPosition: 'top', + buttons: [ + buttonSave, + {pmType: 'label', text: 'or'}, + buttonCancel + ] + }); + + openForm = function () { + schedulerListWindow.addItem(formCreateCaseScheduler); + schedulerListWindow.open(); + loadUsers(); + loadDataForm(); + applyStyleWindowForm(schedulerListWindow); + schedulerListWindow.showFooter(); + schedulerListWindow.defineEvents(); + }; + }; + + PMDesigner.startTimer.openForm = function (element) { + openForm(); + }; + + PMDesigner.startTimer.validate = function (element) { + if (element.ports.isEmpty()) { + PMDesigner.msgFlash('Must connect to a Task'.translate(), document.body, 'error', 3000, 5); + return false; + } + PMDesigner.startTimer(element); + if (loadValuesStartTimer(true) === 0) { + PMDesigner.msgFlash('The task doesn\'t have assigned users'.translate(), document.body, 'info', 3000, 5); + return false; + } + return true; + }; + +}()); +( + function () { + var dataBaseConnectionOption, + winFrmDataBaseConnectionShow, + frmDataBaseConnection, + closeClicked = true; - var loadValuesStartTimer, openForm, updateStatus; + PMDesigner.database = function (event) { + var winGrdpnlDataBaseConnection, + panelTest, + grdpnlDataBaseConnection, + flagError, + titleOld, + btnNew, + btnTestConnection, + btnCreate, + btnCancel, + testShow, + isDirtyFrmDataBaseConnection, + showForm, + listDBConnection, + refreshGridPanelInMainWindow, + dataBaseConnectionsGetRestProxy, + dataBaseConnectionPostTestRestProxy, + dataBaseConnectionGetRestProxy, + dataBaseConnectionPutRestProxy, + dataBaseConnectionDeleteRestProxy, + dataBaseConnectionPostRestProxy, + cboEngineSetOptionsRestProxy, + showEncoderOptions, + hideEncoderOptions, + cboConnectionTypeOracleSetOptions, + cboEncodeSetOptionsRestProxy, + winFrmDataBaseConnectionShow, + cboEngine, + txtUID, + cboEncode, + txtTns, + txtServer, + txtDataBaseName, + disableAllItems, + txtUsername, + txtPassword, + txtPort, + btnBack, + txtDescription, + cboConnectionTypeOracle, + dataBaseConnectionData; - PMDesigner.startTimer = function (element) { + disableAllItems = function () { + winGrdpnlDataBaseConnection.getItems()[0].setVisible(false); + winGrdpnlDataBaseConnection.getItems()[1].setVisible(false); + winGrdpnlDataBaseConnection.getItems()[2].setVisible(false); - var startTimer = element, - restClient, - loadServerData, - listUsers, - itemsDaly, - itemsWeekly, - loadOptionsRadio, - itemsMonthly, - itemsOneTime, - itemsEvery, - showProperties, - updateCaseScheduler, - buttonCancel, - loadUsers, - loadDataForm, - formCreateCaseScheduler, - schedulerListWindow, - buttonSave, - dataForm; + txtUID.setVisible(false); + btnTestConnection.setVisible(false); + btnBack.setVisible(false); + btnCreate.setVisible(false); + btnCancel.setVisible(false); + }; - loadValuesStartTimer = function ($flag) { - listUsers = []; - dataForm = []; - restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - calls: [ - { - url: 'activity/' + startTimer.ports.get(0).connection.flo_element_dest + '/assignee/all', - method: 'GET' - }, - { - url: 'case-scheduler/' + startTimer.evn_uid, - method: 'GET' - } - ] - }, - functionSuccess: function (xhr, response) { - listUsers = response[0].response; - dataForm = response[1].response; - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: [null, 'There are problems loading the Start Timer, please try again.'.translate()] - }); - restClient.executeRestClient(); - if ($flag) { - return listUsers.length; - } - return true; - }; + testShow = function (testData) { + var msg = "", titleSummary, style, i, flag; + flagError = 0; + disableAllItems(); + titleOld = winGrdpnlDataBaseConnection.getTitle(); + winGrdpnlDataBaseConnection.setTitle("Testing Server Connection".translate()); + winGrdpnlDataBaseConnection.getItems()[2].setVisible(true); - updateCaseScheduler = function (data) { - var restProxy = new PMRestClient({ - endpoint: 'case-scheduler/' + startTimer.evn_uid, - typeRequest: 'update', - data: data, - functionSuccess: function (xhr, response) { - formCreateCaseScheduler.reset(); - schedulerListWindow.close(); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageSuccess: 'Start Timer updated successfully'.translate(), - messageError: 'There are problems updating the Start Timer, please try again.'.translate(), - flashContainer: document.body - }); - restProxy.executeRestClient(); - }; + for (i = 0; i <= testData.length - 1; i += 1) { + flag = (typeof(testData[i].error) != "undefined") ? 1 : 0; + if (flag != 1) { + msg = msg + "" + testData[i].test + "
"; + } else { + msg = msg + "" + testData[i].error + "
"; + } - updateStatus = function () { - var status = (typeof dataForm.sch_state !== 'undefined') ? ((dataForm.sch_state === 'ACTIVE') ? 'INACTIVE' : 'ACTIVE') : 'INACTIVE'; - dataForm.sch_state = status; - updateCaseScheduler(dataForm); - }; + if (typeof(testData[i].error) != "undefined" && flagError == 0) { + flagError = 1; + } + } + if (flag == 0) { + btnCreate.setVisible(true); + btnBack.setVisible(true); + } else { + btnBack.setVisible(true); + } - //Items for the form Create and edit Case Scheduler - itemsDaly = [ - { - pmType: 'panel', - layout: 'hbox', - items: [ - { - id: 'startDate', - pmType: 'datetime', - label: 'Start date'.translate(), - value: '', - returnFormat: 'yy-mm-dd', - required: true, - dateFormat: 'yy mm dd', - dateTime: false, - name: 'startDate', - valueType: 'date', - labelWidth: '26%' - }, - { - id: 'endDate', - pmType: 'datetime', - label: 'End date'.translate(), - value: '', - returnFormat: 'yy-mm-dd', - required: false, - dateFormat: 'yy mm dd', - dateTime: false, - name: 'endDate', - valueType: 'date' + titleSummary = "
Testing Database Server configuration
"; + + style = $('#panelTest').attr("style"); + titleSummary = titleSummary + "
" + msg + "
"; + $('#panelTest').empty(); + style = style + ' background: #FFFFFF; font: normal 0.8em arial;'; + $('#panelTest').attr("style", style); + $('#panelTest').append(titleSummary); + }; + + isDirtyFrmDataBaseConnection = function () { + var message_window; + $("input,select,textarea").blur(); + if (frmDataBaseConnection.isVisible()) { + if (frmDataBaseConnection.isDirty()) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: "Database Connections".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + dataBaseConnectionOption = ""; + if (closeClicked) { + winGrdpnlDataBaseConnection.close(); + } + refreshGridPanelInMainWindow(false); + }, + buttonType: "success" + } + ], + title: 'Confirm'.translate() + }); + message_window.open(); + message_window.showFooter(); + } else { + if (closeClicked) { + winGrdpnlDataBaseConnection.close(); + } else { + dataBaseConnectionOption = ""; + refreshGridPanelInMainWindow(false); + } } - ] - }, - { - id: 'execttime', - pmType: 'text', - label: 'Execution time'.translate(), - value: '', - required: true, - name: 'execttime', - placeholder: '(HH:MM) Format 24 hrs.'.translate(), - valueType: 'string', - validators: [{ - pmType: 'regexp', - criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, - errorMessage: 'Please enter a valid hour.'.translate() + } else { + winGrdpnlDataBaseConnection.close(); } - ], - helper: 'Example: 1:00, 14:30, 00:00' + }; + showForm = function () { + disableAllItems(); + winGrdpnlDataBaseConnection.setTitle(titleOld); + winGrdpnlDataBaseConnection.getItems()[1].setVisible(true); + btnTestConnection.setVisible(true); + btnCancel.setVisible(true); } - ]; - itemsWeekly = [ - { - pmType: 'panel', - layout: 'hbox', - items: [ - { - id: 'startDate', - pmType: 'datetime', - label: 'Start date'.translate(), - value: '', - returnFormat: 'yy-mm-dd', - required: true, - dateFormat: 'yy mm dd', - dateTime: false, - name: 'startDate', - valueType: 'date', - labelWidth: '26%' - }, - { - id: 'endDate', - pmType: 'datetime', - label: 'End date'.translate(), - value: '', - returnFormat: 'yy-mm-dd', - required: false, - dateFormat: 'yy mm dd', - dateTime: false, - name: 'endDate', - valueType: 'date' - } - ] - }, - { - id: 'execttime', - pmType: 'text', - label: 'Execution time'.translate(), - value: '', - required: true, - name: 'execttime', - placeholder: '(HH:MM) Format 24 hrs.'.translate(), - valueType: 'string', - validators: [{ - pmType: 'regexp', - criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, - errorMessage: 'Please enter a valid hour.'.translate() + refreshGridPanelInMainWindow = function (load) { + disableAllItems(); + winGrdpnlDataBaseConnection.hideFooter(); + dataBaseConnectionOption = ""; + winGrdpnlDataBaseConnection.getItems()[0].setVisible(true); + winGrdpnlDataBaseConnection.setTitle("Database Connections".translate()); + load = load != null ? load : true; + if (load) { + dataBaseConnectionsGetRestProxy(grdpnlDataBaseConnection); } - ], - helper: 'Example: 1:00, 14:30, 00:00' - }, - { - id: 'daysoftheweek', - pmType: 'checkbox', - label: 'Select the day(s) of the week below'.translate(), - value: '', - name: 'daysoftheweek', - required: false, - controlPositioning: 'horizontal', - maxDirectionOptions: 3, - options: [ - { - id: 'monday', - label: 'Monday'.translate(), - value: '1' - }, - { - id: 'tuesday', - label: 'Tuesday'.translate(), - value: '2' + }; + + dataBaseConnectionsGetRestProxy = function (grdpnl) { + var restProxy = new PMRestClient({ + endpoint: "database-connections", + typeRequest: "get", + functionSuccess: function (xhr, response) { + listDBConnection = response; + grdpnl.setDataItems(listDBConnection); + grdpnl.sort('dbs_database_name', 'asc'); }, - { - id: 'wednesday', - label: 'Wednesday'.translate(), - value: '3' + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + dataBaseConnectionPostTestRestProxy = function (data) { + var restProxy = new PMRestClient({ + endpoint: "database-connection/test", + typeRequest: "post", + data: data, + functionSuccess: function (xhr, response) { + testShow(response); }, - { - id: 'thursday', - label: 'Thursday'.translate(), - value: '4' + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + dataBaseConnectionGetRestProxy = function (dataBaseConnectionUid) { + var restProxy = new PMRestClient({ + endpoint: "database-connection/" + dataBaseConnectionUid, + typeRequest: "get", + functionSuccess: function (xhr, response) { + var data = response; + dataBaseConnectionOption = "PUT"; + winFrmDataBaseConnectionShow("PUT", data); }, - { - id: 'friday', - label: 'Friday'.translate(), - value: '5' + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restProxy.executeRestClient(); + }; + + dataBaseConnectionPutRestProxy = function (dataBaseConnectionUid, data) { + var restProxy = new PMRestClient({ + endpoint: "database-connection/" + dataBaseConnectionUid, + typeRequest: "update", + data: data, + functionSuccess: function (xhr, response) { + refreshGridPanelInMainWindow(); }, - { - id: 'saturday', - label: 'Saturday'.translate(), - value: '6' + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); }, - { - id: 'sunday', - label: 'Sunday'.translate(), - value: '7' - } - ] - } - ]; + messageSuccess: 'Database connection edited successfully'.translate(), + flashContainer: grdpnlDataBaseConnection + }); - loadOptionsRadio = function (newVal) { - var paneldaysofMonth = formCreateCaseScheduler.getItems()[1].getItems()[2].getItems()[1]; - paneldaysofMonth.setVisible(true); - if (newVal === 'dayofmonth') { - paneldaysofMonth.getItems()[0].setVisible(true); - paneldaysofMonth.getItems()[1].setVisible(false); - } else if (newVal === 'day') { - paneldaysofMonth.getItems()[0].setVisible(false); - paneldaysofMonth.getItems()[1].setVisible(true); - } - }; + restProxy.executeRestClient(); + }; - itemsMonthly = [ - { - pmType: 'panel', - layout: 'hbox', - items: [ - { - id: 'startDate', - pmType: 'datetime', - label: 'Start date'.translate(), - value: '', - returnFormat: 'yy-mm-dd', - required: true, - dateFormat: 'yy mm dd', - datetime: false, - name: 'startDate', - valueType: 'date', - labelWidth: '26%' + dataBaseConnectionDeleteRestProxy = function (dataBaseConnectionUid) { + var restProxy = new PMRestClient({ + endpoint: "database-connection/" + dataBaseConnectionUid, + typeRequest: "remove", + functionSuccess: function (xhr, response) { + refreshGridPanelInMainWindow(); }, - { - id: 'endDate', - pmType: 'datetime', - label: 'End date'.translate(), - value: '', - returnFormat: 'yy-mm-dd', - required: false, - dateFormat: 'yy mm dd', - datetime: false, - name: 'endDate', - valueType: 'date' - } - ] - }, - { - id: 'execttime', - pmType: 'text', - label: 'Execution time'.translate(), - value: '', - required: true, - name: 'execttime', - placeholder: '(HH:MM) Format 24 hrs.'.translate(), - valueType: 'string', - controlsWidth: 580, - validators: [{ - pmType: 'regexp', - criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, - errorMessage: 'Please enter a valid hour.'.translate() - } - ], - helper: 'Example: 1:00, 14:30, 00:00' - }, - { - pmType: 'panel', - id: 'panelDays', - layout: 'hbox', - items: [ - { - id: 'options', - pmType: 'radio', - label: '', - value: '', - name: 'options', - required: false, - controlPositioning: 'vertical', - maxDirectionOptions: 4, - options: [ - { - id: 'dayMonth', - label: 'Day of month'.translate(), - value: 'dayofmonth' - }, - { - id: 'day', - label: 'The day'.translate(), - value: 'day' - } - ], - onChange: function (newVal, oldVal) { - loadOptionsRadio(newVal); - }, - labelWidth: '46%' - }, - { - pmType: 'panel', - id: 'paneldaysofMonth', - layout: 'vbox', - items: [ - { - id: 'dayoftheMonth', - pmType: 'text', - label: '', - value: '', - placeholder: 'Day of the month (example: 1)'.translate(), - required: false, - name: 'dayMonth', - valueType: 'string' - }, - { - pmType: 'panel', - id: 'panelmonth', - layout: 'hbox', - items: [ - { - id: 'first', - pmType: 'dropdown', - label: '', - value: '', - required: false, - name: 'first', - valueType: 'string', - options: [ - { - label: 'First'.translate(), - value: '1' - }, - { - label: 'Second'.translate(), - value: '2' - }, - { - label: 'Third'.translate(), - value: '3' - }, - { - label: 'Fourth'.translate(), - value: '4' - }, - { - label: 'Last'.translate(), - value: '5' - } - ], - controlsWidth: 100 - }, - { - id: 'day', - pmType: 'dropdown', - label: '', - value: '', - required: false, - name: 'day', - valueType: 'string', - options: [ - { - label: 'Monday'.translate(), - value: '1' - }, - { - label: 'Tuesday'.translate(), - value: '2' - }, - { - label: 'Wednesday'.translate(), - value: '3' - }, - { - label: 'Thursday'.translate(), - value: '4' - }, - { - label: 'Friday'.translate(), - value: '5' - }, - { - label: 'Saturday'.translate(), - value: '6' - }, - { - label: 'Sunday'.translate(), - value: '7' - } - ], - controlsWidth: 100 - } - ] - } - ] - } - ] - }, - { - id: 'months', - pmType: 'checkbox', - label: 'Of the month(s)'.translate(), - value: '', - name: 'months', - required: false, - controlPositioning: 'horizontal', - maxDirectionOptions: 4, - options: [ - { - id: 'jan', - label: 'Jan'.translate(), - value: '1' - }, - { - id: 'feb', - label: 'Feb'.translate(), - value: '2' - }, - { - id: 'mar', - label: 'Mar'.translate(), - value: '3' - }, - { - id: 'apr', - label: 'Apr'.translate(), - value: '4' - }, - { - id: 'may', - label: 'May'.translate(), - value: '5' - }, - { - id: 'jun', - label: 'Jun'.translate(), - value: '6' - }, - { - id: 'jul', - label: 'Jul'.translate(), - value: '7' - }, - { - id: 'aug', - label: 'Aug'.translate(), - value: '8' + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); }, - { - id: 'sep', - label: 'Sep'.translate(), - value: '9' + messageSuccess: 'Database connection deleted successfully'.translate(), + flashContainer: grdpnlDataBaseConnection + }); + restProxy.executeRestClient(); + }; + + dataBaseConnectionPostRestProxy = function (data) { + var restProxy = new PMRestClient({ + endpoint: "database-connection", + typeRequest: "post", + data: data, + functionSuccess: function (xhr, response) { + refreshGridPanelInMainWindow(); }, - { - id: 'oct', - label: 'Oct'.translate(), - value: '10' + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + + refreshGridPanelInMainWindow(); }, - { - id: 'nov', - label: 'Nov'.translate(), - value: '11' + messageError: 'An unexpected error while deleting the DB Connection, please try again later.'.translate(), + messageSuccess: 'Database connection saved successfully'.translate(), + flashContainer: grdpnlDataBaseConnection + }); + + restProxy.executeRestClient(); + }; + + cboEngineSetOptionsRestProxy = function (cboEngine, cboEncode) { + cboEngine.clearOptions(); + var restProxy = new PMRestClient({ + typeRequest: "get", + functionSuccess: function (xhr, response) { + var data = response, + i, + arrayOptions = []; + for (i = 0; i <= data.length - 1; i += 1) { + arrayOptions.push( + { + value: data[i].id, + label: data[i].name + } + ); + } + cboEngine.setOptions(arrayOptions); + cboEngine.setValue(arrayOptions[0].value); + cboEncodeSetOptionsRestProxy(cboEngine.getValue(), cboEncode); }, - { - id: 'dec', - label: 'Dec'.translate(), - value: '12' + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); } - ] - } - ]; + }); - itemsOneTime = [{ - id: 'execttime', - pmType: 'text', - label: 'Execution time'.translate(), - value: '', - required: true, - name: 'execttime', - placeholder: '(HH:MM) Format 24 hrs.'.translate(), - valueType: 'string', - validators: [{ - pmType: 'regexp', - criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, - errorMessage: 'Please enter a valid hour.'.translate() - } - ], - helper: 'Example: 1:00, 14:30, 00:00' - }]; + restProxy.setBaseEndPoint("system/db-engines"); + restProxy.executeRestClient(); + }; - itemsEvery = [{ - id: 'execttime', - pmType: 'text', - label: 'Execute every Hour(s)'.translate(), - value: '', - required: true, - name: 'execttime', - valueType: 'string', - placeholder: '(HH:MM) Format 24 hrs.'.translate(), - validators: [{ - pmType: 'regexp', - criteria: /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/, - errorMessage: 'Please enter a valid hour.'.translate() - } - ], - helper: 'Example: 1:00, 14:30, 00:00' - }]; - - showProperties = function (newValue) { - switch (newValue) { - case 'daily': - formCreateCaseScheduler.getItems()[1].clearItems(); - formCreateCaseScheduler.getItems()[1].setVisible(true); - formCreateCaseScheduler.getItems()[1].setItems(itemsDaly); - break; - case 'weekly': - formCreateCaseScheduler.getItems()[1].clearItems(); - formCreateCaseScheduler.getItems()[1].setVisible(true); - formCreateCaseScheduler.getItems()[1].setItems(itemsWeekly); - break; - case 'monthly': - formCreateCaseScheduler.getItems()[1].clearItems(); - formCreateCaseScheduler.getItems()[1].setVisible(true); - formCreateCaseScheduler.getItems()[1].setItems(itemsMonthly); - var paneldaysofMonth = formCreateCaseScheduler.getItems()[1].getItems()[2].getItems()[1]; - paneldaysofMonth.setVisible(false); - formCreateCaseScheduler.getItems()[1].getItems()[2].getItems()[0].hideColon(); - paneldaysofMonth.getItems()[0].hideColon(); - paneldaysofMonth.getItems()[1].getItems()[0].hideColon(); - paneldaysofMonth.getItems()[1].getItems()[1].hideColon(); - break; - case 'oneTime': - formCreateCaseScheduler.getItems()[1].clearItems(); - formCreateCaseScheduler.getItems()[1].setVisible(true); - formCreateCaseScheduler.getItems()[1].setItems(itemsOneTime); - break; - case 'every': - formCreateCaseScheduler.getItems()[1].clearItems(); - formCreateCaseScheduler.getItems()[1].setVisible(true); - formCreateCaseScheduler.getItems()[1].setItems(itemsEvery); - validateKeysField(formCreateCaseScheduler.getField('execttime').getControls()[0].getHTML(), ['isnumber', 'iscolon']); - break; - } - }; + hideEncoderOptions = function () { + cboEncode.setVisible(true); + cboConnectionTypeOracle.setVisible(true); + }; - //Form to Edit and create the Case Scheduler - formCreateCaseScheduler = new PMUI.form.Form({ - id: 'formCreateCaseScheduler', - border: false, - visibleHeader: false, - width: '925px', - name: 'formcreate', - title: '', - items: [ - { - id: 'panelProperties', - pmType: 'panel', - layout: 'vbox', - fieldset: true, - height: '350px', - legend: 'Properties'.translate(), - items: [ - { - id: 'state', - pmType: 'dropdown', - label: 'Status'.translate(), - name: 'state', - required: true, - value: '', - controlsWidth: 150, - options: [ - { - value: 'ACTIVE', - label: 'Active'.translate() - }, - { - value: 'INACTIVE', - label: 'Inactive'.translate() - } - ] - }, - { - id: 'username', - pmType: 'dropdown', - label: 'User'.translate(), - name: 'username', - required: true, - controlsWidth: 300, - value: '', - options: [], - onChange: function (newValue, prevValue) { - } - }, - { - id: 'name', - pmType: 'text', - label: 'Name'.translate(), - value: startTimer.evn_name, - required: true, - name: 'name', - visible: false, - valueType: 'string' - }, + showEncoderOptions = function () { + cboEncode.setVisible(true); + cboConnectionTypeOracle.setVisible(false); + }; + cboConnectionTypeOracleSetOptions = function (cboConnectionTypeOracle) { + var arrayEnconde = [], + i, + arrayOptions = []; + cboConnectionTypeOracle.clearOptions(); + + arrayEnconde = [ + {"value": "NORMAL", "text": "Normal"}, + {"value": "TNS", "text": "TNS"} + ]; + + for (i = 0; i <= arrayEnconde.length - 1; i += 1) { + arrayOptions.push( { - id: 'performTask', - pmType: 'dropdown', - label: 'Perform this task'.translate(), - name: 'performTask', - required: true, - value: '', - controlsWidth: 300, - options: [ - { - label: '- Select -'.translate(), - value: '', - disabled: true, - selected: true - }, - { - value: 'daily', - label: 'Daily'.translate() - }, - { - value: 'weekly', - label: 'Weekly'.translate() - }, - { - value: 'monthly', - label: 'Monthly'.translate() - }, - { - value: 'oneTime', - label: 'One Time Only'.translate() - }, - { - value: 'every', - label: 'Every'.translate() - } - ], - onChange: function (newValue, prevValue) { - showProperties(newValue); - } + value: arrayEnconde[i].value, + label: arrayEnconde[i].text } - ] - }, - { - id: 'panelSelectDate', - pmType: 'panel', - layout: 'vbox', - fieldset: true, - visible: false, - height: '350px', - legend: 'Select the date and time for case(s) to be initiated.'.translate(), - items: [] + ); } - ] - }); - buttonCancel = new PMUI.ui.Button({ - id: 'cancelSchedulerButton', - text: 'Cancel'.translate(), - buttonType: 'error', - handler: function (event) { - if (formCreateCaseScheduler.isDirty()) { - var message_window = new PMUI.ui.MessageWindow({ - windowMessageType: 'warning', - width: 490, - bodyHeight: 'auto', - id: 'cancelMessageStartTimer', - title: 'Start Timer Event'.translate(), - message: 'Are you sure you want to discard your changes?'.translate(), - footerItems: [ - { - text: 'No'.translate(), - handler: function () { - message_window.close(); - }, - buttonType: "error" - }, - { - text: 'Yes'.translate(), - handler: function () { - message_window.close(); - schedulerListWindow.close(); - }, - buttonType: "success" - } - ] - }); - message_window.open(); - message_window.showFooter(); - } else { - formCreateCaseScheduler.reset(); - schedulerListWindow.close(); - } - } - }); + cboConnectionTypeOracle.setOptions(arrayOptions); + }; + cboEncodeSetOptionsRestProxy = function (selectedCboEngineValue, cboEncode) { + var arrayEnconde = [], + arrayNewEnconde, + i, + portsDefault, + arrayOptions, + encode = selectedCboEngineValue; + cboEncode.clearOptions(); - //Window Buttons - buttonSave = new PMUI.ui.Button({ - id: 'saveSchedulerButton', - text: 'Save'.translate(), - height: 31, - buttonType: 'success', - handler: function (event) { - if (formCreateCaseScheduler.isValid()) { - var dataFormCreate = formCreateCaseScheduler.getData(); - - var dataToSend = { - sch_del_user_name: dataFormCreate.username, - sch_name: startTimer.evn_name, - tas_uid: startTimer.ports.get(0).connection.flo_element_dest, - sch_start_time: '', - sch_start_date: '', - sch_week_days: '', - sch_start_day: '', - sch_start_day_opt_1: '', - sch_start_day_opt_2: '', - sch_months: '', - sch_end_date: '', - sch_repeat_every: '', - sch_state: (dataFormCreate.state !== '') ? dataFormCreate.state : 'ACTIVE', - sch_option: '' - }; + arrayEnconde["mysql"] = [ + {"value": "big5", "text": "big5 - Big5 Traditional Chinese"}, + {"value": "dec8", "text": "dec8 - DEC West European"}, + {"value": "cp850", "text": "cp850 - DOS West European"}, + {"value": "hp8", "text": "hp8 - HP West European"}, + {"value": "koi8r", "text": "koi8r - KOI8-R Relcom Russian"}, + {"value": "latin1", "text": "latin1 - cp1252 West European"}, + {"value": "latin2", "text": "latin2 - ISO 8859-2 Central European"}, + {"value": "swe7", "text": "swe7 - 7bit Swedish"}, + {"value": "ascii", "text": "ascii - US ASCII"}, + {"value": "ujis", "text": "ujis - EUC-JP Japanese"}, + {"value": "sjis", "text": "sjis - Shift-JIS Japanese"}, + {"value": "hebrew", "text": "hebrew - ISO 8859-8 Hebrew"}, + {"value": "tis620", "text": "tis620 - TIS620 Thai"}, + {"value": "euckr", "text": "euckr - EUC-KR Korean"}, + {"value": "koi8u", "text": "koi8u - KOI8-U Ukrainian"}, + {"value": "gb2312", "text": "gb2312 - GB2312 Simplified Chinese"}, + {"value": "greek", "text": "greek - ISO 8859-7 Greek"}, + {"value": "cp1250", "text": "cp1250 - Windows Central European"}, + {"value": "gbk", "text": "gbk - GBK Simplified Chinese"}, + {"value": "latin5", "text": "latin5 - ISO 8859-9 Turkish"}, + {"value": "armscii8", "text": "armscii8 - ARMSCII-8 Armenian"}, + {"value": "utf8", "text": "utf8 - UTF-8 Unicode"}, + {"value": "ucs2", "text": "ucs2 - UCS-2 Unicode"}, + {"value": "cp866", "text": "cp866 - DOS Russian"}, + {"value": "keybcs2", "text": "keybcs2 - DOS Kamenicky Czech-Slovak"}, + {"value": "macce", "text": "macce - Mac Central European"}, + {"value": "macroman", "text": "macroman - Mac West European"}, + {"value": "cp852", "text": "cp852 - DOS Central European"}, + {"value": "latin7", "text": "atin7 - ISO 8859-13 Baltic"}, + {"value": "cp1251", "text": "cp1251 - Windows Cyrillic"}, + {"value": "cp1256", "text": "cp1256 - Windows Arabic"}, + {"value": "cp1257", "text": "cp1257 - Windows Baltic"}, + {"value": "binary", "text": "binary - Binary pseudo charset"}, + {"value": "geostd8", "text": "geostd8 - GEOSTD8 Georgian"}, + {"value": "cp932", "text": "cp932] - SJIS for Windows Japanese"}, + {"value": "eucjpms", "text": "eucjpms - UJIS for Windows Japanese"} + ]; - var perform = dataFormCreate.performTask; - switch (perform) { - case 'daily': - dataToSend.sch_option = '1'; - dataToSend.sch_start_time = dataFormCreate.execttime; - dataToSend.sch_start_date = dataFormCreate.startDate; - dataToSend.sch_end_date = dataFormCreate.endDate; - break; - case 'weekly': - var formdays = eval(dataFormCreate.daysoftheweek); - var days = ''; - for (i = 0; i < formdays.length; i += 1) { - if (i !== (formdays.length - 1)) { - days += formdays[i] + '|'; - } else { - days += formdays[i]; - } - } + arrayEnconde["pgsql"] = [ + {"value": "BIG5", "text": "BIG5"}, + {"value": "EUC_CN", "text": "EUC_CN"}, + {"value": "EUC_JP", "text": "EUC_JP"}, + {"value": "EUC_KR", "text": "EUC_KR"}, + {"value": "EUC_TW", "text": "EUC_TW"}, + {"value": "GB18030", "text": "GB18030"}, + {"value": "GBK", "text": "GBK"}, + {"value": "ISO_8859_5", "text": "ISO_8859_5"}, + {"value": "ISO_8859_6", "text": "ISO_8859_6"}, + {"value": "ISO_8859_7", "text": "ISO_8859_7"}, + {"value": "ISO_8859_8", "text": "ISO_8859_8"}, + {"value": "JOHAB", "text": "JOHAB"}, + {"value": "KOI8", "text": "KOI8"}, + {"value": "selected", "text": "LATIN1"}, + {"value": "LATIN2", "text": "LATIN2"}, + {"value": "LATIN3", "text": "LATIN3"}, + {"value": "LATIN4", "text": "LATIN4"}, + {"value": "LATIN5", "text": "LATIN5"}, + {"value": "LATIN6", "text": "LATIN6"}, + {"value": "LATIN7", "text": "LATIN7"}, + {"value": "LATIN8", "text": "LATIN8"}, + {"value": "LATIN9", "text": "LATIN9"}, + {"value": "LATIN10", "text": "LATIN10"}, + {"value": "SJIS", "text": "SJIS"}, + {"value": "SQL_ASCII", "text": "SQL_ASCII"}, + {"value": "UHC", "text": "UHC"}, + {"value": "UTF8", "text": "UTF8"}, + {"value": "WIN866", "text": "WIN866"}, + {"value": "WIN874", "text": "WIN874"}, + {"value": "WIN1250", "text": "WIN1250"}, + {"value": "WIN1251", "text": "WIN1251"}, + {"value": "WIN1252", "text": "WIN1252"}, + {"value": "WIN1256", "text": "WIN1256"}, + {"value": "WIN1258", "text": "WIN1258"} + ]; - dataToSend.sch_option = '2'; - dataToSend.sch_start_time = dataFormCreate.execttime; - dataToSend.sch_start_date = dataFormCreate.startDate; - dataToSend.sch_end_date = dataFormCreate.endDate; - dataToSend.sch_week_days = days; - break; - case 'monthly': - dataToSend.sch_option = '3'; - dataToSend.sch_start_time = dataFormCreate.execttime; - dataToSend.sch_start_date = dataFormCreate.startDate; - dataToSend.sch_end_date = dataFormCreate.endDate; - if (dataFormCreate.options === 'dayofmonth') { - var formmonths = eval(dataFormCreate.months); - var months = ''; - for (i = 0; i < formmonths.length; i += 1) { - if (i !== (formmonths.length - 1)) { - months += formmonths[i] + '|'; - } else { - months += formmonths[i]; - } - } - dataToSend.sch_start_day = '1'; //Day of month - dataToSend.sch_start_day_opt_1 = dataFormCreate.dayMonth;//1 to 31 - day of the month - } else if (dataFormCreate.options === 'day') { - var opt2 = dataFormCreate.first + '|' + dataFormCreate.day; - var formmonths = eval(dataFormCreate.months); - var months = ''; - for (i = 0; i < formmonths.length; i += 1) { - if (i !== (formmonths.length - 1)) { - months += formmonths[i] + '|'; - } else { - months += formmonths[i]; - } - } - dataToSend.sch_start_day = '2'; //Day of month - dataToSend.sch_start_day_opt_2 = opt2;//1 to 31 - day of the month + arrayEnconde["mssql"] = [ + {"value": "utf8", "text": "utf8 - UTF-8 Unicode"} + ]; - } - dataToSend.sch_months = months; - break; - case 'oneTime': - dataToSend.sch_option = '4'; - dataToSend.sch_start_time = dataFormCreate.execttime; - break; - case 'every': - dataToSend.sch_option = '5'; - dataToSend.sch_repeat_every = timeToDecimal(dataFormCreate.execttime).toFixed(2); - break; - } - updateCaseScheduler(dataToSend); - } - } - }); + arrayEnconde["oracle"] = [ + {"value": "UTF8", "text": "UTF8 - Unicode 3.0 UTF-8 Universal character set, CESU-8 compliant"}, + {"value": "UTFE", "text": "UTFE - EBCDIC form of Unicode 3.0 UTF-8 Universal character set"}, + {"value": "AL16UTF16", "text": "AL16UTF16 - Unicode 3.1 UTF-16 Universal character set"}, + {"value": "AL32UTF8", "text": "AL32UTF8 - Unicode 3.1 UTF-8 Universal character set"} + ]; - //load users - loadUsers = function () { - var field = formCreateCaseScheduler.getField('username'); - field.clearOptions(); - for (var i = 0; i < listUsers.length; i += 1) { - field.addOption({ - value: listUsers[i].aas_username, - label: listUsers[i].aas_name + ' ' + listUsers[i].aas_lastname - }); - } - }; + arrayEnconde["sqlsrv"] = [ + {"value": "utf8", "text": "utf8 - UTF-8 Unicode"} + ]; - loadDataForm = function () { - var loadTime, - option, - daysVal, - monthsVal, - monthsop, - days, - i, - startTime, - finallyST, - dataEdit; - - loadTime = function (dataEdit, dataForm) { - var starDate, - startTime, - finallyST, - endDate; - starDate = dataForm.sch_start_date ? dataForm.sch_start_date.split(' ') : ['']; - endDate = dataForm.sch_end_date ? dataForm.sch_end_date.split(' ') : ['']; - - startTime = dataForm.sch_start_time.split(' '); - startTime = startTime[1].split(':'); - finallyST = startTime[0] + ':' + startTime[1]; - dataEdit[4].setValue(starDate[0]); - dataEdit[5].setValue(endDate[0]); - dataEdit[6].setValue(finallyST); - }; + arrayNewEnconde = (typeof(arrayEnconde[encode]) != "undefined") ? arrayEnconde[encode] : []; + arrayOptions = []; - dataEdit = formCreateCaseScheduler.getFields(); - - dataEdit[0].setValue(dataForm.sch_state); - dataEdit[1].setValue(dataForm.sch_del_user_name); - option = 'daily'; - switch (dataForm.sch_option) { - case '1': - option = 'daily'; - dataEdit[3].setValue(option); - showProperties(option); - dataEdit = formCreateCaseScheduler.getFields(); - loadTime(dataEdit, dataForm); - break; - case '2': - option = 'weekly'; - dataEdit[3].setValue(option); - showProperties(option); - dataEdit = formCreateCaseScheduler.getFields(); - loadTime(dataEdit, dataForm); - - daysVal = "[\""; - days = dataForm.sch_week_days.split('|'); - for (i = 0; i < days.length; i += 1) { - if (i !== (days.length - 1)) { - daysVal += days[i] + "\",\""; - } else { - daysVal += days[i] + "\"]"; + for (i = 0; i <= arrayNewEnconde.length - 1; i += 1) { + arrayOptions.push( + { + value: arrayNewEnconde[i].value, + label: arrayNewEnconde[i].text } - } - dataEdit[7].setValue(daysVal); - break; - case '3': - option = 'monthly'; - dataEdit[3].setValue(option); - showProperties(option); - dataEdit = formCreateCaseScheduler.getFields(); - loadTime(dataEdit, dataForm); - days = []; - if (dataForm.sch_start_day !== '') { - days = dataForm.sch_start_day.split('|'); - } + ); + } - if (days[0] === '1') { - dataEdit[7].setValue('dayofmonth'); - loadOptionsRadio('dayofmonth'); - dataEdit[8].setValue(days[1]); - } else if (days[0] === '2') { - dataEdit[7].setValue('day'); - loadOptionsRadio('day'); - dataEdit[9].setValue(days[1]); - dataEdit[10].setValue(days[2]); - } - monthsVal = "[\""; - monthsop = dataForm.sch_months.split('|'); - for (i = 0; i < monthsop.length; i += 1) { - if (i !== (monthsop.length - 1)) { - monthsVal += monthsop[i] + "\",\""; - } else { - monthsVal += monthsop[i] + "\"]"; - } - } - dataEdit[11].setValue(monthsVal); - break; - case '4': - option = 'oneTime'; - dataEdit[3].setValue(option); - showProperties(option); - dataEdit = formCreateCaseScheduler.getFields(); - startTime = dataForm.sch_start_time.split(' '); - startTime = startTime[1].split(':'); - finallyST = startTime[0] + ':' + startTime[1]; - dataEdit[4].setValue(finallyST); - break; - case '5': - option = 'every'; - dataEdit[3].setValue(option); - showProperties(option); - dataEdit = formCreateCaseScheduler.getFields(); - dataEdit[4].setValue(decimalToTime(parseFloat(dataForm.sch_repeat_every))); - break; - } - }; + cboEncode.setOptions(arrayOptions); + cboEncode.setValue('utf8'); - //Main window Case Scheduler - schedulerListWindow = new PMUI.ui.Window({ - id: 'schedulerListWindow', - title: 'Start Timer Event'.translate(), - height: DEFAULT_WINDOW_HEIGHT, - width: DEFAULT_WINDOW_WIDTH, - buttonPanelPosition: 'top', - buttons: [ - buttonSave, - {pmType: 'label', text: 'or'}, - buttonCancel - ] - }); + portsDefault = ["3306", "5432", "1433", "1521"]; + switch (encode) { + case "mysql": + txtPort.setValue(portsDefault[0]); + showEncoderOptions(); + break; + case "pgsql": + txtPort.setValue(portsDefault[1]); + showEncoderOptions(); + break; + case "mssql": + txtPort.setValue(portsDefault[2]); + showEncoderOptions(); + break; + case "oracle": + txtPort.setValue(portsDefault[3]); + hideEncoderOptions(); + break; + } + }; - openForm = function () { - schedulerListWindow.addItem(formCreateCaseScheduler); - schedulerListWindow.open(); - loadUsers(); - loadDataForm(); - applyStyleWindowForm(schedulerListWindow); - schedulerListWindow.showFooter(); - schedulerListWindow.defineEvents(); - }; - }; + winFrmDataBaseConnectionShow = function (option, data) { + disableAllItems(); + dataBaseConnectionData = data; + frmDataBaseConnection.reset(); + cboEngineSetOptionsRestProxy(cboEngine, cboEncode); + cboConnectionTypeOracleSetOptions(cboConnectionTypeOracle); + winGrdpnlDataBaseConnection.getItems()[1].setVisible(true); + btnTestConnection.setVisible(true); + btnCancel.setVisible(true); + winGrdpnlDataBaseConnection.showFooter(); - PMDesigner.startTimer.openForm = function (element) { - openForm(); - }; + switch (option) { + case "POST": + winGrdpnlDataBaseConnection.setTitle("Create Database Connection".translate()); + frmDataBaseConnection.setTitle(""); + txtTns.setVisible(false); + txtTns.setRequired(false); + txtServer.setVisible(true); + txtServer.setRequired(true); + txtDataBaseName.setVisible(true); + txtDataBaseName.setRequired(true); + txtPort.setVisible(true); + txtPort.setRequired(true); + txtPort.setValue("3306"); + break; + case "PUT": + winGrdpnlDataBaseConnection.setTitle("Edit Database Connection".translate()); + frmDataBaseConnection.setTitle(""); + txtUID.setVisible(true); + txtUID.setValue(dataBaseConnectionData.dbs_uid); + cboEngine.setValue(dataBaseConnectionData.dbs_type); + cboEncodeSetOptionsRestProxy(dataBaseConnectionData.dbs_type, cboEncode); + cboEncode.setValue(dataBaseConnectionData.dbs_encode); + txtServer.setValue(dataBaseConnectionData.dbs_server); + txtDataBaseName.setValue(dataBaseConnectionData.dbs_database_name); + txtUsername.setValue(dataBaseConnectionData.dbs_username); + txtPassword.setValue(dataBaseConnectionData.dbs_password); + txtPort.setValue(dataBaseConnectionData.dbs_port); + txtDescription.setValue(dataBaseConnectionData.dbs_description); - PMDesigner.startTimer.validate = function (element) { - if (element.ports.isEmpty()) { - PMDesigner.msgFlash('Must connect to a Task'.translate(), document.body, 'error', 3000, 5); - return false; - } - PMDesigner.startTimer(element); - if (loadValuesStartTimer(true) === 0) { - PMDesigner.msgFlash('The task doesn\'t have assigned users'.translate(), document.body, 'info', 3000, 5); - return false; - } - return true; - }; + if (dataBaseConnectionData.dbs_type == "oracle") { + cboConnectionTypeOracle.setValue(dataBaseConnectionData.dbs_connection_type); + cboConnectionTypeOracle.setVisible(true); -}()); -( - function () { - var dataBaseConnectionOption, - winFrmDataBaseConnectionShow, - frmDataBaseConnection, - closeClicked = true; + if (dataBaseConnectionData.dbs_connection_type == "TNS" && dataBaseConnectionData.dbs_tns != "") { + txtTns.setValue(dataBaseConnectionData.dbs_tns); + txtTns.setVisible(true); + txtTns.setRequired(true); - PMDesigner.database = function (event) { - var winGrdpnlDataBaseConnection, - panelTest, - grdpnlDataBaseConnection, - flagError, - titleOld, - btnNew, - btnTestConnection, - btnCreate, - btnCancel, - testShow, - isDirtyFrmDataBaseConnection, - showForm, - listDBConnection, - refreshGridPanelInMainWindow, - dataBaseConnectionsGetRestProxy, - dataBaseConnectionPostTestRestProxy, - dataBaseConnectionGetRestProxy, - dataBaseConnectionPutRestProxy, - dataBaseConnectionDeleteRestProxy, - dataBaseConnectionPostRestProxy, - cboEngineSetOptionsRestProxy, - showEncoderOptions, - hideEncoderOptions, - cboConnectionTypeOracleSetOptions, - cboEncodeSetOptionsRestProxy, - winFrmDataBaseConnectionShow, - cboEngine, - txtUID, - cboEncode, - txtTns, - txtServer, - txtDataBaseName, - disableAllItems, - txtUsername, - txtPassword, - txtPort, - btnBack, - txtDescription, - cboConnectionTypeOracle, - dataBaseConnectionData; + txtServer.setValue(""); + txtServer.setVisible(false); + txtServer.setRequired(false); - disableAllItems = function () { - winGrdpnlDataBaseConnection.getItems()[0].setVisible(false); - winGrdpnlDataBaseConnection.getItems()[1].setVisible(false); - winGrdpnlDataBaseConnection.getItems()[2].setVisible(false); + txtDataBaseName.setValue(""); + txtDataBaseName.setVisible(false); + txtDataBaseName.setRequired(false); - txtUID.setVisible(false); - btnTestConnection.setVisible(false); - btnBack.setVisible(false); - btnCreate.setVisible(false); - btnCancel.setVisible(false); - }; + txtPort.setValue(""); + txtPort.setVisible(false); + txtPort.setRequired(false); + } else { + txtTns.setValue(""); + txtTns.setVisible(false); + txtTns.setRequired(false); - testShow = function (testData) { - var msg = "", titleSummary, style, i, flag; - flagError = 0; - disableAllItems(); - titleOld = winGrdpnlDataBaseConnection.getTitle(); - winGrdpnlDataBaseConnection.setTitle("Testing Server Connection".translate()); - winGrdpnlDataBaseConnection.getItems()[2].setVisible(true); + txtServer.setVisible(true); + txtServer.setRequired(true); - for (i = 0; i <= testData.length - 1; i += 1) { - flag = (typeof(testData[i].error) != "undefined") ? 1 : 0; - if (flag != 1) { - msg = msg + "" + testData[i].test + "
"; - } else { - msg = msg + "" + testData[i].error + "
"; - } + txtDataBaseName.setVisible(true); + txtDataBaseName.setRequired(true); - if (typeof(testData[i].error) != "undefined" && flagError == 0) { - flagError = 1; - } - } - if (flag == 0) { - btnCreate.setVisible(true); - btnBack.setVisible(true); - } else { - btnBack.setVisible(true); - } + txtPort.setVisible(true); + txtPort.setRequired(true); + } + } else { + txtTns.setValue(""); + txtTns.setVisible(false); + txtTns.setRequired(false); - titleSummary = "
Testing Database Server configuration
"; + txtServer.setVisible(true); + txtServer.setRequired(true); - style = $('#panelTest').attr("style"); - titleSummary = titleSummary + "
" + msg + "
"; - $('#panelTest').empty(); - style = style + ' background: #FFFFFF; font: normal 0.8em arial;'; - $('#panelTest').attr("style", style); - $('#panelTest').append(titleSummary); - }; + txtDataBaseName.setVisible(true); + txtDataBaseName.setRequired(true); - isDirtyFrmDataBaseConnection = function () { - var message_window; - $("input,select,textarea").blur(); - if (frmDataBaseConnection.isVisible()) { - if (frmDataBaseConnection.isDirty()) { - message_window = new PMUI.ui.MessageWindow({ - id: "cancelMessageTriggers", - windowMessageType: 'warning', - width: 490, - title: "Database Connections".translate(), - message: 'Are you sure you want to discard your changes?'.translate(), - footerItems: [ - { - text: "No".translate(), - handler: function () { - message_window.close(); - }, - buttonType: "error" - }, - { - text: "Yes".translate(), - handler: function () { - message_window.close(); - dataBaseConnectionOption = ""; - if (closeClicked) { - winGrdpnlDataBaseConnection.close(); - } - refreshGridPanelInMainWindow(false); - }, - buttonType: "success" - } - ], - title: 'Confirm'.translate() - }); - message_window.open(); - message_window.showFooter(); - } else { - if (closeClicked) { - winGrdpnlDataBaseConnection.close(); - } else { - dataBaseConnectionOption = ""; - refreshGridPanelInMainWindow(false); + txtPort.setVisible(true); + txtPort.setRequired(true); } - } - } else { - winGrdpnlDataBaseConnection.close(); + break; } + frmDataBaseConnection.setFocus(); }; - showForm = function () { - disableAllItems(); - winGrdpnlDataBaseConnection.setTitle(titleOld); - winGrdpnlDataBaseConnection.getItems()[1].setVisible(true); - btnTestConnection.setVisible(true); - btnCancel.setVisible(true); - } - refreshGridPanelInMainWindow = function (load) { - disableAllItems(); - winGrdpnlDataBaseConnection.hideFooter(); - dataBaseConnectionOption = ""; - winGrdpnlDataBaseConnection.getItems()[0].setVisible(true); - winGrdpnlDataBaseConnection.setTitle("Database Connections".translate()); - load = load != null ? load : true; - if (load) { - dataBaseConnectionsGetRestProxy(grdpnlDataBaseConnection); - } - }; + txtUID = new PMUI.field.TextField({ + id: "txtUID", + name: "txtUID", + valueType: "string", + controlsWidth: 300, + label: "UID".translate(), + maxLength: 200, + readOnly: true, + visible: false + }); - dataBaseConnectionsGetRestProxy = function (grdpnl) { - var restProxy = new PMRestClient({ - endpoint: "database-connections", - typeRequest: "get", - functionSuccess: function (xhr, response) { - listDBConnection = response; - grdpnl.setDataItems(listDBConnection); - grdpnl.sort('dbs_database_name', 'asc'); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } - }); - restProxy.executeRestClient(); - }; + cboEngine = new PMUI.field.DropDownListField({ + id: "cboEngine", + name: "cboEngine", + label: "Engine".translate(), + options: null, + controlsWidth: 150, + onChange: function (newValue, prevValue) { + if (cboEngine.getValue() == "oracle") { + cboConnectionTypeOracleSetOptions(cboConnectionTypeOracle); + } else { + txtTns.setVisible(false); + txtTns.setRequired(false); - dataBaseConnectionPostTestRestProxy = function (data) { - var restProxy = new PMRestClient({ - endpoint: "database-connection/test", - typeRequest: "post", - data: data, - functionSuccess: function (xhr, response) { - testShow(response); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } - }); - restProxy.executeRestClient(); - }; + txtServer.setVisible(true); + txtServer.setRequired(true); - dataBaseConnectionGetRestProxy = function (dataBaseConnectionUid) { - var restProxy = new PMRestClient({ - endpoint: "database-connection/" + dataBaseConnectionUid, - typeRequest: "get", - functionSuccess: function (xhr, response) { - var data = response; - dataBaseConnectionOption = "PUT"; - winFrmDataBaseConnectionShow("PUT", data); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } - }); - restProxy.executeRestClient(); - }; + txtDataBaseName.setVisible(true); + txtDataBaseName.setRequired(true); - dataBaseConnectionPutRestProxy = function (dataBaseConnectionUid, data) { - var restProxy = new PMRestClient({ - endpoint: "database-connection/" + dataBaseConnectionUid, - typeRequest: "update", - data: data, - functionSuccess: function (xhr, response) { - refreshGridPanelInMainWindow(); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageSuccess: 'Database connection edited successfully'.translate(), - flashContainer: grdpnlDataBaseConnection - }); + txtPort.setVisible(true); + txtPort.setRequired(true); + } - restProxy.executeRestClient(); - }; - - dataBaseConnectionDeleteRestProxy = function (dataBaseConnectionUid) { - var restProxy = new PMRestClient({ - endpoint: "database-connection/" + dataBaseConnectionUid, - typeRequest: "remove", - functionSuccess: function (xhr, response) { - refreshGridPanelInMainWindow(); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageSuccess: 'Database connection deleted successfully'.translate(), - flashContainer: grdpnlDataBaseConnection - }); - restProxy.executeRestClient(); - }; + cboEncodeSetOptionsRestProxy(cboEngine.getValue(), cboEncode); + } + }); - dataBaseConnectionPostRestProxy = function (data) { - var restProxy = new PMRestClient({ - endpoint: "database-connection", - typeRequest: "post", - data: data, - functionSuccess: function (xhr, response) { - refreshGridPanelInMainWindow(); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); + cboEncode = new PMUI.field.DropDownListField({ + id: "cboEncode", + name: "cboEncode", + label: "Encode".translate(), + options: null, + controlsWidth: 300 + }); - refreshGridPanelInMainWindow(); - }, - messageError: 'An unexpected error while deleting the DB Connection, please try again later.'.translate(), - messageSuccess: 'Database connection saved successfully'.translate(), - flashContainer: grdpnlDataBaseConnection - }); + cboConnectionTypeOracle = new PMUI.field.DropDownListField({ + id: "cboConnectionTypeOracle", + name: "cboConnectionTypeOracle", + label: "Select Connection Type".translate(), + options: null, + controlsWidth: 300, - restProxy.executeRestClient(); - }; + onChange: function (newValue, prevValue) { + if (cboConnectionTypeOracle.getValue() != "NORMAL") { + txtTns.setVisible(true); + txtTns.setRequired(true); - cboEngineSetOptionsRestProxy = function (cboEngine, cboEncode) { - cboEngine.clearOptions(); - var restProxy = new PMRestClient({ - typeRequest: "get", - functionSuccess: function (xhr, response) { - var data = response, - i, - arrayOptions = []; - for (i = 0; i <= data.length - 1; i += 1) { - arrayOptions.push( - { - value: data[i].id, - label: data[i].name - } - ); - } - cboEngine.setOptions(arrayOptions); - cboEngine.setValue(arrayOptions[0].value); - cboEncodeSetOptionsRestProxy(cboEngine.getValue(), cboEncode); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } - }); + txtServer.setVisible(false); + txtServer.setRequired(false); - restProxy.setBaseEndPoint("system/db-engines"); - restProxy.executeRestClient(); - }; + txtDataBaseName.setVisible(false); + txtDataBaseName.setRequired(false); - hideEncoderOptions = function () { - cboEncode.setVisible(true); - cboConnectionTypeOracle.setVisible(true); - }; + txtPort.setVisible(false); + txtPort.setRequired(false); + } else { + txtTns.setVisible(false); + txtTns.setRequired(false); - showEncoderOptions = function () { - cboEncode.setVisible(true); - cboConnectionTypeOracle.setVisible(false); - }; - cboConnectionTypeOracleSetOptions = function (cboConnectionTypeOracle) { - var arrayEnconde = [], - i, - arrayOptions = []; - cboConnectionTypeOracle.clearOptions(); + txtServer.setVisible(true); + txtServer.setRequired(true); - arrayEnconde = [ - {"value": "NORMAL", "text": "Normal"}, - {"value": "TNS", "text": "TNS"} - ]; + txtDataBaseName.setVisible(true); + txtDataBaseName.setRequired(true); - for (i = 0; i <= arrayEnconde.length - 1; i += 1) { - arrayOptions.push( - { - value: arrayEnconde[i].value, - label: arrayEnconde[i].text - } - ); + txtPort.setValue("1521"); + txtPort.setVisible(true); + txtPort.setRequired(true); + } } + }); - cboConnectionTypeOracle.setOptions(arrayOptions); - }; - cboEncodeSetOptionsRestProxy = function (selectedCboEngineValue, cboEncode) { - var arrayEnconde = [], - arrayNewEnconde, - i, - portsDefault, - arrayOptions, - encode = selectedCboEngineValue; - cboEncode.clearOptions(); - - arrayEnconde["mysql"] = [ - {"value": "big5", "text": "big5 - Big5 Traditional Chinese"}, - {"value": "dec8", "text": "dec8 - DEC West European"}, - {"value": "cp850", "text": "cp850 - DOS West European"}, - {"value": "hp8", "text": "hp8 - HP West European"}, - {"value": "koi8r", "text": "koi8r - KOI8-R Relcom Russian"}, - {"value": "latin1", "text": "latin1 - cp1252 West European"}, - {"value": "latin2", "text": "latin2 - ISO 8859-2 Central European"}, - {"value": "swe7", "text": "swe7 - 7bit Swedish"}, - {"value": "ascii", "text": "ascii - US ASCII"}, - {"value": "ujis", "text": "ujis - EUC-JP Japanese"}, - {"value": "sjis", "text": "sjis - Shift-JIS Japanese"}, - {"value": "hebrew", "text": "hebrew - ISO 8859-8 Hebrew"}, - {"value": "tis620", "text": "tis620 - TIS620 Thai"}, - {"value": "euckr", "text": "euckr - EUC-KR Korean"}, - {"value": "koi8u", "text": "koi8u - KOI8-U Ukrainian"}, - {"value": "gb2312", "text": "gb2312 - GB2312 Simplified Chinese"}, - {"value": "greek", "text": "greek - ISO 8859-7 Greek"}, - {"value": "cp1250", "text": "cp1250 - Windows Central European"}, - {"value": "gbk", "text": "gbk - GBK Simplified Chinese"}, - {"value": "latin5", "text": "latin5 - ISO 8859-9 Turkish"}, - {"value": "armscii8", "text": "armscii8 - ARMSCII-8 Armenian"}, - {"value": "utf8", "text": "utf8 - UTF-8 Unicode"}, - {"value": "ucs2", "text": "ucs2 - UCS-2 Unicode"}, - {"value": "cp866", "text": "cp866 - DOS Russian"}, - {"value": "keybcs2", "text": "keybcs2 - DOS Kamenicky Czech-Slovak"}, - {"value": "macce", "text": "macce - Mac Central European"}, - {"value": "macroman", "text": "macroman - Mac West European"}, - {"value": "cp852", "text": "cp852 - DOS Central European"}, - {"value": "latin7", "text": "atin7 - ISO 8859-13 Baltic"}, - {"value": "cp1251", "text": "cp1251 - Windows Cyrillic"}, - {"value": "cp1256", "text": "cp1256 - Windows Arabic"}, - {"value": "cp1257", "text": "cp1257 - Windows Baltic"}, - {"value": "binary", "text": "binary - Binary pseudo charset"}, - {"value": "geostd8", "text": "geostd8 - GEOSTD8 Georgian"}, - {"value": "cp932", "text": "cp932] - SJIS for Windows Japanese"}, - {"value": "eucjpms", "text": "eucjpms - UJIS for Windows Japanese"} - ]; + txtTns = new PMUI.field.TextField({ + id: "txtTns", + name: "txtTns", + valueType: "txtTns", + controlsWidth: 300, + label: "TNS".translate(), + maxLength: 200, + visible: false, + required: true + }); - arrayEnconde["pgsql"] = [ - {"value": "BIG5", "text": "BIG5"}, - {"value": "EUC_CN", "text": "EUC_CN"}, - {"value": "EUC_JP", "text": "EUC_JP"}, - {"value": "EUC_KR", "text": "EUC_KR"}, - {"value": "EUC_TW", "text": "EUC_TW"}, - {"value": "GB18030", "text": "GB18030"}, - {"value": "GBK", "text": "GBK"}, - {"value": "ISO_8859_5", "text": "ISO_8859_5"}, - {"value": "ISO_8859_6", "text": "ISO_8859_6"}, - {"value": "ISO_8859_7", "text": "ISO_8859_7"}, - {"value": "ISO_8859_8", "text": "ISO_8859_8"}, - {"value": "JOHAB", "text": "JOHAB"}, - {"value": "KOI8", "text": "KOI8"}, - {"value": "selected", "text": "LATIN1"}, - {"value": "LATIN2", "text": "LATIN2"}, - {"value": "LATIN3", "text": "LATIN3"}, - {"value": "LATIN4", "text": "LATIN4"}, - {"value": "LATIN5", "text": "LATIN5"}, - {"value": "LATIN6", "text": "LATIN6"}, - {"value": "LATIN7", "text": "LATIN7"}, - {"value": "LATIN8", "text": "LATIN8"}, - {"value": "LATIN9", "text": "LATIN9"}, - {"value": "LATIN10", "text": "LATIN10"}, - {"value": "SJIS", "text": "SJIS"}, - {"value": "SQL_ASCII", "text": "SQL_ASCII"}, - {"value": "UHC", "text": "UHC"}, - {"value": "UTF8", "text": "UTF8"}, - {"value": "WIN866", "text": "WIN866"}, - {"value": "WIN874", "text": "WIN874"}, - {"value": "WIN1250", "text": "WIN1250"}, - {"value": "WIN1251", "text": "WIN1251"}, - {"value": "WIN1252", "text": "WIN1252"}, - {"value": "WIN1256", "text": "WIN1256"}, - {"value": "WIN1258", "text": "WIN1258"} - ]; + txtServer = new PMUI.field.TextField({ + id: "txtServer", + name: "txtServer", + valueType: "string", + controlsWidth: 300, + label: "Server".translate(), + maxLength: 200, + required: true + }); - arrayEnconde["mssql"] = [ - {"value": "utf8", "text": "utf8 - UTF-8 Unicode"} - ]; + txtDataBaseName = new PMUI.field.TextField({ + id: "txtDataBaseName", + name: "txtDataBaseName", + valueType: "string", + controlsWidth: 300, + label: "Database Name".translate(), + maxLength: 200, + required: true + }); - arrayEnconde["oracle"] = [ - {"value": "UTF8", "text": "UTF8 - Unicode 3.0 UTF-8 Universal character set, CESU-8 compliant"}, - {"value": "UTFE", "text": "UTFE - EBCDIC form of Unicode 3.0 UTF-8 Universal character set"}, - {"value": "AL16UTF16", "text": "AL16UTF16 - Unicode 3.1 UTF-16 Universal character set"}, - {"value": "AL32UTF8", "text": "AL32UTF8 - Unicode 3.1 UTF-8 Universal character set"} - ]; - - arrayEnconde["sqlsrv"] = [ - {"value": "utf8", "text": "utf8 - UTF-8 Unicode"} - ]; - - arrayNewEnconde = (typeof(arrayEnconde[encode]) != "undefined") ? arrayEnconde[encode] : []; - arrayOptions = []; - - for (i = 0; i <= arrayNewEnconde.length - 1; i += 1) { - arrayOptions.push( - { - value: arrayNewEnconde[i].value, - label: arrayNewEnconde[i].text - } - ); - } - - cboEncode.setOptions(arrayOptions); - cboEncode.setValue('utf8'); - - portsDefault = ["3306", "5432", "1433", "1521"]; - switch (encode) { - case "mysql": - txtPort.setValue(portsDefault[0]); - showEncoderOptions(); - break; - case "pgsql": - txtPort.setValue(portsDefault[1]); - showEncoderOptions(); - break; - case "mssql": - txtPort.setValue(portsDefault[2]); - showEncoderOptions(); - break; - case "oracle": - txtPort.setValue(portsDefault[3]); - hideEncoderOptions(); - break; - } - }; - - winFrmDataBaseConnectionShow = function (option, data) { - disableAllItems(); - dataBaseConnectionData = data; - frmDataBaseConnection.reset(); - cboEngineSetOptionsRestProxy(cboEngine, cboEncode); - cboConnectionTypeOracleSetOptions(cboConnectionTypeOracle); - winGrdpnlDataBaseConnection.getItems()[1].setVisible(true); - btnTestConnection.setVisible(true); - btnCancel.setVisible(true); - winGrdpnlDataBaseConnection.showFooter(); - - switch (option) { - case "POST": - winGrdpnlDataBaseConnection.setTitle("Create Database Connection".translate()); - frmDataBaseConnection.setTitle(""); - txtTns.setVisible(false); - txtTns.setRequired(false); - txtServer.setVisible(true); - txtServer.setRequired(true); - txtDataBaseName.setVisible(true); - txtDataBaseName.setRequired(true); - txtPort.setVisible(true); - txtPort.setRequired(true); - txtPort.setValue("3306"); - break; - case "PUT": - winGrdpnlDataBaseConnection.setTitle("Edit Database Connection".translate()); - frmDataBaseConnection.setTitle(""); - txtUID.setVisible(true); - txtUID.setValue(dataBaseConnectionData.dbs_uid); - cboEngine.setValue(dataBaseConnectionData.dbs_type); - cboEncodeSetOptionsRestProxy(dataBaseConnectionData.dbs_type, cboEncode); - cboEncode.setValue(dataBaseConnectionData.dbs_encode); - txtServer.setValue(dataBaseConnectionData.dbs_server); - txtDataBaseName.setValue(dataBaseConnectionData.dbs_database_name); - txtUsername.setValue(dataBaseConnectionData.dbs_username); - txtPassword.setValue(dataBaseConnectionData.dbs_password); - txtPort.setValue(dataBaseConnectionData.dbs_port); - txtDescription.setValue(dataBaseConnectionData.dbs_description); - - if (dataBaseConnectionData.dbs_type == "oracle") { - cboConnectionTypeOracle.setValue(dataBaseConnectionData.dbs_connection_type); - cboConnectionTypeOracle.setVisible(true); - - if (dataBaseConnectionData.dbs_connection_type == "TNS" && dataBaseConnectionData.dbs_tns != "") { - txtTns.setValue(dataBaseConnectionData.dbs_tns); - txtTns.setVisible(true); - txtTns.setRequired(true); - - txtServer.setValue(""); - txtServer.setVisible(false); - txtServer.setRequired(false); - - txtDataBaseName.setValue(""); - txtDataBaseName.setVisible(false); - txtDataBaseName.setRequired(false); - - txtPort.setValue(""); - txtPort.setVisible(false); - txtPort.setRequired(false); - } else { - txtTns.setValue(""); - txtTns.setVisible(false); - txtTns.setRequired(false); - - txtServer.setVisible(true); - txtServer.setRequired(true); - - txtDataBaseName.setVisible(true); - txtDataBaseName.setRequired(true); - - txtPort.setVisible(true); - txtPort.setRequired(true); - } - } else { - txtTns.setValue(""); - txtTns.setVisible(false); - txtTns.setRequired(false); - - txtServer.setVisible(true); - txtServer.setRequired(true); - - txtDataBaseName.setVisible(true); - txtDataBaseName.setRequired(true); - - txtPort.setVisible(true); - txtPort.setRequired(true); - } - break; - } - frmDataBaseConnection.setFocus(); - }; - - txtUID = new PMUI.field.TextField({ - id: "txtUID", - name: "txtUID", - valueType: "string", - controlsWidth: 300, - label: "UID".translate(), - maxLength: 200, - readOnly: true, - visible: false - }); - - cboEngine = new PMUI.field.DropDownListField({ - id: "cboEngine", - name: "cboEngine", - label: "Engine".translate(), - options: null, - controlsWidth: 150, - onChange: function (newValue, prevValue) { - if (cboEngine.getValue() == "oracle") { - cboConnectionTypeOracleSetOptions(cboConnectionTypeOracle); - } else { - txtTns.setVisible(false); - txtTns.setRequired(false); - - txtServer.setVisible(true); - txtServer.setRequired(true); - - txtDataBaseName.setVisible(true); - txtDataBaseName.setRequired(true); - - txtPort.setVisible(true); - txtPort.setRequired(true); - } - - cboEncodeSetOptionsRestProxy(cboEngine.getValue(), cboEncode); - } - }); - - cboEncode = new PMUI.field.DropDownListField({ - id: "cboEncode", - name: "cboEncode", - label: "Encode".translate(), - options: null, - controlsWidth: 300 - }); - - cboConnectionTypeOracle = new PMUI.field.DropDownListField({ - id: "cboConnectionTypeOracle", - name: "cboConnectionTypeOracle", - label: "Select Connection Type".translate(), - options: null, - controlsWidth: 300, - - onChange: function (newValue, prevValue) { - if (cboConnectionTypeOracle.getValue() != "NORMAL") { - txtTns.setVisible(true); - txtTns.setRequired(true); - - txtServer.setVisible(false); - txtServer.setRequired(false); - - txtDataBaseName.setVisible(false); - txtDataBaseName.setRequired(false); - - txtPort.setVisible(false); - txtPort.setRequired(false); - } else { - txtTns.setVisible(false); - txtTns.setRequired(false); - - txtServer.setVisible(true); - txtServer.setRequired(true); - - txtDataBaseName.setVisible(true); - txtDataBaseName.setRequired(true); - - txtPort.setValue("1521"); - txtPort.setVisible(true); - txtPort.setRequired(true); - } - } - }); - - txtTns = new PMUI.field.TextField({ - id: "txtTns", - name: "txtTns", - valueType: "txtTns", - controlsWidth: 300, - label: "TNS".translate(), - maxLength: 200, - visible: false, - required: true - }); - - txtServer = new PMUI.field.TextField({ - id: "txtServer", - name: "txtServer", - valueType: "string", - controlsWidth: 300, - label: "Server".translate(), - maxLength: 200, - required: true - }); - - txtDataBaseName = new PMUI.field.TextField({ - id: "txtDataBaseName", - name: "txtDataBaseName", - valueType: "string", - controlsWidth: 300, - label: "Database Name".translate(), - maxLength: 200, - required: true - }); - - txtUsername = new PMUI.field.TextField({ - id: "txtUsername", - name: "txtUsername", - valueType: "string", - controlsWidth: 300, - label: "Username".translate(), - maxLength: 200, - required: true - }); + txtUsername = new PMUI.field.TextField({ + id: "txtUsername", + name: "txtUsername", + valueType: "string", + controlsWidth: 300, + label: "Username".translate(), + maxLength: 200, + required: true + }); txtPassword = new PMUI.field.PasswordField({ id: "txtPassword", @@ -10627,3928 +10627,3928 @@ InputDocument.prototype.build = function () { }() ); -(function () { - $ctrlSpaceMessage = $("

" + "Press".translate() + " ctrl+space " + "to get the function list".translate() + ".

"); - var btnCopyImport, openFormCustom, formEditTriggerCustom; - var triggerOriginDataForUpdate = {}; - PMDesigner.trigger = function (event) { - var listTriggers, - clickedClose = true, - message_ErrorWindow, - flagChanges, - isDirtyFormTrigger, - gridListTrigger, - getListTrigger, - addNumberTriggerWizard, - newTriggerOptions, - allTreesItems, - buttonNew, - buttonCopy, - buttonWizard, - openListTriggers, - openFormWizard, - openFormWizardEditMode, - openFormCopy, - openFormEditCode, - openNewTriggerOptions, - listProjects, - getListProjects, - triggerSelectedData, - formCopyTrigger, - codMirr, - formEditTriggerWizard, - sepInputs, - labelInputs, - paramPanel, - sepOutputs, - labelOutputs, - returnPanel, - parameterItems, - returnItems, - treeNewTrigger, - accordionNewTrigger, - updateCustom, - checkIfValuesAreEqual, - buttonSave, - copyButton, - applyButton, - btnEditSourceCode, - buttonCancel, - editCode, - formEditCode, - triggerWindow, - formcustom; - - message_ErrorWindow = new PMUI.ui.MessageWindow({ - id: "errorMessage", - width: 490, - windowMessageType: 'error', - title: "Triggers".translate(), - message: "This is an error message.".translate(), - footerItems: [ - { - text: 'OK'.translate(), - handler: function () { - message_ErrorWindow.close(); - }, - buttonType: "success" +(function () { + $ctrlSpaceMessage = $("

" + "Press".translate() + " ctrl+space " + "to get the function list".translate() + ".

"); + var btnCopyImport, openFormCustom, formEditTriggerCustom; + var triggerOriginDataForUpdate = {}; + PMDesigner.trigger = function (event) { + var listTriggers, + clickedClose = true, + message_ErrorWindow, + flagChanges, + isDirtyFormTrigger, + gridListTrigger, + getListTrigger, + addNumberTriggerWizard, + newTriggerOptions, + allTreesItems, + buttonNew, + buttonCopy, + buttonWizard, + openListTriggers, + openFormWizard, + openFormWizardEditMode, + openFormCopy, + openFormEditCode, + openNewTriggerOptions, + listProjects, + getListProjects, + triggerSelectedData, + formCopyTrigger, + codMirr, + formEditTriggerWizard, + sepInputs, + labelInputs, + paramPanel, + sepOutputs, + labelOutputs, + returnPanel, + parameterItems, + returnItems, + treeNewTrigger, + accordionNewTrigger, + updateCustom, + checkIfValuesAreEqual, + buttonSave, + copyButton, + applyButton, + btnEditSourceCode, + buttonCancel, + editCode, + formEditCode, + triggerWindow, + formcustom; + + message_ErrorWindow = new PMUI.ui.MessageWindow({ + id: "errorMessage", + width: 490, + windowMessageType: 'error', + title: "Triggers".translate(), + message: "This is an error message.".translate(), + footerItems: [ + { + text: 'OK'.translate(), + handler: function () { + message_ErrorWindow.close(); + }, + buttonType: "success" + } + ] + }); + + isDirtyFormTrigger = function () { + $("input,select,textarea").blur(); + $("div.pmui-window-body.pmui-background").css('overflow', ''); + var formcustom = triggerWindow.getItems()[1]; + var formwizard = triggerWindow.getItems()[2]; + var formcopy = triggerWindow.getItems()[3]; + var formeditcode = triggerWindow.getItems()[4]; + var accordionnewtrigger = triggerWindow.getItems()[5]; + var flag = false; + + var finalData = { + tri_uid: getData2PMUI(formEditTriggerCustom.html).uid, + tri_title: getData2PMUI(formEditTriggerCustom.html).title, + tri_description: getData2PMUI(formEditTriggerCustom.html).description, + tri_webbot: getData2PMUI(formEditTriggerCustom.html).code + }; + + if (formcustom.isVisible() == true) { + flag = (checkIfValuesAreEqual(triggerOriginDataForUpdate, finalData)) ? false : true; + } else if (formwizard.isVisible() == true) { + flag = formEditTriggerWizard.isDirty(); + } else if (formcopy.isVisible() == true) { + flag = formCopyTrigger.isDirty(); + if (!flag) { + $('.ctrlSpaceMessage').remove(); + } + } else if (formeditcode.isVisible() == true) { + flag = formeditcode.isDirty(); + var flagFormCustom = (checkIfValuesAreEqual(triggerOriginDataForUpdate, finalData)) ? false : true; + if (!flag && formeditcode.getItems()[0].controls[0].value != "" || flagFormCustom) { + flag = true; + } + } + + if (flag == true) { + var message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + title: "Triggers".translate(), + windowMessageType: 'warning', + width: 490, + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, { + text: "Yes".translate(), + handler: function () { + triggerOriginDataForUpdate = {}; + var formcustom = triggerWindow.getItems()[1]; + var formwizard = triggerWindow.getItems()[2]; + var formcopy = triggerWindow.getItems()[3]; + var formeditcode = triggerWindow.getItems()[4]; + + if (formcustom.isVisible() == true) { + var uidInForm = formEditTriggerCustom.getFields()[0].getValue(); + formEditTriggerCustom.reset(); + openListTriggers(); + } else if (formwizard.isVisible() == true) { + var uidInForm = formEditTriggerWizard.getFields()[0].getValue(); + formEditTriggerWizard.reset(); + openListTriggers(); + } else if (formcopy.isVisible() == true) { + $('.ctrlSpaceMessage').remove(); + formCopyTrigger.reset(); + openListTriggers(); + } else if (formeditcode.isVisible() == true) { + formeditcode.reset(); + openFormCustom("Edit".translate()); + } + message_window.close(); + if (clickedClose) { + triggerWindow.close(); + } + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + var formcustom = triggerWindow.getItems()[1]; + var formwizard = triggerWindow.getItems()[2]; + var formcopy = triggerWindow.getItems()[3]; + var formeditcode = triggerWindow.getItems()[4]; + var accordionnewtrigger = triggerWindow.getItems()[5]; + + if (formcustom.isVisible() == true) { + var uidInForm = formEditTriggerCustom.getFields()[0].getValue(); + formEditTriggerCustom.reset(); + openListTriggers(); + } else if (formwizard.isVisible() == true) { + var uidInForm = formEditTriggerWizard.getFields()[0].getValue(); + formEditTriggerWizard.reset(); + openListTriggers(); + } else if (formcopy.isVisible() == true) { + formCopyTrigger.reset(); + openListTriggers(); + } else if (formeditcode.isVisible() == true) { + formeditcode.reset(); + openFormCustom("Edit".translate()); + } else if (accordionnewtrigger.isVisible() == true) { + openListTriggers(); + } + if (clickedClose) { + triggerWindow.close(); + } + } + }; + //GRID List Case Scheduler + gridListTrigger = new PMUI.grid.GridPanel({ + id: "listTriggers", + pageSize: 10, + width: "96%", + style: { + cssClasses: ["mafe-gridPanel"] + }, + filterPlaceholder: 'Search ...'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + tableContainerHeight: 374, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [ + { + id: 'listTriggersButtonShow', + title: '', + dataType: 'button', + searchable: false, + buttonLabel: 'Show ID'.translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-show' + ] + }, + id: 'copyuid', + onButtonClick: function (row, grid) { + var dataRow = row.getData(); + messageWindow = new PMUI.ui.MessageWindow({ + id: 'dynaformMessageWindowUID', + windowMessageType: 'info', + width: 490, + title: "Triggers".translate(), + message: dataRow.tri_uid, + footerItems: [ + { + text: 'OK'.translate(), + handler: function () { + messageWindow.close(); + }, + buttonType: "success" + } + ] + }); + messageWindow.setTitle("ID".translate()); + messageWindow.open(); + messageWindow.showFooter(); + $(messageWindow.dom.icon).removeClass(); + } + }, + { + title: 'Title'.translate(), + id: "title", + dataType: 'string', + width: "407px", + visible: true, + columnData: "tri_title", + searcheable: true, + sortable: true, + alignmentCell: 'left' + }, + { + title: 'Type'.translate(), + id: "type", + dataType: 'string', + width: "225px", + visible: true, + alignmentCell: 'left', + columnData: function (data) { + if (typeof(data.tri_param) == "object" && typeof(data.tri_param.params) == "object") { + var wizardData = data.tri_param.params; + + return wizardData.LIBRARY_NAME; + } else { + return "Custom"; + } + }, + searcheable: true, + sortable: true + }, + { + id: "editButton", + title: '', + dataType: 'button', + messageTooltip: "Edit".translate(), + buttonLabel: "Edit".translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-edit' + ] + }, + onButtonClick: function (row, grid) { + triggerOriginDataForUpdate = {}; + var data = row.getData(); + triggerOriginDataForUpdate = data; + var fields; + if (data.tri_param == "") { + + openFormCustom("Edit".translate()); + formEditTriggerCustom.showFooter(); + + var codeMirrorControl, cmControlCopyTrigger; + codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; + + if (codeMirrorControl != undefined) { + codeMirrorControl.setSize(580, 160); + } + formEditTriggerCustom.getItems()[1].setHeight(170); + fields = formEditTriggerCustom.getItems()[0]; + fields.getItems()[0].setValue(data.tri_uid); + fields.getItems()[1].setValue(data.tri_title); + fields.getItems()[2].setValue(data.tri_description); + formEditTriggerCustom.getItems()[1].setValue(data.tri_webbot); + + codeMirrorControl.setValue(data.tri_webbot); + codeMirrorControl.refresh(); + } else { + openFormWizardEditMode(); + + var wizardData = data.tri_param.params; + + var lib = wizardData.LIBRARY_CLASS; + lib = lib.split('.'); + lib = lib[1]; + fields = formEditTriggerWizard.getFields(); + fields[0].setValue(data.tri_uid); + fields[1].setValue(lib); + fields[2].setValue(wizardData.PMFUNTION_NAME); + fields[3].setValue(wizardData.LIBRARY_NAME + " (" + wizardData.PMFUNTION_LABEL + ")"); + fields[4].setValue(data.tri_title); + fields[5].setValue(data.tri_description); + fields[6].setValue(data.tri_webbot); + + var inputItems = []; + var outputItems = []; + + restClient = new PMRestClient({ + endpoint: "trigger-wizard/" + lib + "/" + wizardData.PMFUNTION_NAME, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + if (response.fn_params.input != undefined) { + for (j = 0; j < response.fn_params.input.length; j++) { + var nameInput = response.fn_params.input[j].name; + + var inp = new CriteriaField({ + id: nameInput, + pmType: "text", + name: nameInput, + label: response.fn_params.input[j].label, + value: wizardData[nameInput].toString(), + controlsWidth: 400, + labelWidth: '27%', + helper: response.fn_params.input[j].description, + required: response.fn_params.input[j].name === "unpauseDate" ? true : response.fn_params.input[j].required + }); + + inputItems.push(inp); + } + } + if (response.fn_params.output != undefined) { + for (k = 0; k < response.fn_params.output.length; k++) { + var nameOutput = response.fn_params.output[k].name; + + var out = new CriteriaField({ + id: nameOutput, + pmType: "text", + name: nameOutput, + label: response.fn_params.output[k].label, + value: wizardData.TRI_ANSWER.toString(), + controlsWidth: 400, + labelWidth: '27%', + helper: response.fn_params.output[k].description, + required: response.fn_params.output[k].required + }); + + outputItems.push(out); + } + } + triggerWindow.setTitle("Edit".translate() + " " + wizardData.LIBRARY_NAME); + if (inputItems.length > 0) { + formEditTriggerWizard.getItems()[1].setVisible(true); + formEditTriggerWizard.getItems()[2].setVisible(true); + formEditTriggerWizard.getItems()[3].setVisible(true); + formEditTriggerWizard.getItems()[3].clearItems(); + formEditTriggerWizard.getItems()[3].setItems(inputItems); + } else { + formEditTriggerWizard.getItems()[1].setVisible(false); + formEditTriggerWizard.getItems()[2].setVisible(false); + formEditTriggerWizard.getItems()[3].setVisible(false); + formEditTriggerWizard.getItems()[3].clearItems(); + } + if (outputItems.length > 0) { + formEditTriggerWizard.getItems()[4].setVisible(true); + formEditTriggerWizard.getItems()[5].setVisible(true); + formEditTriggerWizard.getItems()[6].setVisible(true); + formEditTriggerWizard.getItems()[6].clearItems(); + formEditTriggerWizard.getItems()[6].setItems(outputItems); + } else { + formEditTriggerWizard.getItems()[4].setVisible(false); + formEditTriggerWizard.getItems()[5].setVisible(false); + formEditTriggerWizard.getItems()[6].setVisible(false); + formEditTriggerWizard.getItems()[6].clearItems(); + } + labelInputs.dom.labelTextContainer.style.display = "none"; + labelOutputs.dom.labelTextContainer.style.display = "none"; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the triggers wizard list, please try again.".translate() + }); + restClient.executeRestClient(); + } + } + }, + { + id: "deleteButton", + title: '', + dataType: 'button', + messageTooltip: "Delete".translate(), + buttonLabel: "Delete".translate(), + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + }, + onButtonClick: function (row, grid) { + var questionWindow, dataRow = row.getData(); + + questionWindow = new PMUI.ui.MessageWindow({ + id: "questionDeleteWindow", + title: "Triggers".translate(), + windowMessageType: 'warning', + width: 490, + message: "Do you want to delete this Trigger?".translate(), + footerItems: [ + { + id: 'questionDeleteWindowButtonNo', + text: "No".translate(), + visible: true, + handler: function () { + questionWindow.close(); + }, + buttonType: "error" + }, { + id: 'questionDeleteWindowButtonYes', + text: "Yes".translate(), + visible: true, + handler: function () { + questionWindow.close(); + restClient = new PMRestClient({ + endpoint: "trigger/" + dataRow.tri_uid, + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + grid.removeItem(row); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: "Trigger deleted successfully".translate(), + flashContainer: gridListTrigger + }); + restClient.executeRestClient(); + }, + buttonType: "success" + }, + ] + }); + + questionWindow.open(); + questionWindow.dom.titleContainer.style.height = "17px"; + questionWindow.showFooter(); + } + } + ], + dataItems: listTriggers, + onRowClick: function (row, data) { + + } + }); + + getListTrigger = function () { + var restClient = new PMRestClient({ + endpoint: 'triggers', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + listTriggers = response; + gridListTrigger.setDataItems(listTriggers); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the Triggers list, please try again.".translate() + }); + restClient.executeRestClient(); + }; + + addNumberTriggerWizard = function (value, position) { + coutTriggers = document.createElement("span"); + coutTriggers.textContent = value; + headerAccordion = triggerWindow.getItems()[5].getItems()[position].header.html; + headerAccordion.appendChild(coutTriggers); + coutTriggers.style.float = "right"; + coutTriggers.style.color = "white"; + coutTriggers.style.fontSize = "13px"; + coutTriggers.style.marginRight = "6px"; + coutTriggers.style.marginTop = "3px"; + }; + + newTriggerOptions = function () { + + var acItemCustom = accordionNewTrigger.getItems()[0]; + var acItemCopy = accordionNewTrigger.getItems()[1]; + acItemCustom.setIconClosed('pmcustomtrigger'); + acItemCustom.setIconExpanded('pmcustomtrigger'); + acItemCopy.setIconClosed('pmcopytrigger'); + acItemCopy.setIconExpanded('pmcopytrigger'); + + var itemCustom = jQuery("#custom > .pmui-accordion-item-header > span")[1]; + itemCustom.style.width = "0px"; + var itemCopy = jQuery("#copy > .pmui-accordion-item-header > span")[1]; + itemCopy.style.width = "0px"; + + var numOfItems = accordionNewTrigger.getItems(); + + var lengthLibFunctions = []; + if (numOfItems.length <= 2) { + restClient = new PMRestClient({ + endpoint: "trigger-wizards", + typeRequest: 'get', + functionSuccess: function (xhr, response) { + for (i = 0; i < response.length; i++) { + var functTree = response[i].lib_functions; + lengthLibFunctions[i] = functTree.length; + var newTreeItems = []; + for (h = 0; h < functTree.length; h++) { + newTreeItems.push({ + label: functTree[h].fn_label, + id: functTree[h].fn_name, + onClick: function () { + for (s = 0; s < response.length; s++) { + for (p = 0; p < response[s].lib_functions.length; p++) { + if (response[s].lib_functions[p].fn_name == this.id) { + var fn = response[s].lib_functions[p].fn_params; + var fnLabel = response[s].lib_functions[p].fn_label; + var fnName = response[s].lib_functions[p].fn_name; + var libName = response[s].lib_name; + var libTitle = response[s].lib_title; + p = response[s].lib_functions.length; + s = response.length - 1; + } + } + } + var inputItems = []; + if (fn.input != undefined) { + for (j = 0; j < fn.input.length; j++) { + var val = ""; + if (fn.input[j].type == "array") { + val = "array('')"; + } + var inp = new CriteriaField({ + id: fn.input[j].name, + pmType: "text", + name: fn.input[j].name, + label: fn.input[j].label, + controlsWidth: 400, + labelWidth: '27%', + value: val, + helper: fn.input[j].description, + required: fn.input[j].name === "unpauseDate" ? true : fn.input[j].required + }); + + inputItems.push(inp); + } + } + + var outputItems = []; + if (fn.output != undefined) { + for (k = 0; k < fn.output.length; k++) { + var out = new CriteriaField({ + id: fn.output[k].name, + pmType: "text", + name: fn.output[k].name, + label: fn.output[k].label, + controlsWidth: 400, + labelWidth: '27%', + helper: fn.output[k].description, + required: fn.output[k].required + }); + + outputItems.push(out); + } + } + formEditTriggerWizard.reset(); + formEditTriggerWizard.setTitle(fnLabel + ' (' + fnName + ')'); + formEditTriggerWizard.getItems()[0].getItems()[1].setValue(libName); + formEditTriggerWizard.getItems()[0].getItems()[2].setValue(fnName); + formEditTriggerWizard.getItems()[0].getItems()[3].setValue(libTitle + ' (' + fnLabel + ')'); + + if (inputItems.length > 0) { + formEditTriggerWizard.getItems()[1].setVisible(true); + formEditTriggerWizard.getItems()[2].setVisible(true); + formEditTriggerWizard.getItems()[3].setVisible(true); + formEditTriggerWizard.getItems()[3].clearItems(); + formEditTriggerWizard.getItems()[3].setItems(inputItems); + } else { + formEditTriggerWizard.getItems()[1].setVisible(false); + formEditTriggerWizard.getItems()[2].setVisible(false); + formEditTriggerWizard.getItems()[3].setVisible(false); + formEditTriggerWizard.getItems()[3].clearItems(); + } + if (outputItems.length > 0) { + formEditTriggerWizard.getItems()[4].setVisible(true); + formEditTriggerWizard.getItems()[5].setVisible(true); + formEditTriggerWizard.getItems()[6].setVisible(true); + formEditTriggerWizard.getItems()[6].clearItems(); + formEditTriggerWizard.getItems()[6].setItems(outputItems); + } else { + formEditTriggerWizard.getItems()[4].setVisible(false); + formEditTriggerWizard.getItems()[5].setVisible(false); + formEditTriggerWizard.getItems()[6].setVisible(false); + formEditTriggerWizard.getItems()[6].clearItems(); + } + openFormWizard(); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + triggerWindow.setTitle("Create".translate() + " " + libTitle); + } + }); + } + labelInputs.dom.labelTextContainer.style.display = "none"; + labelOutputs.dom.labelTextContainer.style.display = "none"; + allTreesItems[i] = newTreeItems; + + var arrayTriggerWizards = [ + "pmFunctions", + "pmSugar", + "pmTalend", + "pmTrAlfresco", + "pmTrSharepoint", + "pmZimbra" + ]; + + if (arrayTriggerWizards.indexOf(response[i].lib_name) == -1) { + $("head").append(""); + } + + //Accordion + var newAccordionItem = []; + newAccordionItem = { + iconClass: response[i].lib_name, + id: response[i].lib_name, + title: response[i].lib_title, + height: 'auto' + }; + accordionNewTrigger.addItem(newAccordionItem); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the triggers wizard list, please try again.".translate() + }); + restClient.executeRestClient(); + } + + openNewTriggerOptions(); + var accordion = triggerWindow.getItems()[5].getItems(); + accordion[0].setVisible(false); + accordion[1].setVisible(false); + for (i = 0; i < accordion.length; i++) { + accordion[i].header.html.style.backgroundColor = "#FFFFFF"; + if (i > 1) { + addNumberTriggerWizard(lengthLibFunctions[i - 2], (i)); + } + } + }; + + allTreesItems = []; + getListTrigger(); + + //Button NEW Trigger + buttonNew = new PMUI.ui.Button({ + id: 'newTriggerButton', + text: "Create".translate(), + height: "36px", + width: 100, + handler: function (event) { + openFormCustom("Create".translate()); + formEditTriggerCustom.getField("code").dom.labelTextContainer.style.width = "23.8%"; + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + formEditTriggerCustom.showFooter(); + + var codeMirrorControl, cmControlCopyTrigger; + codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; + formEditTriggerCustom.getItems()[1].html.style.padding = "10px"; + if (codeMirrorControl !== undefined) { + codeMirrorControl.setSize(580, 150); + } + formEditTriggerCustom.getItems()[1].setHeight(170); + + formEditTriggerCustom.reset(); + + fields = formEditTriggerCustom.getItems()[0]; + fields.getItems()[0].setValue(""); + fields.getItems()[1].setValue(""); + fields.getItems()[2].setValue(""); + formEditTriggerCustom.getItems()[1].setValue(""); + formEditTriggerCustom.getItems()[1].controls[0].cm.setValue(""); + codeMirrorControl.refresh(); + }, + style: { + cssClasses: [ + 'mafe-button-create' + ] + } + }); + + //Button COPY Trigger + buttonCopy = new PMUI.ui.Button({ + id: 'copyTriggerButton', + text: "Copy".translate(), + height: "36px", + width: 100, + handler: function (event) { + getListProjects(); + openFormCopy(); + formCopyTrigger.getFields()[1].clearOptions(); + $("#Code .CodeMirror.cm-s-default.CodeMirror-wrap").css({'border': '1px solid #c0c0c0'}); + + var cmControlCopyTrigger = formCopyTrigger.getFields()[4].controls[0].cm; + cmControlCopyTrigger.setValue(""); + if (cmControlCopyTrigger !== undefined) { + cmControlCopyTrigger.setSize(650, 140); + } + cmControlCopyTrigger.refresh(); + }, + style: { + cssClasses: [ + 'mafe-button-create' + ] + } + }); + + //Button WIZARD Trigger + buttonWizard = new PMUI.ui.Button({ + id: 'wizardTriggerButton', + text: "Wizard".translate(), + height: "36px", + width: 100, + handler: function (event) { + newTriggerOptions(); + }, + style: { + cssClasses: [ + 'mafe-button-create' + ] + } + }); + + openListTriggers = function () { + triggerWindow.getItems()[0].setVisible(true); + triggerWindow.getItems()[1].setVisible(false); + triggerWindow.getItems()[2].setVisible(false); + triggerWindow.getItems()[3].setVisible(false); + triggerWindow.getItems()[4].setVisible(false); + triggerWindow.getItems()[5].setVisible(false); + triggerWindow.setTitle("Triggers".translate()); + triggerWindow.hideFooter(); + $(triggerWindow.body).removeClass("pmui-background"); + }; + + openFormCustom = function (typeTitle) { + triggerWindow.getItems()[0].setVisible(false); + triggerWindow.getItems()[1].setVisible(true); + triggerWindow.getItems()[2].setVisible(false); + triggerWindow.getItems()[3].setVisible(false); + triggerWindow.getItems()[4].setVisible(false); + triggerWindow.getItems()[5].setVisible(false); + triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel + triggerWindow.footer.getItems()[1].setVisible(true); //button Save + triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code + triggerWindow.footer.getItems()[3].setVisible(false); //button Aply + triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import + + triggerWindow.setTitle(typeTitle + " Custom Trigger".translate()); + triggerWindow.showFooter(); + $(triggerWindow.body).addClass("pmui-background"); + formEditTriggerCustom.setFocus(); + + $('.CodeMirror.cm-s-default')[0].style.border = "1px solid #c0c0c0"; + if (formEditTriggerCustom.getItems()[0].getItems()[1].visible == false) { + var fields = formEditTriggerCustom.getItems()[0]; + fields.getItems()[1].setVisible(true); + fields.getItems()[2].setVisible(true); + formEditTriggerCustom.footer.getItems()[1].setVisible(true); + } + formEditTriggerCustom.getFields()[4].dom.labelTextContainer.style.marginLeft = "10px"; + formEditTriggerCustom.setAlignmentButtons('left'); + + $("#code").after($ctrlSpaceMessage.css({ + "margin": "5px 0 0 0", + "text-align": "center", + "width": "655px", + "padding": "" + })); + }; + + openFormWizard = function () { + triggerWindow.getItems()[0].setVisible(false); + triggerWindow.getItems()[1].setVisible(false); + triggerWindow.getItems()[2].setVisible(true); + triggerWindow.getItems()[3].setVisible(false); + triggerWindow.getItems()[4].setVisible(false); + triggerWindow.getItems()[5].setVisible(false); + triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel + triggerWindow.footer.getItems()[1].setVisible(true); //button Save + triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code + triggerWindow.footer.getItems()[3].setVisible(false); //button Aply + triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import + triggerWindow.showFooter(); + $(triggerWindow.body).addClass("pmui-background"); + formEditTriggerWizard.setFocus(); + }; + + openFormWizardEditMode = function () { + triggerWindow.getItems()[0].setVisible(false); + triggerWindow.getItems()[1].setVisible(false); + triggerWindow.getItems()[2].setVisible(true); + triggerWindow.getItems()[3].setVisible(false); + triggerWindow.getItems()[4].setVisible(false); + triggerWindow.getItems()[5].setVisible(false); + triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel + triggerWindow.footer.getItems()[1].setVisible(true); //button Save + triggerWindow.footer.getItems()[2].setVisible(true); //Edit Source Code + triggerWindow.footer.getItems()[3].setVisible(false); //button Aply + triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import + triggerWindow.showFooter(); + $(triggerWindow.body).addClass("pmui-background"); + formEditTriggerWizard.setFocus(); + }; + + + openFormCopy = function () { + triggerWindow.getItems()[0].setVisible(false); + triggerWindow.getItems()[1].setVisible(false); + triggerWindow.getItems()[2].setVisible(false); + triggerWindow.getItems()[3].setVisible(true); + triggerWindow.getItems()[4].setVisible(false); + triggerWindow.getItems()[5].setVisible(false); + triggerWindow.setTitle("Copy Trigger".translate()); + triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel + triggerWindow.footer.getItems()[1].setVisible(false); //button Save + triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code + triggerWindow.footer.getItems()[3].setVisible(false); //button Aply + triggerWindow.footer.getItems()[4].setVisible(true); //button Copy/import + triggerWindow.showFooter(); + $(triggerWindow.body).addClass("pmui-background"); + formCopyTrigger.setFocus(); + + $(".pmui-field").css("float", "left"); + $('#Code .pmui.pmui-pmcodemirrorcontrol').append($ctrlSpaceMessage.css({ + "margin-top": "10px", + "text-align": "", + "width": "655px", + "padding": "" + })); + }; + + openFormEditCode = function () { + triggerWindow.getItems()[0].setVisible(false); + triggerWindow.getItems()[1].setVisible(false); + triggerWindow.getItems()[2].setVisible(false); + triggerWindow.getItems()[3].setVisible(false); + triggerWindow.getItems()[4].setVisible(true); + triggerWindow.getItems()[5].setVisible(false); + triggerWindow.setTitle("Editor".translate()); + triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel + triggerWindow.footer.getItems()[1].setVisible(false); //button Save + triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code + triggerWindow.footer.getItems()[3].setVisible(true); //button Aply + triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import + triggerWindow.showFooter(); + $(triggerWindow.body).addClass("pmui-background"); + + $($('#codeEditor .CodeMirror.cm-s-default.CodeMirror-wrap')[0]).after($ctrlSpaceMessage.css({ + "padding": "5px 0 0 10px", + "text-align": "" + })); + + }; + + openNewTriggerOptions = function () { + triggerWindow.getItems()[0].setVisible(false); + triggerWindow.getItems()[1].setVisible(false); + triggerWindow.getItems()[2].setVisible(false); + triggerWindow.getItems()[3].setVisible(false); + triggerWindow.getItems()[4].setVisible(false); + triggerWindow.getItems()[5].setVisible(true); + triggerWindow.setTitle("Create Predefined Trigger".translate()); + triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel + triggerWindow.footer.getItems()[1].setVisible(false); //button Save + triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code + triggerWindow.footer.getItems()[3].setVisible(false); //button Aply + triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import + triggerWindow.showFooter(); + $(triggerWindow.body).removeClass("pmui-background"); + }; + + //obtaning the list of process to show it on the copy/import of a trigger dropdown + listProjects = []; + getListProjects = function () { + restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + listProjects = []; + formCopyTrigger.getFields()[0].clearOptions(); + listProjects[0] = { + label: "- Select a process -".translate(), + value: "", + disabled: true, + selected: true + }; + for (i = 0; i < response.length; i++) { + listProjects.push({ + label: response[i].prj_name, + value: response[i].prj_uid + }); + } + formCopyTrigger.getFields()[0].setOptions(listProjects); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the list of projects.".translate() + }); + restClient.setBaseEndPoint('projects'); + restClient.executeRestClient(); + }; + + //form Copy/Import Trigger + triggerSelectedData; + formCopyTrigger = new PMUI.form.Form({ + id: "formCopyTriggers", + border: true, + width: '890px', + height: 'auto', + title: "", + visibleHeader: false, + items: [ + { + pmType: 'dropdown', + id: "processField", + label: 'Process'.translate(), + name: 'prj_uid', + required: true, + controlsWidth: 300, + value: "", + options: listProjects, + onChange: function (newValue, prevValue) { + var formFields = formCopyTrigger.getFields(); + formFields[2].setValue(""); + formFields[3].setValue(""); + formFields[4].controls[0].cm.setValue(""); + + var uidProj = newValue, myForm = this.form; + + //obtaning the Trigger list of the process SELECTED + restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + triggerSelectedData = response; + var listTriggersCopy = []; + listTriggersCopy[0] = { + label: "- Select a trigger -".translate(), + value: "", + disabled: true, + selected: true + }; + + for (i = 0; i < response.length; i++) { + listTriggersCopy.push({ + label: response[i].tri_title, + value: response[i].tri_uid + }); + } + formFields[1].setOptions(listTriggersCopy); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the list of triggers.".translate() + }); + restClient.setBaseEndPoint("project/" + uidProj + "/triggers"); + restClient.executeRestClient(); + } + }, + { + pmType: 'dropdown', + id: "triggerField", + label: 'Trigger'.translate(), + name: 'tri_uid', + required: true, + controlsWidth: 300, + value: "", + options: [], + onChange: function (newValue, prevValue) { + var formFields = formCopyTrigger.getFields(); + formFields[2].setValue(""); + formFields[3].setValue(""); + formFields[4].controls[0].cm.setValue(""); + + var uidTri = newValue; + + for (i = 0; i < triggerSelectedData.length; i++) { + if (triggerSelectedData[i].tri_uid == uidTri) { + formFields[2].setValue(triggerSelectedData[i].tri_title); + formFields[3].setValue(triggerSelectedData[i].tri_description); + formFields[4].controls[0].cm.setValue(triggerSelectedData[i].tri_webbot); + } + } + } + }, + { + pmType: "text", + id: "triTitle", + label: "Title of the new trigger".translate(), + placeholder: "Insert the title of the new trigger".translate(), + name: "tri_title", + required: true, + valueType: 'string', + controlsWidth: 300, + style: { + cssProperties: { + 'float': 'left' + } + } + }, + { + pmType: "textarea", + id: "triDescription", + rows: 80, + name: 'tri_description', + label: "Description of the new trigger".translate(), + valueType: 'string', + controlsWidth: 652, + style: { + cssClasses: ['mafe-textarea-resize'], + cssProperties: {'float': 'left'} + } + } + ] + }); + codMirr = new PMCodeMirrorField(); + codMirr.setLabel("Code".translate()); + codMirr.setID("Code"); + codMirr.setName('tri_webbot'); + CodeMirror.commands.autocomplete = function (cm) { + CodeMirror.showHint(cm, CodeMirror.phpHint); + }; + formCopyTrigger.addItem(codMirr); + + //Form to Edit the trigger with the WIZARD (we used a Form because we need buttons to save the changes) + formEditTriggerWizard = new PMUI.form.Form({ + id: "formEditTriggerWizard", + border: true, + visibleHeader: false, + name: "formwizard", + width: 926, + title: "New Trigger".translate(), + items: [ + { + id: "panelDetailsWizard", + pmType: "panel", + layout: 'vbox', + fieldset: false, + height: 'auto', + legend: "DETAILS".translate(), + items: [ + { + id: "uid", + pmType: "text", + label: "ID".translate(), + value: "", + name: "uid", + visible: false, + valueType: 'string' + }, + { + id: "libName", + pmType: "text", + label: "", + value: "", + name: "libName", + visible: false, + valueType: 'string' + }, + { + id: "fnName", + pmType: "text", + label: "", + value: "", + name: "fnName", + visible: false, + valueType: 'string' + }, + { + id: "type", + pmType: "text", + label: "Type".translate(), + value: "WIZARD", + controlsWidth: 450, + labelWidth: '27%', + readOnly: true, + name: "type", + valueType: 'string' + }, + { + id: "titleDetailsWiz", + pmType: "text", + label: "Title".translate(), + value: "", + controlsWidth: 450, + labelWidth: '27%', + name: "titleDetails", + valueType: 'string', + required: true + }, + { + id: "descriptionDetailsWiz", + pmType: "textarea", + label: "Description".translate(), + value: "", + rows: 90, + width: '300px', + controlsWidth: 450, + labelWidth: '27%', + name: "descriptionDetails", + valueType: 'string', + style: {cssClasses: ['mafe-textarea-resize']} + }, + { + id: "webbot", + pmType: "text", + label: "Webbot".translate(), + value: "", + name: "webbot", + controlsWidth: 300, + labelWidth: '27%', + visible: false, + valueType: 'string' + } + ] + } + ] + }); + + //adding a separator Inputs line + sepInputs = new PMSeparatorLineField({ + controlHeight: '1px', + controlColor: "#CDCDCD", + controlsWidth: "890px", + marginLeft: '0%' + }); + formEditTriggerWizard.addItem(sepInputs); + + //adding a label Inputs + labelInputs = new PMLabelField({ + text: "PARAMETERS".translate(), + textMode: "plain", + style: { + cssProperties: { + color: "#AEAEAE", + 'font-weight': 'bold' + } + }, + controlsWidth: 885 + }); + formEditTriggerWizard.addItem(labelInputs); + + //adding the Inputs Items (PARAMETERS) Panel + paramPanel = new PMUI.form.FormPanel({ + id: "panelParametersWizard", + layout: 'vbox', + fieldset: false, + height: 'auto', + visible: false, + legend: "__PARAMETERS__".translate(), + items: [] + }); + formEditTriggerWizard.addItem(paramPanel); + + //adding a separator Outputs line + sepOutputs = new PMSeparatorLineField({ + controlHeight: 1, + controlColor: "#CDCDCD", + controlsWidth: "890px", + marginLeft: '0%' + }); + formEditTriggerWizard.addItem(sepOutputs); + + //adding a label Outputs + labelOutputs = new PMLabelField({ + text: "RETURN VALUE".translate(), + textMode: "plain", + style: { + cssProperties: { + color: "#AEAEAE", + 'font-weight': 'bold' + } + }, + controlsWidth: 885 + }); + + formEditTriggerWizard.addItem(labelOutputs); + + //adding the Output Items (Returns) Panel + returnPanel = new PMUI.form.FormPanel({ + id: "panelReturnValWizard", + layout: 'vbox', + fieldset: false, + height: 'auto', + visible: false, + legend: "RETURN VALUE".translate(), + items: [] + }); + formEditTriggerWizard.addItem(returnPanel); + + + //treePanel New Trigger PMF + treeNewTrigger = new PMUI.panel.TreePanel({ + id: "treeNewTrigger", + width: 'auto', + height: 'auto', + style: { + cssClasses: ['pmtrigger'], + cssProperties: { + 'margin-top': '5px', + 'margin-bottom': '4px' + } + }, + items: [] + }); + + //Acordion Panel New Triggers Options + accordionNewTrigger = new PMUI.panel.AccordionPanel({ + id: "accordionNewTrigger", + width: 885, + height: 'auto', + borderWidth: "0px", + hiddenTitle: true, + style: { + cssProperties: { + 'margin-left': '30px' + } + }, + items: [ + { + iconClass: "", + id: 'custom', + title: "Custom Trigger".translate(), + height: '26px', + body: "", + style: { + cssProperties: { + "background-color": "#FDFDFD" + } + } + }, + { + iconClass: "", + id: 'copy', + title: "Copy Trigger".translate(), + height: '26px', + body: "", + style: { + cssProperties: { + "background-color": "#FDFDFD" + } + } + } + ], + listeners: { + select: function (obj, event) { + + if (obj.id == "custom") { + openFormCustom("Create".translate()); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + formEditTriggerCustom.showFooter(); + + var codeMirrorControl, cmControlCopyTrigger; + codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; + + if (codeMirrorControl != undefined) { + codeMirrorControl.setSize(580, 150); //CodeMirror Size + } + formEditTriggerCustom.getItems()[1].setHeight(170); + + formEditTriggerCustom.reset(); + + fields = formEditTriggerCustom.getItems()[0]; + fields.getItems()[0].setValue(""); + fields.getItems()[1].setValue(""); + fields.getItems()[2].setValue(""); + formEditTriggerCustom.getItems()[1].setValue(""); + formEditTriggerCustom.getItems()[1].controls[0].cm.setValue(""); + + } else if (obj.id == "copy") { + + getListProjects(); + openFormCopy(); + $($('#Code .CodeMirror.cm-s-default.CodeMirror-wrap')[1]).css({'border': '1px solid #c0c0c0'}); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + + var cmControlCopyTrigger = formCopyTrigger.getFields()[4].controls[0].cm; + if (cmControlCopyTrigger != undefined) { + cmControlCopyTrigger.setSize(650, 140); //CodeMirror in formCopyTrigger Size + } + } else { + if (treeNewTrigger.getItems() == "" || treeNewTrigger.id != obj.id) { + var acItems = accordionNewTrigger.getItems(); + var accordionActualItem = accordionNewTrigger.getItem(obj.id); + + for (i = 0; i < acItems.length; i++) { + if (acItems[i].id == accordionActualItem.id) { + var positionActualAcItem = i - 2; + } + } + + treeNewTrigger.setItems(allTreesItems[positionActualAcItem]); + treeNewTrigger.setID(obj.id); + + accordionActualItem.setBody(treeNewTrigger); + treeNewTrigger.defineEvents(); + applyStyleTreePanel(treeNewTrigger, false); + } + } + } + } + }); + + updateCustom = function (dataToSend, triggerUid) { + var restClient = new PMRestClient({ + endpoint: "trigger/" + triggerUid, + typeRequest: 'update', + data: dataToSend, + functionSuccess: function (xhr, response) { + formEditTriggerCustom.setDirty(false); + getListTrigger(); + openListTriggers(); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + }, + functionFailure: function (xhr, response) { + var msg = response.error.message; + var arrayMatch = []; + + if ((arrayMatch = /^[\w\s]+\:\s*(.*)$/i.exec(msg))) { + msg = arrayMatch[1]; + } + + PMDesigner.msgWinError(msg); + }, + messageSuccess: "Trigger updated successfully".translate(), + flashContainer: gridListTrigger + }); + restClient.executeRestClient(); + }; + + checkIfValuesAreEqual = function (initialData, finalData) { + if (typeof(initialData['tri_uid']) == "undefined" && finalData['tri_uid'] == '') { + if (finalData['tri_description'] != '' || finalData['tri_title'] != '' || finalData['tri_webbot'] != '') { + return false; + } + } + for (var key1 in initialData) { + for (var key2 in finalData) { + if (typeof(initialData[key1]) != "undefined" && + typeof(finalData[key2]) != "undefined" && + key1 == key2 && + initialData[key1] != finalData[key2] + ) { + return false; + } + } + } + return true; + } + + //Buttons Save and Cancel for the 'formEditTriggerCustom' and 'formEditTriggerWizard' + buttonSave = new PMUI.ui.Button({ + id: 'saveTriggerButton', + text: "Save".translate(), + handler: function (event) { + triggerOriginDataForUpdate = {}; + var formcustom = triggerWindow.getItems()[1], + formwizard = triggerWindow.getItems()[2], + formTriggerData, + restClient, + dataToSend, + formTriggerData, + inputFields, + message_window, + outputV, + outputFields, + inputV, + dataToSend, + flagEdit; + if (formcustom.isVisible() == true) { + valuesCustom=formcustom.getItems()[0]; + if (!formEditTriggerCustom.isValid( )) { + flagEdit = formEditTriggerCustom.visible; + } else { + flagEdit = formEditTriggerCustom.isValid(); + } + if (flagEdit) { + if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { + formTriggerData = getData2PMUI(formEditTriggerCustom.html); + } else { + formTriggerData = formEditTriggerCustom.getData(); + } + if (formTriggerData.title.trim() === "") { + return false; + } + dataToSend = { + tri_title: formTriggerData.title, + tri_description: formTriggerData.description, + tri_webbot: formTriggerData.code, + tri_param: "" + }; + + if (formTriggerData.uid === "") { + restClient = new PMRestClient({ + endpoint: 'trigger', + typeRequest: 'post', + data: dataToSend, + functionSuccess: function (xhr, response) { + formEditTriggerCustom.setDirty(false); + getListTrigger(); + formEditTriggerCustom.getItems()[0].getItems()[0].setValue(response.tri_uid); + openListTriggers(); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + }, + functionFailure: function (xhr, response) { + var msg = response.error.message, + arrayMatch = []; + + if ((arrayMatch = /^[\w\s]+\:\s*(.*)$/i.exec(msg))) { + msg = arrayMatch[1]; + } + + PMDesigner.msgWinError(msg); + }, + messageSuccess: "New Trigger saved successfully".translate(), + flashContainer: gridListTrigger + }); + restClient.executeRestClient(); + } else { + if (formTriggerData.wizzard != "") { + if (formEditTriggerCustom.isDirty()) { + message_window = new PMUI.ui.MessageWindow({ + id: "wizzardToCustomTriggerWin", + windowMessageType: 'warning', + title: 'Triggers'.translate(), + width: 490, + message: 'Do you want to save the changes? This Trigger will be saved like a custom Trigger.'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + openFormWizardEditMode(); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + formEditTriggerCustom.reset(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + updateCustom(dataToSend, formTriggerData.uid); + }, + buttonType: "success" + } + ] + + }); + message_window.open(); + message_window.showFooter(); + } else { + openListTriggers(); + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + } + } else { + updateCustom(dataToSend, formTriggerData.uid); + } + } + } + } else if (formwizard.isVisible() == true) { + if (formEditTriggerWizard.isValid() || ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1))) { + if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { + formTriggerData = getData2PMUI(formEditTriggerWizard.html); + } else { + formTriggerData = formEditTriggerWizard.getData(); + } + + inputV = {}; + inputFields = formEditTriggerWizard.getItems()[3]; + for (i = 0; i < inputFields.getItems().length; i++) { + inputV[inputFields.getItems()[i].name] = formTriggerData[inputFields.getItems()[i].name]; + } + + outputV = {}; + outputFields = formEditTriggerWizard.getItems()[6]; + for (j = 0; j < outputFields.getItems().length; j++) { + outputV[outputFields.getItems()[j].name] = formTriggerData[outputFields.getItems()[j].name]; + } + + dataToSend = { + tri_title: formTriggerData.titleDetails, + tri_description: formTriggerData.descriptionDetails, + tri_type: "SCRIPT", + tri_params: { + input: inputV, + output: outputV + } + }; + + if (formTriggerData.uid === "") { + restClient = new PMRestClient({ + endpoint: 'trigger-wizard/' + formTriggerData.libName + '/' + formTriggerData.fnName, + typeRequest: 'post', + data: dataToSend, + functionSuccess: function (xhr, response) { + formEditTriggerWizard.setDirty(false); + getListTrigger(); + formEditTriggerWizard.getFields()[0].setValue(response.tri_uid); + openListTriggers(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: "New Trigger saved successfully".translate(), + flashContainer: gridListTrigger + }); + restClient.executeRestClient(); + } else { + restClient = new PMRestClient({ + endpoint: 'trigger-wizard/' + formTriggerData.libName + '/' + formTriggerData.fnName + '/' + formTriggerData.uid, + typeRequest: 'update', + data: dataToSend, + functionSuccess: function (xhr, response) { + formEditTriggerWizard.setDirty(false); + getListTrigger(); + openListTriggers(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: "Trigger updated successfully".translate(), + flashContainer: gridListTrigger + }); + restClient.executeRestClient(); + } + } + } + }, + buttonType: 'success' + }); + + //Buttons Save and Cancel for the 'formEditTriggerCustom' and 'formEditTriggerWizard' + copyButton = new PMUI.ui.Button({ + id: 'copyAndSaveButton', + text: "Copy Trigger".translate(), + buttonType: 'success', + handler: function (event) { + var data, + dataToSend, + restClient; + if (formCopyTrigger.isValid()) { + formCopyTrigger.setDirty(false); + + data = formCopyTrigger.getData(); + dataToSend = { + tri_title: getData2PMUI(formCopyTrigger.html).tri_title.trim(), + tri_description: data.tri_description, + tri_webbot: data.tri_webbot, + tri_param: "" + }; + restClient = new PMRestClient({ + endpoint: 'trigger', + typeRequest: 'post', + data: dataToSend, + functionSuccess: function (xhr, response) { + getListTrigger(); + formCopyTrigger.reset(); + openListTriggers(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageSuccess: "New Trigger saved successfully".translate(), + flashContainer: gridListTrigger + }); + restClient.executeRestClient(); + } + } + }); + + //Buttons Apply for the Code Editor + applyButton = new PMUI.ui.Button({ + id: 'applyButton', + text: "Apply".translate(), + buttonType: 'success', + handler: function (event) { + + $("div.pmui-window-body.pmui-background").css('overflow', ''); + if (formEditCode.isValid()) { + var typeTitle = "Edit".translate(); + if (triggerWindow.getItems()[1].getData().uid == "") { + typeTitle = "Create".translate(); + } + openFormCustom(typeTitle); + formEditCode.setDirty(false); + + var editCode = formEditCode.getItems()[0].controls[0].cm; + editCodeValue = editCode.getValue(); + + var codeMirrorCustom = formEditTriggerCustom.getItems()[1].controls[0].cm; + + if (codeMirrorCustom != undefined) { + codeMirrorCustom.setSize(580, 150); //CodeMirror Size + } + codeMirrorCustom.setValue(editCodeValue); + formEditTriggerCustom.getItems()[1].setValue(editCodeValue); + + editCode.setValue(""); + editCodeValue = ""; + + formEditCode.getItems()[0].setValue(""); + } + } + }); + + //Button Edit Source Code (this is showed just when the Trigger Wizzard is opened in edition mode) + btnEditSourceCode = new PMUI.ui.Button({ + id: 'btnEditSourceCode', + text: "Edit Source Code".translate(), + buttonType: 'success', + handler: function (event) { + + var data = formEditTriggerWizard.getData(); + var fields; + openFormCustom("Edit".translate()); + formEditTriggerCustom.showFooter(); + + var codeMirrorControl; + codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; + + if (codeMirrorControl !== undefined) { + codeMirrorControl.setSize(650, 280); + } + formEditTriggerCustom.getItems()[1].setHeight(170); + + fields = formEditTriggerCustom.getItems()[0]; + fields.getItems()[0].setValue(data.uid); + fields.getItems()[1].setValue(data.titleDetails); + fields.getItems()[2].setValue(data.descriptionDetails); + fields.getItems()[3].setValue(data.webbot); + fields.getItems()[3].setVisible(false); + formEditTriggerCustom.getItems()[1].setValue(data.webbot); + + codeMirrorControl.setValue(data.webbot); + + formEditTriggerCustom.getItems()[1].setHeight(300); + fields.getItems()[1].setVisible(false); + fields.getItems()[2].setVisible(false); + formEditTriggerCustom.footer.getItems()[1].setVisible(false); + formEditTriggerCustom.footer.getItems()[0].style.addProperties({'margin-right': "10px"}); + formEditTriggerCustom.footer.style.addProperties({width: '880px'}); + codeMirrorControl.refresh(); + } + }); + + buttonCancel = new PMUI.ui.Button({ + id: 'cancelTriggerButton', + text: "Cancel".translate(), + buttonType: 'error', + handler: function (event) { + clickedClose = false; + isDirtyFormTrigger(); + } + }); + + //Form to Edit the Custom trigger (we used a Form because we need buttons to save the changes) + formEditTriggerCustom = new PMUI.form.Form({ + id: "formEditTriggerCustom", + border: true, + visibleHeader: false, + width: '900px', + height: "365px", + name: "formcustom", + title: "Custom Trigger".translate(), + items: [ + { + id: "panelDetailsCustom", + pmType: "panel", + layout: 'vbox', + fieldset: false, + height: '380px', + legend: "DETAILS".translate(), + items: [ + { + id: "uid", + pmType: "text", + label: "ID".translate(), + value: "", + name: "uid", + readOnly: true, + visible: false, + valueType: 'string' + }, + { + id: "title", + pmType: "text", + label: "Title".translate(), + value: "", + required: true, + name: "title", + valueType: 'string' + }, + { + id: "description", + pmType: "textarea", + rows: 70, + name: 'description', + label: "Description".translate(), + valueType: 'string', + style: {cssClasses: ['mafe-textarea-resize']} + }, + { + id: "wizzard", + pmType: "text", + label: "Wizzard".translate(), + value: "", + name: "wizzard", + readOnly: true, + visible: false, + valueType: 'string' + } + ] + } + ], + buttons: [ + { + text: "@@", + id: "selectPickerButton", + handler: function () { + var picker = new VariablePicker(); + picker.open({ + success: function (variable) { + var codeMirror = formEditTriggerCustom.getItems()[1].controls[0].cm; + var cursorPos = codeMirror.getCursor(); + codeMirror.replaceSelection(variable); + codeMirror.setCursor(cursorPos.line, cursorPos.ch); + } + }); + }, + style: { + cssProperties: { + "margin-left": '208px', + "background": "rgb(30, 145, 209)", + "border": "0px solid rgb(30, 145, 209)" + } + } + }, { + text: "Open Editor".translate(), + id: "openEditorButton", + handler: function () { + openFormEditCode(); + formEditCode.showFooter(); + + var codeMirrorCustom = formEditTriggerCustom.getItems()[1].controls[0].cm; + var value = codeMirrorCustom.getValue(); + + var codeMirrorCopy = formEditCode.getItems()[0].controls[0].cm; + + if (codeMirrorCopy != undefined) { + codeMirrorCopy.setSize(810, 315); //CodeMirror Size + $($('#codeEditor .CodeMirror.cm-s-default.CodeMirror-wrap')[0]).css({'border': '1px solid #c0c0c0'}); + + } + + formEditCode.getItems()[0].setHeight(325); + + codeMirrorCopy.setValue(value); + formEditCode.getItems()[0].setValue(value); + formEditCode.setDirty(false); + + $('#codeEditor .pmui-field-label').hide(); + $('#formEditCode').children().last().css({ + 'margin-top': '-352px', + 'border': '0px', + 'margin-right': '-15px' + }).find('a').css('padding', '10px 5px'); + $($('#codeEditor .CodeMirror.cm-s-default.CodeMirror-wrap')[0]).css({ + 'margin-left': '10px', + 'width': '850px', + 'height': '360px' + }); + $('#triggerWindow .pmui-window-body').css('overflow', 'hidden'); + codeMirrorCopy.refresh(); + }, + style: { + cssProperties: { + "margin-right": 2 + } + } + } + ] + }); + cd = new PMCodeMirrorField({ + labelWidth: '23.8%' + }); + cd.setLabel("Code".translate()); + formEditTriggerCustom.addItem(cd); + formEditTriggerCustom.getItems()[1].setName('code'); + formEditTriggerCustom.getItems()[1].setID('code'); + + formEditCode = new PMUI.form.Form({ + id: "formEditCode", + border: true, + visibleHeader: false, + width: '925px', + name: "formeditcode", + title: "Editor".translate(), + items: [], + buttons: [ + { + text: "@@", + id: "selectPickerButton", + handler: function () { + var picker = new VariablePicker(); + picker.open({ + success: function (variable) { + var codeMirror = formEditCode.getItems()[0].controls[0].cm; + var cursorPos = codeMirror.getCursor(); + codeMirror.replaceSelection(variable); + codeMirror.setCursor(cursorPos.line, cursorPos.ch); + } + }); + }, + style: { + cssProperties: { + "margin-left": '229px', + "background": "rgb(45, 62, 80)", + "border": "1px solid rgb(45, 62, 80)" + } + } + } + ] + }); + editCode = new PMCodeMirrorField({ + labelWidth: '9%' + }); + editCode.setLabel("Code".translate()); + formEditCode.addItem(editCode); + formEditCode.getItems()[0].setName('codeEditor'); + formEditCode.getItems()[0].setID('codeEditor'); + + //Trigger Window + triggerWindow = new PMUI.ui.Window({ + id: "triggerWindow", + title: "Triggers".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT, + footerItems: [ + buttonCancel, + buttonSave, + btnEditSourceCode, + applyButton, + copyButton + ], + buttonPanelPosition: "bottom", + footerAling: "right", + onBeforeClose: function () { + clickedClose = true; + isDirtyFormTrigger(); + } + }); + + + triggerWindow.addItem(gridListTrigger); + triggerWindow.addItem(formEditTriggerCustom); + triggerWindow.addItem(formEditTriggerWizard); + triggerWindow.addItem(formCopyTrigger); + triggerWindow.addItem(formEditCode); + triggerWindow.addItem(accordionNewTrigger); + + if (typeof listTriggers !== "undefined") { + triggerWindow.open(); + codMirr.dom.labelTextContainer.style.width = "23.8%"; + codMirr.html.style.padding = "10px"; + formEditTriggerCustom.panel.html.style.padding = "10px 10px"; + $('#listTriggers .pmui-textcontrol').css({'margin-top': '5px', width: '250px'}); + applyStyleWindowForm(triggerWindow); + triggerWindow.hideFooter(); + openListTriggers(); + + gridListTrigger.dom.toolbar.appendChild(buttonNew.getHTML()); + buttonNew.defineEvents(); + + gridListTrigger.dom.toolbar.appendChild(buttonCopy.getHTML()); + buttonCopy.defineEvents(); + + gridListTrigger.dom.toolbar.appendChild(buttonWizard.getHTML()); + buttonWizard.defineEvents(); + + triggerWindow.defineEvents(); + gridListTrigger.sort('tri_title', 'asc'); + formEditTriggerCustom.panel.style.addProperties({'overflow': 'hidden'}); + + formcustom = triggerWindow.getItems()[1]; + valuesCustom=formcustom.getItems()[0]; + } + }; + + PMDesigner.trigger.create = function () { + var codeMirrorControl, cmControlCopyTrigger; + openFormCustom("Create".translate()); + formEditTriggerCustom.getField("code").dom.labelTextContainer.style.width = "23.8%"; + $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); + formEditTriggerCustom.showFooter(); + + codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; + formEditTriggerCustom.getItems()[1].html.style.padding = "10px"; + if (codeMirrorControl !== undefined) { + codeMirrorControl.setSize(580, 150); + codeMirrorControl.refresh(); + } + codeMirrorControl.refresh(); + formEditTriggerCustom.getItems()[1].setHeight(170); + formEditTriggerCustom.reset(); + }; +}()); +/** + * new stepTask module + */ +var stepsTask = function (activity) { + this.mainWindow = null; + this.secondaryWindow = null; + this.stepsAssignTree = null; + this.mainContainer = null; + this.labelsPanel = null; + this.stepsMainContainer = null; + this.stepsAssignAccordion = null; + this.confirmWindow = null; + this.elementAccordionOpen = null; + this.groupType = null; + this.groupLabel = null; + this.stepsType = null; + this.stepsAssigned = null; + stepsTask.prototype.initialize.call(this, activity); +}; +/** + * initialization method steps settings, constants are created. + * components are created + * the data is loaded + * styles are customized + * It extends behaviors and events + */ +stepsTask.prototype.initialize = function () { + this.groupType = ['DYNAFORM', 'INPUT_DOCUMENT', 'OUTPUT_DOCUMENT', 'EXTERNAL']; + this.groupLabel = ['Dynaform (s)'.translate(), 'Input Document (s)'.translate(), 'OutPut Document (s)'.translate(), 'External (s)'.translate()]; + this.stepsType = { + "DYNAFORM": "Dynaform".translate(), + "INPUT_DOCUMENT": "Input Document".translate(), + "OUTPUT_DOCUMENT": "Output Document".translate(), + "EXTERNAL": "External".translate() + }; + this.stepsAssigned = new PMUI.util.ArrayList(); + this.elementAccordionOpen = new PMUI.util.ArrayList(); + this.createWidgets(); + this.mainWindow.addItem(this.mainContainer); + this.mainWindow.open(); + this.loadInitialData(); + this.customStyles(); + this.elementsAccordionOpenFixed(); + this.addEventSortableInAccordionElements(); + this.addEventSortableInTreePanelElements(); +}; +/** + * the components are created PMUI UI + * - confirmWindow + * - mainWindow + * - labelsPanel + * - stepsAssignTree + * - stepsAssignAccordion + * - stepsMainContainer + * - mainContainer + * - secondaryWindow + */ +stepsTask.prototype.createWidgets = function () { + var that = this; + this.confirmWindow = new PMUI.ui.MessageWindow({ + id: 'confirmWindowDeleteAcceptedValue', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: '', + message: '', + footerItems: [ + { + id: 'confirmWindow-footer-no', + text: 'No'.translate(), + visible: true, + buttonType: "error" + }, { + id: 'confirmWindow-footer-yes', + text: 'Yes'.translate(), + visible: true, + buttonType: "success" + } + ], + visibleFooter: true + }); + this.mainWindow = new PMUI.ui.Window({ + id: "stepsForTask", + title: "Steps for task".translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH + }); + this.labelsPanel = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH, + proportion: 0.08, + layout: "hbox", + items: [ + new PMUI.field.TextAnnotationField({ + text: 'Available Elements'.translate(), + text_Align: 'center', + proportion: 1.4 + }), + new PMUI.field.TextAnnotationField({ + text: 'Assigned Elements (Drop here)'.translate(), + text_Align: 'center', + proportion: 1.3 + }), + new PMUI.ui.Button({ + buttonType: "link", + "text": "Expand all".translate(), + id: "expand-button", + proportion: 0.6, + handler: function () { + var items, i, item, buttonAfected; + items = that.stepsAssignAccordion.getItems(); + buttonAfected = that.labelsPanel.getItem("collapse-button"); + buttonAfected.setDisabled(false); + this.setDisabled(true); + that.elementAccordionOpen.clear(); + for (i = 0; i < items.length; i += 1) { + item = items[i]; + item.expand(); + that.elementAccordionOpen.insert(item); + } } - ] - }); - - isDirtyFormTrigger = function () { - $("input,select,textarea").blur(); - $("div.pmui-window-body.pmui-background").css('overflow', ''); - var formcustom = triggerWindow.getItems()[1]; - var formwizard = triggerWindow.getItems()[2]; - var formcopy = triggerWindow.getItems()[3]; - var formeditcode = triggerWindow.getItems()[4]; - var accordionnewtrigger = triggerWindow.getItems()[5]; - var flag = false; - - var finalData = { - tri_uid: getData2PMUI(formEditTriggerCustom.html).uid, - tri_title: getData2PMUI(formEditTriggerCustom.html).title, - tri_description: getData2PMUI(formEditTriggerCustom.html).description, - tri_webbot: getData2PMUI(formEditTriggerCustom.html).code - }; - - if (formcustom.isVisible() == true) { - flag = (checkIfValuesAreEqual(triggerOriginDataForUpdate, finalData)) ? false : true; - } else if (formwizard.isVisible() == true) { - flag = formEditTriggerWizard.isDirty(); - } else if (formcopy.isVisible() == true) { - flag = formCopyTrigger.isDirty(); - if (!flag) { - $('.ctrlSpaceMessage').remove(); + }), + new PMUI.ui.Button({ + buttonType: "link", + "text": "Collapse all".translate(), + id: "collapse-button", + proportion: 0.7, + disabled: true, + handler: function () { + var items, i, item, buttonAfected; + buttonAfected = that.labelsPanel.getItem("expand-button"); + buttonAfected.setDisabled(false); + this.setDisabled(true); + items = that.stepsAssignAccordion.getItems(); + for (i = 0; i < items.length; i += 1) { + item = items[i]; + that.elementAccordionOpen.remove(item); + item.collapse(); + } } - } else if (formeditcode.isVisible() == true) { - flag = formeditcode.isDirty(); - var flagFormCustom = (checkIfValuesAreEqual(triggerOriginDataForUpdate, finalData)) ? false : true; - if (!flag && formeditcode.getItems()[0].controls[0].value != "" || flagFormCustom) { - flag = true; + }) + ] + }); + this.stepsAssignTree = new PMUI.panel.TreePanel({ + id: 'stepsAssignTree', + proportion: 0.5, + height: 475, + filterable: true, + autoBind: true, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nodeDefaultSettings: { + labelDataBind: 'obj_title', + autoBind: true, + collapsed: false, + itemsDataBind: 'items', + childrenDefaultSettings: { + labelDataBind: 'obj_title', + autoBind: true + }, + behavior: 'drag' + }, + style: { + cssProperties: { + margin: '0px 0px 0px 0px', + float: 'left', + overflow: 'auto' + }, + cssClasses: ['mafe-border-panel'] + } + }); + this.stepsAssignAccordion = new PMUI.panel.AccordionPanel({ + id: 'stepsAssignAccordion', + multipleSelection: true, + hiddenTitle: true, + proportion: 1.5, + style: { + cssProperties: { + margin: '0px 0px 0px 0px' + }, + cssClasses: ['mafe-border-panel'] + }, + listeners: { + select: function (accordionItem, event) { + var buttonExpand, buttonCollapse, itemsAccod; + itemsAccod = that.stepsAssignAccordion.items; + if (accordionItem.collapsed) { + if (that.elementAccordionOpen.indexOf(accordionItem) > -1) { + that.elementAccordionOpen.remove(accordionItem); + } + } else { + if (that.elementAccordionOpen.indexOf(accordionItem) === -1) { + that.elementAccordionOpen.insert(accordionItem); + } } - } - - if (flag == true) { - var message_window = new PMUI.ui.MessageWindow({ - id: "cancelMessageTriggers", - title: "Triggers".translate(), - windowMessageType: 'warning', - width: 490, - message: 'Are you sure you want to discard your changes?'.translate(), - footerItems: [ - { - text: "No".translate(), - handler: function () { - message_window.close(); - }, - buttonType: "error" - }, { - text: "Yes".translate(), - handler: function () { - triggerOriginDataForUpdate = {}; - var formcustom = triggerWindow.getItems()[1]; - var formwizard = triggerWindow.getItems()[2]; - var formcopy = triggerWindow.getItems()[3]; - var formeditcode = triggerWindow.getItems()[4]; - - if (formcustom.isVisible() == true) { - var uidInForm = formEditTriggerCustom.getFields()[0].getValue(); - formEditTriggerCustom.reset(); - openListTriggers(); - } else if (formwizard.isVisible() == true) { - var uidInForm = formEditTriggerWizard.getFields()[0].getValue(); - formEditTriggerWizard.reset(); - openListTriggers(); - } else if (formcopy.isVisible() == true) { - $('.ctrlSpaceMessage').remove(); - formCopyTrigger.reset(); - openListTriggers(); - } else if (formeditcode.isVisible() == true) { - formeditcode.reset(); - openFormCustom("Edit".translate()); - } - message_window.close(); - if (clickedClose) { - triggerWindow.close(); - } - }, - buttonType: "success" - } - ] - }); - message_window.open(); - message_window.showFooter(); - } else { - var formcustom = triggerWindow.getItems()[1]; - var formwizard = triggerWindow.getItems()[2]; - var formcopy = triggerWindow.getItems()[3]; - var formeditcode = triggerWindow.getItems()[4]; - var accordionnewtrigger = triggerWindow.getItems()[5]; - - if (formcustom.isVisible() == true) { - var uidInForm = formEditTriggerCustom.getFields()[0].getValue(); - formEditTriggerCustom.reset(); - openListTriggers(); - } else if (formwizard.isVisible() == true) { - var uidInForm = formEditTriggerWizard.getFields()[0].getValue(); - formEditTriggerWizard.reset(); - openListTriggers(); - } else if (formcopy.isVisible() == true) { - formCopyTrigger.reset(); - openListTriggers(); - } else if (formeditcode.isVisible() == true) { - formeditcode.reset(); - openFormCustom("Edit".translate()); - } else if (accordionnewtrigger.isVisible() == true) { - openListTriggers(); - } - if (clickedClose) { - triggerWindow.close(); + buttonCollapse = that.labelsPanel.getItem("collapse-button"); + buttonExpand = that.labelsPanel.getItem("expand-button"); + if (that.elementAccordionOpen.getSize() === 0) { + buttonExpand.setDisabled(false); + buttonCollapse.setDisabled(true); + } else if (that.elementAccordionOpen.getSize() === itemsAccod.getSize()) { + buttonExpand.setDisabled(true); + buttonCollapse.setDisabled(false); + } else { + buttonExpand.setDisabled(false); + buttonCollapse.setDisabled(false); } } - }; - //GRID List Case Scheduler - gridListTrigger = new PMUI.grid.GridPanel({ - id: "listTriggers", - pageSize: 10, - width: "96%", - style: { - cssClasses: ["mafe-gridPanel"] - }, - filterPlaceholder: 'Search ...'.translate(), - nextLabel: 'Next'.translate(), - previousLabel: 'Previous'.translate(), - tableContainerHeight: 374, - customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { - return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); - }, - columns: [ - { - id: 'listTriggersButtonShow', - title: '', - dataType: 'button', - searchable: false, - buttonLabel: 'Show ID'.translate(), - buttonStyle: { - cssClasses: [ - 'mafe-button-show' - ] - }, - id: 'copyuid', - onButtonClick: function (row, grid) { - var dataRow = row.getData(); - messageWindow = new PMUI.ui.MessageWindow({ - id: 'dynaformMessageWindowUID', - windowMessageType: 'info', - width: 490, - title: "Triggers".translate(), - message: dataRow.tri_uid, - footerItems: [ - { - text: 'OK'.translate(), - handler: function () { - messageWindow.close(); - }, - buttonType: "success" - } - ] - }); - messageWindow.setTitle("ID".translate()); - messageWindow.open(); - messageWindow.showFooter(); - $(messageWindow.dom.icon).removeClass(); - } - }, - { - title: 'Title'.translate(), - id: "title", - dataType: 'string', - width: "407px", - visible: true, - columnData: "tri_title", - searcheable: true, - sortable: true, - alignmentCell: 'left' - }, - { - title: 'Type'.translate(), - id: "type", - dataType: 'string', - width: "225px", - visible: true, - alignmentCell: 'left', - columnData: function (data) { - if (typeof(data.tri_param) == "object" && typeof(data.tri_param.params) == "object") { - var wizardData = data.tri_param.params; - - return wizardData.LIBRARY_NAME; - } else { - return "Custom"; - } - }, - searcheable: true, - sortable: true - }, - { - id: "editButton", - title: '', - dataType: 'button', - messageTooltip: "Edit".translate(), - buttonLabel: "Edit".translate(), - buttonStyle: { - cssClasses: [ - 'mafe-button-edit' - ] - }, - onButtonClick: function (row, grid) { - triggerOriginDataForUpdate = {}; - var data = row.getData(); - triggerOriginDataForUpdate = data; - var fields; - if (data.tri_param == "") { - - openFormCustom("Edit".translate()); - formEditTriggerCustom.showFooter(); - - var codeMirrorControl, cmControlCopyTrigger; - codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; - - if (codeMirrorControl != undefined) { - codeMirrorControl.setSize(580, 160); - } - formEditTriggerCustom.getItems()[1].setHeight(170); - fields = formEditTriggerCustom.getItems()[0]; - fields.getItems()[0].setValue(data.tri_uid); - fields.getItems()[1].setValue(data.tri_title); - fields.getItems()[2].setValue(data.tri_description); - formEditTriggerCustom.getItems()[1].setValue(data.tri_webbot); - - codeMirrorControl.setValue(data.tri_webbot); - codeMirrorControl.refresh(); - } else { - openFormWizardEditMode(); - - var wizardData = data.tri_param.params; - - var lib = wizardData.LIBRARY_CLASS; - lib = lib.split('.'); - lib = lib[1]; - fields = formEditTriggerWizard.getFields(); - fields[0].setValue(data.tri_uid); - fields[1].setValue(lib); - fields[2].setValue(wizardData.PMFUNTION_NAME); - fields[3].setValue(wizardData.LIBRARY_NAME + " (" + wizardData.PMFUNTION_LABEL + ")"); - fields[4].setValue(data.tri_title); - fields[5].setValue(data.tri_description); - fields[6].setValue(data.tri_webbot); - - var inputItems = []; - var outputItems = []; - - restClient = new PMRestClient({ - endpoint: "trigger-wizard/" + lib + "/" + wizardData.PMFUNTION_NAME, - typeRequest: 'get', - functionSuccess: function (xhr, response) { - if (response.fn_params.input != undefined) { - for (j = 0; j < response.fn_params.input.length; j++) { - var nameInput = response.fn_params.input[j].name; - - var inp = new CriteriaField({ - id: nameInput, - pmType: "text", - name: nameInput, - label: response.fn_params.input[j].label, - value: wizardData[nameInput].toString(), - controlsWidth: 400, - labelWidth: '27%', - helper: response.fn_params.input[j].description, - required: response.fn_params.input[j].name === "unpauseDate" ? true : response.fn_params.input[j].required - }); - - inputItems.push(inp); - } - } - if (response.fn_params.output != undefined) { - for (k = 0; k < response.fn_params.output.length; k++) { - var nameOutput = response.fn_params.output[k].name; - - var out = new CriteriaField({ - id: nameOutput, - pmType: "text", - name: nameOutput, - label: response.fn_params.output[k].label, - value: wizardData.TRI_ANSWER.toString(), - controlsWidth: 400, - labelWidth: '27%', - helper: response.fn_params.output[k].description, - required: response.fn_params.output[k].required - }); - - outputItems.push(out); - } - } - triggerWindow.setTitle("Edit".translate() + " " + wizardData.LIBRARY_NAME); - if (inputItems.length > 0) { - formEditTriggerWizard.getItems()[1].setVisible(true); - formEditTriggerWizard.getItems()[2].setVisible(true); - formEditTriggerWizard.getItems()[3].setVisible(true); - formEditTriggerWizard.getItems()[3].clearItems(); - formEditTriggerWizard.getItems()[3].setItems(inputItems); - } else { - formEditTriggerWizard.getItems()[1].setVisible(false); - formEditTriggerWizard.getItems()[2].setVisible(false); - formEditTriggerWizard.getItems()[3].setVisible(false); - formEditTriggerWizard.getItems()[3].clearItems(); - } - if (outputItems.length > 0) { - formEditTriggerWizard.getItems()[4].setVisible(true); - formEditTriggerWizard.getItems()[5].setVisible(true); - formEditTriggerWizard.getItems()[6].setVisible(true); - formEditTriggerWizard.getItems()[6].clearItems(); - formEditTriggerWizard.getItems()[6].setItems(outputItems); - } else { - formEditTriggerWizard.getItems()[4].setVisible(false); - formEditTriggerWizard.getItems()[5].setVisible(false); - formEditTriggerWizard.getItems()[6].setVisible(false); - formEditTriggerWizard.getItems()[6].clearItems(); - } - labelInputs.dom.labelTextContainer.style.display = "none"; - labelOutputs.dom.labelTextContainer.style.display = "none"; - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: "There are problems getting the triggers wizard list, please try again.".translate() - }); - restClient.executeRestClient(); - } - } + } + }); + this.stepsMainContainer = new PMUI.core.Panel({ + id: "stepsMainContainer", + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT - 45, + layout: 'hbox', + height: 475, + items: [ + this.stepsAssignTree, + this.stepsAssignAccordion + ] + }); + this.mainContainer = new PMUI.core.Panel({ + id: "mainContainer", + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT - 45, + layout: 'vbox', + items: [ + this.labelsPanel, + this.stepsMainContainer + ] + }); + this.secondaryWindow = new PMUI.ui.Window({ + visibleFooter: true, + title: 'Trigger'.translate(), + footerAlign: 'right', + footerItems: [ + { + text: "@@", + id: "secondaryWindow-criteria", + handler: function () { }, - { - id: "deleteButton", - title: '', - dataType: 'button', - messageTooltip: "Delete".translate(), - buttonLabel: "Delete".translate(), - buttonStyle: { - cssClasses: [ - 'mafe-button-delete' - ] + style: { + cssProperties: { + "background": "rgb(45, 62, 80)", + "border": "1px solid rgb(45, 62, 80)" }, - onButtonClick: function (row, grid) { - var questionWindow, dataRow = row.getData(); - - questionWindow = new PMUI.ui.MessageWindow({ - id: "questionDeleteWindow", - title: "Triggers".translate(), - windowMessageType: 'warning', - width: 490, - message: "Do you want to delete this Trigger?".translate(), - footerItems: [ - { - id: 'questionDeleteWindowButtonNo', - text: "No".translate(), - visible: true, - handler: function () { - questionWindow.close(); - }, - buttonType: "error" - }, { - id: 'questionDeleteWindowButtonYes', - text: "Yes".translate(), - visible: true, - handler: function () { - questionWindow.close(); - restClient = new PMRestClient({ - endpoint: "trigger/" + dataRow.tri_uid, - typeRequest: 'remove', - functionSuccess: function (xhr, response) { - grid.removeItem(row); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageSuccess: "Trigger deleted successfully".translate(), - flashContainer: gridListTrigger - }); - restClient.executeRestClient(); - }, - buttonType: "success" - }, - ] - }); - - questionWindow.open(); - questionWindow.dom.titleContainer.style.height = "17px"; - questionWindow.showFooter(); - } + cssClasses: ["mafe-button-condition-trigger"] } - ], - dataItems: listTriggers, - onRowClick: function (row, data) { - - } - }); - - getListTrigger = function () { - var restClient = new PMRestClient({ - endpoint: 'triggers', - typeRequest: 'get', - functionSuccess: function (xhr, response) { - listTriggers = response; - gridListTrigger.setDataItems(listTriggers); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); + }, { + id: 'secondaryWindow-cancel', + text: 'Cancel'.translate(), + buttonType: 'error', + height: 31, + style: { + cssClasses: ["mafe-button-condition-trigger"] }, - messageError: "There are problems getting the Triggers list, please try again.".translate() - }); - restClient.executeRestClient(); - }; - - addNumberTriggerWizard = function (value, position) { - coutTriggers = document.createElement("span"); - coutTriggers.textContent = value; - headerAccordion = triggerWindow.getItems()[5].getItems()[position].header.html; - headerAccordion.appendChild(coutTriggers); - coutTriggers.style.float = "right"; - coutTriggers.style.color = "white"; - coutTriggers.style.fontSize = "13px"; - coutTriggers.style.marginRight = "6px"; - coutTriggers.style.marginTop = "3px"; - }; - - newTriggerOptions = function () { - - var acItemCustom = accordionNewTrigger.getItems()[0]; - var acItemCopy = accordionNewTrigger.getItems()[1]; - acItemCustom.setIconClosed('pmcustomtrigger'); - acItemCustom.setIconExpanded('pmcustomtrigger'); - acItemCopy.setIconClosed('pmcopytrigger'); - acItemCopy.setIconExpanded('pmcopytrigger'); - - var itemCustom = jQuery("#custom > .pmui-accordion-item-header > span")[1]; - itemCustom.style.width = "0px"; - var itemCopy = jQuery("#copy > .pmui-accordion-item-header > span")[1]; - itemCopy.style.width = "0px"; - - var numOfItems = accordionNewTrigger.getItems(); - - var lengthLibFunctions = []; - if (numOfItems.length <= 2) { - restClient = new PMRestClient({ - endpoint: "trigger-wizards", - typeRequest: 'get', - functionSuccess: function (xhr, response) { - for (i = 0; i < response.length; i++) { - var functTree = response[i].lib_functions; - lengthLibFunctions[i] = functTree.length; - var newTreeItems = []; - for (h = 0; h < functTree.length; h++) { - newTreeItems.push({ - label: functTree[h].fn_label, - id: functTree[h].fn_name, - onClick: function () { - for (s = 0; s < response.length; s++) { - for (p = 0; p < response[s].lib_functions.length; p++) { - if (response[s].lib_functions[p].fn_name == this.id) { - var fn = response[s].lib_functions[p].fn_params; - var fnLabel = response[s].lib_functions[p].fn_label; - var fnName = response[s].lib_functions[p].fn_name; - var libName = response[s].lib_name; - var libTitle = response[s].lib_title; - p = response[s].lib_functions.length; - s = response.length - 1; - } - } - } - var inputItems = []; - if (fn.input != undefined) { - for (j = 0; j < fn.input.length; j++) { - var val = ""; - if (fn.input[j].type == "array") { - val = "array('')"; - } - var inp = new CriteriaField({ - id: fn.input[j].name, - pmType: "text", - name: fn.input[j].name, - label: fn.input[j].label, - controlsWidth: 400, - labelWidth: '27%', - value: val, - helper: fn.input[j].description, - required: fn.input[j].name === "unpauseDate" ? true : fn.input[j].required - }); - - inputItems.push(inp); - } - } - - var outputItems = []; - if (fn.output != undefined) { - for (k = 0; k < fn.output.length; k++) { - var out = new CriteriaField({ - id: fn.output[k].name, - pmType: "text", - name: fn.output[k].name, - label: fn.output[k].label, - controlsWidth: 400, - labelWidth: '27%', - helper: fn.output[k].description, - required: fn.output[k].required - }); - - outputItems.push(out); - } - } - formEditTriggerWizard.reset(); - formEditTriggerWizard.setTitle(fnLabel + ' (' + fnName + ')'); - formEditTriggerWizard.getItems()[0].getItems()[1].setValue(libName); - formEditTriggerWizard.getItems()[0].getItems()[2].setValue(fnName); - formEditTriggerWizard.getItems()[0].getItems()[3].setValue(libTitle + ' (' + fnLabel + ')'); - - if (inputItems.length > 0) { - formEditTriggerWizard.getItems()[1].setVisible(true); - formEditTriggerWizard.getItems()[2].setVisible(true); - formEditTriggerWizard.getItems()[3].setVisible(true); - formEditTriggerWizard.getItems()[3].clearItems(); - formEditTriggerWizard.getItems()[3].setItems(inputItems); - } else { - formEditTriggerWizard.getItems()[1].setVisible(false); - formEditTriggerWizard.getItems()[2].setVisible(false); - formEditTriggerWizard.getItems()[3].setVisible(false); - formEditTriggerWizard.getItems()[3].clearItems(); - } - if (outputItems.length > 0) { - formEditTriggerWizard.getItems()[4].setVisible(true); - formEditTriggerWizard.getItems()[5].setVisible(true); - formEditTriggerWizard.getItems()[6].setVisible(true); - formEditTriggerWizard.getItems()[6].clearItems(); - formEditTriggerWizard.getItems()[6].setItems(outputItems); - } else { - formEditTriggerWizard.getItems()[4].setVisible(false); - formEditTriggerWizard.getItems()[5].setVisible(false); - formEditTriggerWizard.getItems()[6].setVisible(false); - formEditTriggerWizard.getItems()[6].clearItems(); - } - openFormWizard(); - $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); - triggerWindow.setTitle("Create".translate() + " " + libTitle); - } - }); - } - labelInputs.dom.labelTextContainer.style.display = "none"; - labelOutputs.dom.labelTextContainer.style.display = "none"; - allTreesItems[i] = newTreeItems; - - var arrayTriggerWizards = [ - "pmFunctions", - "pmSugar", - "pmTalend", - "pmTrAlfresco", - "pmTrSharepoint", - "pmZimbra" - ]; - - if (arrayTriggerWizards.indexOf(response[i].lib_name) == -1) { - $("head").append(""); - } - - //Accordion - var newAccordionItem = []; - newAccordionItem = { - iconClass: response[i].lib_name, - id: response[i].lib_name, - title: response[i].lib_title, - height: 'auto' - }; - accordionNewTrigger.addItem(newAccordionItem); - } - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: "There are problems getting the triggers wizard list, please try again.".translate() - }); - restClient.executeRestClient(); - } - - openNewTriggerOptions(); - var accordion = triggerWindow.getItems()[5].getItems(); - accordion[0].setVisible(false); - accordion[1].setVisible(false); - for (i = 0; i < accordion.length; i++) { - accordion[i].header.html.style.backgroundColor = "#FFFFFF"; - if (i > 1) { - addNumberTriggerWizard(lengthLibFunctions[i - 2], (i)); + handler: function () { } - } - }; - - allTreesItems = []; - getListTrigger(); - - //Button NEW Trigger - buttonNew = new PMUI.ui.Button({ - id: 'newTriggerButton', - text: "Create".translate(), - height: "36px", - width: 100, - handler: function (event) { - openFormCustom("Create".translate()); - formEditTriggerCustom.getField("code").dom.labelTextContainer.style.width = "23.8%"; - $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); - formEditTriggerCustom.showFooter(); - - var codeMirrorControl, cmControlCopyTrigger; - codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; - formEditTriggerCustom.getItems()[1].html.style.padding = "10px"; - if (codeMirrorControl !== undefined) { - codeMirrorControl.setSize(580, 150); - } - formEditTriggerCustom.getItems()[1].setHeight(170); - - formEditTriggerCustom.reset(); - - fields = formEditTriggerCustom.getItems()[0]; - fields.getItems()[0].setValue(""); - fields.getItems()[1].setValue(""); - fields.getItems()[2].setValue(""); - formEditTriggerCustom.getItems()[1].setValue(""); - formEditTriggerCustom.getItems()[1].controls[0].cm.setValue(""); - codeMirrorControl.refresh(); - }, - style: { - cssClasses: [ - 'mafe-button-create' - ] - } - }); - - //Button COPY Trigger - buttonCopy = new PMUI.ui.Button({ - id: 'copyTriggerButton', - text: "Copy".translate(), - height: "36px", - width: 100, - handler: function (event) { - getListProjects(); - openFormCopy(); - formCopyTrigger.getFields()[1].clearOptions(); - $("#Code .CodeMirror.cm-s-default.CodeMirror-wrap").css({'border': '1px solid #c0c0c0'}); - - var cmControlCopyTrigger = formCopyTrigger.getFields()[4].controls[0].cm; - cmControlCopyTrigger.setValue(""); - if (cmControlCopyTrigger !== undefined) { - cmControlCopyTrigger.setSize(650, 140); + }, { + id: 'secondaryWindow-save', + text: 'Save'.translate(), + buttonType: 'success', + height: 31, + style: { + cssClasses: ["mafe-button-condition-trigger"] + }, + handler: function () { } - cmControlCopyTrigger.refresh(); - }, - style: { - cssClasses: [ - 'mafe-button-create' - ] } - }); - - //Button WIZARD Trigger - buttonWizard = new PMUI.ui.Button({ - id: 'wizardTriggerButton', - text: "Wizard".translate(), - height: "36px", - width: 100, - handler: function (event) { - newTriggerOptions(); - }, - style: { - cssClasses: [ - 'mafe-button-create' - ] - } - }); - - openListTriggers = function () { - triggerWindow.getItems()[0].setVisible(true); - triggerWindow.getItems()[1].setVisible(false); - triggerWindow.getItems()[2].setVisible(false); - triggerWindow.getItems()[3].setVisible(false); - triggerWindow.getItems()[4].setVisible(false); - triggerWindow.getItems()[5].setVisible(false); - triggerWindow.setTitle("Triggers".translate()); - triggerWindow.hideFooter(); - $(triggerWindow.body).removeClass("pmui-background"); - }; - - openFormCustom = function (typeTitle) { - triggerWindow.getItems()[0].setVisible(false); - triggerWindow.getItems()[1].setVisible(true); - triggerWindow.getItems()[2].setVisible(false); - triggerWindow.getItems()[3].setVisible(false); - triggerWindow.getItems()[4].setVisible(false); - triggerWindow.getItems()[5].setVisible(false); - triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel - triggerWindow.footer.getItems()[1].setVisible(true); //button Save - triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code - triggerWindow.footer.getItems()[3].setVisible(false); //button Aply - triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import - - triggerWindow.setTitle(typeTitle + " Custom Trigger".translate()); - triggerWindow.showFooter(); - $(triggerWindow.body).addClass("pmui-background"); - formEditTriggerCustom.setFocus(); - - $('.CodeMirror.cm-s-default')[0].style.border = "1px solid #c0c0c0"; - if (formEditTriggerCustom.getItems()[0].getItems()[1].visible == false) { - var fields = formEditTriggerCustom.getItems()[0]; - fields.getItems()[1].setVisible(true); - fields.getItems()[2].setVisible(true); - formEditTriggerCustom.footer.getItems()[1].setVisible(true); - } - formEditTriggerCustom.getFields()[4].dom.labelTextContainer.style.marginLeft = "10px"; - formEditTriggerCustom.setAlignmentButtons('left'); - - $("#code").after($ctrlSpaceMessage.css({ - "margin": "5px 0 0 0", - "text-align": "center", - "width": "655px", - "padding": "" - })); - }; - - openFormWizard = function () { - triggerWindow.getItems()[0].setVisible(false); - triggerWindow.getItems()[1].setVisible(false); - triggerWindow.getItems()[2].setVisible(true); - triggerWindow.getItems()[3].setVisible(false); - triggerWindow.getItems()[4].setVisible(false); - triggerWindow.getItems()[5].setVisible(false); - triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel - triggerWindow.footer.getItems()[1].setVisible(true); //button Save - triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code - triggerWindow.footer.getItems()[3].setVisible(false); //button Aply - triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import - triggerWindow.showFooter(); - $(triggerWindow.body).addClass("pmui-background"); - formEditTriggerWizard.setFocus(); - }; - - openFormWizardEditMode = function () { - triggerWindow.getItems()[0].setVisible(false); - triggerWindow.getItems()[1].setVisible(false); - triggerWindow.getItems()[2].setVisible(true); - triggerWindow.getItems()[3].setVisible(false); - triggerWindow.getItems()[4].setVisible(false); - triggerWindow.getItems()[5].setVisible(false); - triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel - triggerWindow.footer.getItems()[1].setVisible(true); //button Save - triggerWindow.footer.getItems()[2].setVisible(true); //Edit Source Code - triggerWindow.footer.getItems()[3].setVisible(false); //button Aply - triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import - triggerWindow.showFooter(); - $(triggerWindow.body).addClass("pmui-background"); - formEditTriggerWizard.setFocus(); - }; - - - openFormCopy = function () { - triggerWindow.getItems()[0].setVisible(false); - triggerWindow.getItems()[1].setVisible(false); - triggerWindow.getItems()[2].setVisible(false); - triggerWindow.getItems()[3].setVisible(true); - triggerWindow.getItems()[4].setVisible(false); - triggerWindow.getItems()[5].setVisible(false); - triggerWindow.setTitle("Copy Trigger".translate()); - triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel - triggerWindow.footer.getItems()[1].setVisible(false); //button Save - triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code - triggerWindow.footer.getItems()[3].setVisible(false); //button Aply - triggerWindow.footer.getItems()[4].setVisible(true); //button Copy/import - triggerWindow.showFooter(); - $(triggerWindow.body).addClass("pmui-background"); - formCopyTrigger.setFocus(); - - $(".pmui-field").css("float", "left"); - $('#Code .pmui.pmui-pmcodemirrorcontrol').append($ctrlSpaceMessage.css({ - "margin-top": "10px", - "text-align": "", - "width": "655px", - "padding": "" - })); - }; - - openFormEditCode = function () { - triggerWindow.getItems()[0].setVisible(false); - triggerWindow.getItems()[1].setVisible(false); - triggerWindow.getItems()[2].setVisible(false); - triggerWindow.getItems()[3].setVisible(false); - triggerWindow.getItems()[4].setVisible(true); - triggerWindow.getItems()[5].setVisible(false); - triggerWindow.setTitle("Editor".translate()); - triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel - triggerWindow.footer.getItems()[1].setVisible(false); //button Save - triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code - triggerWindow.footer.getItems()[3].setVisible(true); //button Aply - triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import - triggerWindow.showFooter(); - $(triggerWindow.body).addClass("pmui-background"); - - $($('#codeEditor .CodeMirror.cm-s-default.CodeMirror-wrap')[0]).after($ctrlSpaceMessage.css({ - "padding": "5px 0 0 10px", - "text-align": "" - })); - - }; - - openNewTriggerOptions = function () { - triggerWindow.getItems()[0].setVisible(false); - triggerWindow.getItems()[1].setVisible(false); - triggerWindow.getItems()[2].setVisible(false); - triggerWindow.getItems()[3].setVisible(false); - triggerWindow.getItems()[4].setVisible(false); - triggerWindow.getItems()[5].setVisible(true); - triggerWindow.setTitle("Create Predefined Trigger".translate()); - triggerWindow.footer.getItems()[0].setVisible(true); //button Cancel - triggerWindow.footer.getItems()[1].setVisible(false); //button Save - triggerWindow.footer.getItems()[2].setVisible(false); //Edit Source Code - triggerWindow.footer.getItems()[3].setVisible(false); //button Aply - triggerWindow.footer.getItems()[4].setVisible(false); //button Copy/import - triggerWindow.showFooter(); - $(triggerWindow.body).removeClass("pmui-background"); - }; - - //obtaning the list of process to show it on the copy/import of a trigger dropdown - listProjects = []; - getListProjects = function () { - restClient = new PMRestClient({ - typeRequest: 'get', - functionSuccess: function (xhr, response) { - listProjects = []; - formCopyTrigger.getFields()[0].clearOptions(); - listProjects[0] = { - label: "- Select a process -".translate(), - value: "", - disabled: true, - selected: true - }; - for (i = 0; i < response.length; i++) { - listProjects.push({ - label: response[i].prj_name, - value: response[i].prj_uid - }); - } - formCopyTrigger.getFields()[0].setOptions(listProjects); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: "There are problems getting the list of projects.".translate() - }); - restClient.setBaseEndPoint('projects'); - restClient.executeRestClient(); - }; - - //form Copy/Import Trigger - triggerSelectedData; - formCopyTrigger = new PMUI.form.Form({ - id: "formCopyTriggers", - border: true, - width: '890px', - height: 'auto', - title: "", - visibleHeader: false, - items: [ - { - pmType: 'dropdown', - id: "processField", - label: 'Process'.translate(), - name: 'prj_uid', - required: true, - controlsWidth: 300, - value: "", - options: listProjects, - onChange: function (newValue, prevValue) { - var formFields = formCopyTrigger.getFields(); - formFields[2].setValue(""); - formFields[3].setValue(""); - formFields[4].controls[0].cm.setValue(""); - - var uidProj = newValue, myForm = this.form; - - //obtaning the Trigger list of the process SELECTED - restClient = new PMRestClient({ - typeRequest: 'get', - functionSuccess: function (xhr, response) { - triggerSelectedData = response; - var listTriggersCopy = []; - listTriggersCopy[0] = { - label: "- Select a trigger -".translate(), - value: "", - disabled: true, - selected: true - }; + ] + }); +}; +/** + * This method loads the initial data module steps,for the components: + * - stepsAssignTree + * - stepsAssignAccordion + */ +stepsTask.prototype.loadInitialData = function () { + this.loadTreePanelData(this.getTreePanelData()); + this.loadAccordionItems(this.getAccordionData()); +}; +/** + * This method loads the options to stepsAssignAccordion + * @param {Array} response An array where each element can be a {Element} object or a JSON object + */ +stepsTask.prototype.loadAccordionItems = function (response) { + var firstResp = [], + secondResp = [], + i, + item, + assigmentConfig, + firstRes = 0, + secondRes = 1; + if (jQuery.isArray(response) && response.length) { + if (typeof response[firstRes] === "object") { + firstResp = response[firstRes].response ? response[firstRes].response : []; + } + if (typeof response[secondRes] === "object") { + secondResp = response[secondRes].response ? response[secondRes].response : []; + } + } + if (firstResp.length) { + for (i = 0; i < firstResp.length; i += 1) { + item = this.createAccordionItem(firstResp[i], true, true); + this.stepsAssignAccordion.addItem(item); + item.dataItem = firstResp[i]; + this.customAccordionItemButtons(item.html, firstResp[i], item); + } + } + assigmentConfig = { + step_type_obj: "Assignment".translate(), + triggers: secondResp, + st_type: "ASSIGNMENT", + obj_title: "Assignment".translate(), + step_uid_obj: "Assignment" + }; + item = this.createAccordionItem(assigmentConfig); + this.stepsAssignAccordion.addItem(item); + item.dataItem = assigmentConfig; + assigmentConfig = { + step_type_obj: "Routing".translate(), + triggers: secondResp, + obj_title: "Routing".translate(), + st_type: 'ROUTING', + step_uid_obj: "Routing" + }; + item = this.createAccordionItem(assigmentConfig); + this.stepsAssignAccordion.addItem(item); + item.dataItem = assigmentConfig; + this.stepsAssignAccordion.defineEvents(); +}; +/** + * This method creates an element for stepsAssignAccordion + * @param {data} It is an object with the settings to create the element + * @returns {PMUI.item.AccordionItem} + */ +stepsTask.prototype.createAccordionItem = function (data) { + var that = this, + gridBefore, + gridAfter, + beforeTitle, + afterTitle, + i, + textLabel; + if (this.stepsType[data.step_type_obj]) { + textLabel = this.stepsType[data.step_type_obj]; + } else { + textLabel = data.step_type_obj; + } + beforeTitle = new PMUI.field.TextAnnotationField({ + text: 'Before'.translate() + ' ' + textLabel, + proportion: 0.5, + text_Align: 'left' + }); + afterTitle = new PMUI.field.TextAnnotationField({ + text: 'After'.translate() + ' ' + textLabel, + proportion: 0.5, + text_Align: 'left', + visible: data.st_type === "ASSIGNMENT" ? false : true + }); - for (i = 0; i < response.length; i++) { - listTriggersCopy.push({ - label: response[i].tri_title, - value: response[i].tri_uid - }); - } - formFields[1].setOptions(listTriggersCopy); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: "There are problems getting the list of triggers.".translate() - }); - restClient.setBaseEndPoint("project/" + uidProj + "/triggers"); - restClient.executeRestClient(); - } - }, - { - pmType: 'dropdown', - id: "triggerField", - label: 'Trigger'.translate(), - name: 'tri_uid', - required: true, - controlsWidth: 300, - value: "", - options: [], - onChange: function (newValue, prevValue) { - var formFields = formCopyTrigger.getFields(); - formFields[2].setValue(""); - formFields[3].setValue(""); - formFields[4].controls[0].cm.setValue(""); - - var uidTri = newValue; - - for (i = 0; i < triggerSelectedData.length; i++) { - if (triggerSelectedData[i].tri_uid == uidTri) { - formFields[2].setValue(triggerSelectedData[i].tri_title); - formFields[3].setValue(triggerSelectedData[i].tri_description); - formFields[4].controls[0].cm.setValue(triggerSelectedData[i].tri_webbot); - } - } - } + gridBefore = new PMUI.grid.GridPanel({ + behavior: 'dragdropsort', + filterable: false, + visibleHeaders: false, + data: data.triggers, + st_type: 'BEFORE', + step_uid: data.step_uid, + visibleFooter: false, + width: '96%', + emptyMessage: 'No records found'.translate(), + style: { + cssClasses: ['mafe-gridPanel'] + }, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [ + { + title: '', + dataType: 'string', + alignmentCell: 'center', + columnData: "st_position", + width: 20 + }, { + title: 'Before Output Document'.translate(), + dataType: 'string', + alignmentCell: 'left', + columnData: 'tri_title', + width: 360 + }, { + title: '', + dataType: 'button', + buttonLabel: function (row, data) { + return data.st_condition === '' ? 'Condition'.translate() : 'Condition *'.translate(); }, - { - pmType: "text", - id: "triTitle", - label: "Title of the new trigger".translate(), - placeholder: "Insert the title of the new trigger".translate(), - name: "tri_title", - required: true, - valueType: 'string', - controlsWidth: 300, - style: { - cssProperties: { - 'float': 'left' + buttonStyle: {cssClasses: ['mafe-button-edit']}, + onButtonClick: function (row, grid) { + var data = row.getData(); + that.editCondition(grid.step_uid, data.tri_uid, data.st_type, row); + } + }, { + title: '', + dataType: 'button', + buttonLabel: 'Edit'.translate(), + buttonStyle: {cssClasses: ['mafe-button-edit']}, + onButtonClick: function (row, grid) { + var data = row.getData(), + restClient; + restClient = new PMRestClient({ + endpoint: 'trigger/' + data.tri_uid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + that.editTrigger(response.tri_webbot, response.tri_uid); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); } - } - }, - { - pmType: "textarea", - id: "triDescription", - rows: 80, - name: 'tri_description', - label: "Description of the new trigger".translate(), - valueType: 'string', - controlsWidth: 652, - style: { - cssClasses: ['mafe-textarea-resize'], - cssProperties: {'float': 'left'} - } + }); + restClient.executeRestClient(); } - ] - }); - codMirr = new PMCodeMirrorField(); - codMirr.setLabel("Code".translate()); - codMirr.setID("Code"); - codMirr.setName('tri_webbot'); - CodeMirror.commands.autocomplete = function (cm) { - CodeMirror.showHint(cm, CodeMirror.phpHint); - }; - formCopyTrigger.addItem(codMirr); - - //Form to Edit the trigger with the WIZARD (we used a Form because we need buttons to save the changes) - formEditTriggerWizard = new PMUI.form.Form({ - id: "formEditTriggerWizard", - border: true, - visibleHeader: false, - name: "formwizard", - width: 926, - title: "New Trigger".translate(), - items: [ - { - id: "panelDetailsWizard", - pmType: "panel", - layout: 'vbox', - fieldset: false, - height: 'auto', - legend: "DETAILS".translate(), - items: [ - { - id: "uid", - pmType: "text", - label: "ID".translate(), - value: "", - name: "uid", - visible: false, - valueType: 'string' - }, - { - id: "libName", - pmType: "text", - label: "", - value: "", - name: "libName", - visible: false, - valueType: 'string' - }, - { - id: "fnName", - pmType: "text", - label: "", - value: "", - name: "fnName", - visible: false, - valueType: 'string' - }, - { - id: "type", - pmType: "text", - label: "Type".translate(), - value: "WIZARD", - controlsWidth: 450, - labelWidth: '27%', - readOnly: true, - name: "type", - valueType: 'string' - }, - { - id: "titleDetailsWiz", - pmType: "text", - label: "Title".translate(), - value: "", - controlsWidth: 450, - labelWidth: '27%', - name: "titleDetails", - valueType: 'string', - required: true - }, - { - id: "descriptionDetailsWiz", - pmType: "textarea", - label: "Description".translate(), - value: "", - rows: 90, - width: '300px', - controlsWidth: 450, - labelWidth: '27%', - name: "descriptionDetails", - valueType: 'string', - style: {cssClasses: ['mafe-textarea-resize']} - }, - { - id: "webbot", - pmType: "text", - label: "Webbot".translate(), - value: "", - name: "webbot", - controlsWidth: 300, - labelWidth: '27%', - visible: false, - valueType: 'string' - } - ] - } - ] - }); - - //adding a separator Inputs line - sepInputs = new PMSeparatorLineField({ - controlHeight: '1px', - controlColor: "#CDCDCD", - controlsWidth: "890px", - marginLeft: '0%' - }); - formEditTriggerWizard.addItem(sepInputs); - - //adding a label Inputs - labelInputs = new PMLabelField({ - text: "PARAMETERS".translate(), - textMode: "plain", - style: { - cssProperties: { - color: "#AEAEAE", - 'font-weight': 'bold' - } - }, - controlsWidth: 885 - }); - formEditTriggerWizard.addItem(labelInputs); - - //adding the Inputs Items (PARAMETERS) Panel - paramPanel = new PMUI.form.FormPanel({ - id: "panelParametersWizard", - layout: 'vbox', - fieldset: false, - height: 'auto', - visible: false, - legend: "__PARAMETERS__".translate(), - items: [] - }); - formEditTriggerWizard.addItem(paramPanel); - - //adding a separator Outputs line - sepOutputs = new PMSeparatorLineField({ - controlHeight: 1, - controlColor: "#CDCDCD", - controlsWidth: "890px", - marginLeft: '0%' - }); - formEditTriggerWizard.addItem(sepOutputs); - - //adding a label Outputs - labelOutputs = new PMLabelField({ - text: "RETURN VALUE".translate(), - textMode: "plain", - style: { - cssProperties: { - color: "#AEAEAE", - 'font-weight': 'bold' - } - }, - controlsWidth: 885 - }); - - formEditTriggerWizard.addItem(labelOutputs); - - //adding the Output Items (Returns) Panel - returnPanel = new PMUI.form.FormPanel({ - id: "panelReturnValWizard", - layout: 'vbox', - fieldset: false, - height: 'auto', - visible: false, - legend: "RETURN VALUE".translate(), - items: [] - }); - formEditTriggerWizard.addItem(returnPanel); - - - //treePanel New Trigger PMF - treeNewTrigger = new PMUI.panel.TreePanel({ - id: "treeNewTrigger", - width: 'auto', - height: 'auto', - style: { - cssClasses: ['pmtrigger'], - cssProperties: { - 'margin-top': '5px', - 'margin-bottom': '4px' - } - }, - items: [] - }); - - //Acordion Panel New Triggers Options - accordionNewTrigger = new PMUI.panel.AccordionPanel({ - id: "accordionNewTrigger", - width: 885, - height: 'auto', - borderWidth: "0px", - hiddenTitle: true, - style: { - cssProperties: { - 'margin-left': '30px' + }, { + title: '', + dataType: 'button', + buttonLabel: 'Remove'.translate(), + buttonStyle: {cssClasses: ['mafe-button-delete']}, + onButtonClick: function (row, grid) { + that.removeTrigger(row, grid); } - }, - items: [ - { - iconClass: "", - id: 'custom', - title: "Custom Trigger".translate(), - height: '26px', - body: "", - style: { - cssProperties: { - "background-color": "#FDFDFD" - } - } + } + ], + onDrop: function (container, draggableItem, index) { + var receiveData = draggableItem.getData(); + if (draggableItem instanceof PMUI.item.TreeNode) { + that.receiveTreeNodeItem(receiveData, this, index); + } else { + that.receiveRowItem(receiveData, this, index, draggableItem); + } + that.updateIndexToGrid(this); + return false; + }, + onSort: function (container, item, index) { + var receiveData = item.getData(); + that.sortableRowHandler(receiveData, this, index); + that.updateIndexToGrid(this); + } + }); + if (data.st_type !== "ROUTING" && data.st_type !== "ASSIGNMENT") { + gridBefore.st_type = 'BEFORE'; + } else if (data.st_type === "ROUTING") { + gridBefore.st_type = "BEFORE_ROUTING"; + } else { + gridBefore.st_type = "BEFORE_ASSIGNMENT"; + } + gridBefore.step_uid = data.step_uid; + gridBefore.clearItems(); + if (jQuery.isArray(data.triggers)) { + for (i = 0; i < data.triggers.length; i += 1) { + if (gridBefore.st_type === data.triggers[i].st_type) { + gridBefore.addDataItem({ + st_condition: data.triggers[i].st_condition, + st_position: data.triggers[i].st_position, + st_type: data.triggers[i].st_type, + tri_description: data.triggers[i].tri_description, + tri_title: data.triggers[i].tri_title, + tri_uid: data.triggers[i].tri_uid, + obj_title: data.triggers[i].tri_title, + obj_uid: data.triggers[i].tri_uid + }); + } + } + } + gridAfter = new PMUI.grid.GridPanel({ + behavior: 'dragdropsort', + filterable: false, + visibleHeaders: false, + data: data.triggers, + visibleFooter: false, + width: '96%', + visible: data.st_type === "ASSIGNMENT" ? false : true, + emptyMessage: 'No records found'.translate(), + style: { + cssClasses: ['mafe-gridPanel'] + }, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + columns: [ + { + title: '', + dataType: 'string', + alignmentCell: 'center', + columnData: 'st_position', + width: 20 + }, { + title: 'Before Output Document'.translate(), + dataType: 'string', + alignmentCell: 'left', + columnData: 'tri_title', + width: 360 + }, { + title: '', + dataType: 'button', + buttonLabel: function (row, data) { + return data.st_condition === '' ? 'Condition'.translate() : 'Condition *'.translate(); }, - { - iconClass: "", - id: 'copy', - title: "Copy Trigger".translate(), - height: '26px', - body: "", - style: { - cssProperties: { - "background-color": "#FDFDFD" - } - } + buttonStyle: {cssClasses: ['mafe-button-edit']}, + onButtonClick: function (row, grid) { + var data = row.getData(); + that.editCondition(grid.step_uid, data.tri_uid, data.st_type, row); } - ], - listeners: { - select: function (obj, event) { - - if (obj.id == "custom") { - openFormCustom("Create".translate()); - $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); - formEditTriggerCustom.showFooter(); - - var codeMirrorControl, cmControlCopyTrigger; - codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; - - if (codeMirrorControl != undefined) { - codeMirrorControl.setSize(580, 150); //CodeMirror Size - } - formEditTriggerCustom.getItems()[1].setHeight(170); - - formEditTriggerCustom.reset(); - - fields = formEditTriggerCustom.getItems()[0]; - fields.getItems()[0].setValue(""); - fields.getItems()[1].setValue(""); - fields.getItems()[2].setValue(""); - formEditTriggerCustom.getItems()[1].setValue(""); - formEditTriggerCustom.getItems()[1].controls[0].cm.setValue(""); - - } else if (obj.id == "copy") { - - getListProjects(); - openFormCopy(); - $($('#Code .CodeMirror.cm-s-default.CodeMirror-wrap')[1]).css({'border': '1px solid #c0c0c0'}); - $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); - - var cmControlCopyTrigger = formCopyTrigger.getFields()[4].controls[0].cm; - if (cmControlCopyTrigger != undefined) { - cmControlCopyTrigger.setSize(650, 140); //CodeMirror in formCopyTrigger Size - } - } else { - if (treeNewTrigger.getItems() == "" || treeNewTrigger.id != obj.id) { - var acItems = accordionNewTrigger.getItems(); - var accordionActualItem = accordionNewTrigger.getItem(obj.id); - - for (i = 0; i < acItems.length; i++) { - if (acItems[i].id == accordionActualItem.id) { - var positionActualAcItem = i - 2; - } - } - - treeNewTrigger.setItems(allTreesItems[positionActualAcItem]); - treeNewTrigger.setID(obj.id); - - accordionActualItem.setBody(treeNewTrigger); - treeNewTrigger.defineEvents(); - applyStyleTreePanel(treeNewTrigger, false); + }, { + title: '', + dataType: 'button', + buttonLabel: 'Edit'.translate(), + buttonStyle: {cssClasses: ['mafe-button-edit']}, + onButtonClick: function (row, grid) { + var data = row.getData(), + restClient; + restClient = new PMRestClient({ + endpoint: 'trigger/' + data.tri_uid, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + that.editTrigger(response.tri_webbot, response.tri_uid); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); } - } + }); + restClient.executeRestClient(); + } + }, { + title: '', + dataType: 'button', + buttonLabel: 'Remove'.translate(), + buttonStyle: {cssClasses: ['mafe-button-delete']}, + onButtonClick: function (row, grid) { + that.removeTrigger(row, grid); } } - }); - - updateCustom = function (dataToSend, triggerUid) { - var restClient = new PMRestClient({ - endpoint: "trigger/" + triggerUid, - typeRequest: 'update', - data: dataToSend, - functionSuccess: function (xhr, response) { - formEditTriggerCustom.setDirty(false); - getListTrigger(); - openListTriggers(); - $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); - }, - functionFailure: function (xhr, response) { - var msg = response.error.message; - var arrayMatch = []; - - if ((arrayMatch = /^[\w\s]+\:\s*(.*)$/i.exec(msg))) { - msg = arrayMatch[1]; - } - - PMDesigner.msgWinError(msg); - }, - messageSuccess: "Trigger updated successfully".translate(), - flashContainer: gridListTrigger - }); - restClient.executeRestClient(); - }; - - checkIfValuesAreEqual = function (initialData, finalData) { - if (typeof(initialData['tri_uid']) == "undefined" && finalData['tri_uid'] == '') { - if (finalData['tri_description'] != '' || finalData['tri_title'] != '' || finalData['tri_webbot'] != '') { - return false; - } - } - for (var key1 in initialData) { - for (var key2 in finalData) { - if (typeof(initialData[key1]) != "undefined" && - typeof(finalData[key2]) != "undefined" && - key1 == key2 && - initialData[key1] != finalData[key2] - ) { - return false; - } - } + ], + onDrop: function (container, draggableItem, index) { + var receiveData = draggableItem.getData(); + if (draggableItem instanceof PMUI.item.TreeNode) { + that.receiveTreeNodeItem(receiveData, this, index); + } else { + that.receiveRowItem(receiveData, this, index, draggableItem); } - return true; + that.updateIndexToGrid(this); + return false; + }, + onSort: function (container, item, index) { + var receiveData = item.getData(); + that.sortableRowHandler(receiveData, this, index); + that.updateIndexToGrid(this); } - - //Buttons Save and Cancel for the 'formEditTriggerCustom' and 'formEditTriggerWizard' - buttonSave = new PMUI.ui.Button({ - id: 'saveTriggerButton', - text: "Save".translate(), - handler: function (event) { - triggerOriginDataForUpdate = {}; - var formcustom = triggerWindow.getItems()[1], - formwizard = triggerWindow.getItems()[2], - formTriggerData, - restClient, - dataToSend, - formTriggerData, - inputFields, - message_window, - outputV, - outputFields, - inputV, - dataToSend, - flagEdit; - if (formcustom.isVisible() == true) { - valuesCustom=formcustom.getItems()[0]; - if (!formEditTriggerCustom.isValid( )) { - flagEdit = formEditTriggerCustom.visible; - } else { - flagEdit = formEditTriggerCustom.isValid(); - } - if (flagEdit) { - if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { - formTriggerData = getData2PMUI(formEditTriggerCustom.html); - } else { - formTriggerData = formEditTriggerCustom.getData(); - } - if (formTriggerData.title.trim() === "") { - return false; - } - dataToSend = { - tri_title: formTriggerData.title, - tri_description: formTriggerData.description, - tri_webbot: formTriggerData.code, - tri_param: "" - }; - - if (formTriggerData.uid === "") { - restClient = new PMRestClient({ - endpoint: 'trigger', - typeRequest: 'post', - data: dataToSend, - functionSuccess: function (xhr, response) { - formEditTriggerCustom.setDirty(false); - getListTrigger(); - formEditTriggerCustom.getItems()[0].getItems()[0].setValue(response.tri_uid); - openListTriggers(); - $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); - }, - functionFailure: function (xhr, response) { - var msg = response.error.message, - arrayMatch = []; - - if ((arrayMatch = /^[\w\s]+\:\s*(.*)$/i.exec(msg))) { - msg = arrayMatch[1]; - } - - PMDesigner.msgWinError(msg); - }, - messageSuccess: "New Trigger saved successfully".translate(), - flashContainer: gridListTrigger - }); - restClient.executeRestClient(); - } else { - if (formTriggerData.wizzard != "") { - if (formEditTriggerCustom.isDirty()) { - message_window = new PMUI.ui.MessageWindow({ - id: "wizzardToCustomTriggerWin", - windowMessageType: 'warning', - title: 'Triggers'.translate(), - width: 490, - message: 'Do you want to save the changes? This Trigger will be saved like a custom Trigger.'.translate(), - footerItems: [ - { - text: "No".translate(), - handler: function () { - message_window.close(); - openFormWizardEditMode(); - $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); - formEditTriggerCustom.reset(); - }, - buttonType: "error" - }, - { - text: "Yes".translate(), - handler: function () { - message_window.close(); - updateCustom(dataToSend, formTriggerData.uid); - }, - buttonType: "success" - } - ] - - }); - message_window.open(); - message_window.showFooter(); - } else { - openListTriggers(); - $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); - } - } else { - updateCustom(dataToSend, formTriggerData.uid); - } - } - } - } else if (formwizard.isVisible() == true) { - if (formEditTriggerWizard.isValid() || ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1))) { - if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { - formTriggerData = getData2PMUI(formEditTriggerWizard.html); - } else { - formTriggerData = formEditTriggerWizard.getData(); - } - - inputV = {}; - inputFields = formEditTriggerWizard.getItems()[3]; - for (i = 0; i < inputFields.getItems().length; i++) { - inputV[inputFields.getItems()[i].name] = formTriggerData[inputFields.getItems()[i].name]; - } - - outputV = {}; - outputFields = formEditTriggerWizard.getItems()[6]; - for (j = 0; j < outputFields.getItems().length; j++) { - outputV[outputFields.getItems()[j].name] = formTriggerData[outputFields.getItems()[j].name]; - } - - dataToSend = { - tri_title: formTriggerData.titleDetails, - tri_description: formTriggerData.descriptionDetails, - tri_type: "SCRIPT", - tri_params: { - input: inputV, - output: outputV - } - }; - - if (formTriggerData.uid === "") { - restClient = new PMRestClient({ - endpoint: 'trigger-wizard/' + formTriggerData.libName + '/' + formTriggerData.fnName, - typeRequest: 'post', - data: dataToSend, - functionSuccess: function (xhr, response) { - formEditTriggerWizard.setDirty(false); - getListTrigger(); - formEditTriggerWizard.getFields()[0].setValue(response.tri_uid); - openListTriggers(); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageSuccess: "New Trigger saved successfully".translate(), - flashContainer: gridListTrigger - }); - restClient.executeRestClient(); - } else { - restClient = new PMRestClient({ - endpoint: 'trigger-wizard/' + formTriggerData.libName + '/' + formTriggerData.fnName + '/' + formTriggerData.uid, - typeRequest: 'update', - data: dataToSend, - functionSuccess: function (xhr, response) { - formEditTriggerWizard.setDirty(false); - getListTrigger(); - openListTriggers(); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageSuccess: "Trigger updated successfully".translate(), - flashContainer: gridListTrigger - }); - restClient.executeRestClient(); - } - } - } - }, - buttonType: 'success' - }); - - //Buttons Save and Cancel for the 'formEditTriggerCustom' and 'formEditTriggerWizard' - copyButton = new PMUI.ui.Button({ - id: 'copyAndSaveButton', - text: "Copy Trigger".translate(), - buttonType: 'success', - handler: function (event) { - var data, - dataToSend, - restClient; - if (formCopyTrigger.isValid()) { - formCopyTrigger.setDirty(false); - - data = formCopyTrigger.getData(); - dataToSend = { - tri_title: getData2PMUI(formCopyTrigger.html).tri_title.trim(), - tri_description: data.tri_description, - tri_webbot: data.tri_webbot, - tri_param: "" - }; - restClient = new PMRestClient({ - endpoint: 'trigger', - typeRequest: 'post', - data: dataToSend, - functionSuccess: function (xhr, response) { - getListTrigger(); - formCopyTrigger.reset(); - openListTriggers(); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageSuccess: "New Trigger saved successfully".translate(), - flashContainer: gridListTrigger - }); - restClient.executeRestClient(); - } - } - }); - - //Buttons Apply for the Code Editor - applyButton = new PMUI.ui.Button({ - id: 'applyButton', - text: "Apply".translate(), - buttonType: 'success', - handler: function (event) { - - $("div.pmui-window-body.pmui-background").css('overflow', ''); - if (formEditCode.isValid()) { - var typeTitle = "Edit".translate(); - if (triggerWindow.getItems()[1].getData().uid == "") { - typeTitle = "Create".translate(); - } - openFormCustom(typeTitle); - formEditCode.setDirty(false); - - var editCode = formEditCode.getItems()[0].controls[0].cm; - editCodeValue = editCode.getValue(); - - var codeMirrorCustom = formEditTriggerCustom.getItems()[1].controls[0].cm; - - if (codeMirrorCustom != undefined) { - codeMirrorCustom.setSize(580, 150); //CodeMirror Size - } - codeMirrorCustom.setValue(editCodeValue); - formEditTriggerCustom.getItems()[1].setValue(editCodeValue); - - editCode.setValue(""); - editCodeValue = ""; - - formEditCode.getItems()[0].setValue(""); - } - } - }); - - //Button Edit Source Code (this is showed just when the Trigger Wizzard is opened in edition mode) - btnEditSourceCode = new PMUI.ui.Button({ - id: 'btnEditSourceCode', - text: "Edit Source Code".translate(), - buttonType: 'success', - handler: function (event) { - - var data = formEditTriggerWizard.getData(); - var fields; - openFormCustom("Edit".translate()); - formEditTriggerCustom.showFooter(); - - var codeMirrorControl; - codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; - - if (codeMirrorControl !== undefined) { - codeMirrorControl.setSize(650, 280); - } - formEditTriggerCustom.getItems()[1].setHeight(170); - - fields = formEditTriggerCustom.getItems()[0]; - fields.getItems()[0].setValue(data.uid); - fields.getItems()[1].setValue(data.titleDetails); - fields.getItems()[2].setValue(data.descriptionDetails); - fields.getItems()[3].setValue(data.webbot); - fields.getItems()[3].setVisible(false); - formEditTriggerCustom.getItems()[1].setValue(data.webbot); - - codeMirrorControl.setValue(data.webbot); - - formEditTriggerCustom.getItems()[1].setHeight(300); - fields.getItems()[1].setVisible(false); - fields.getItems()[2].setVisible(false); - formEditTriggerCustom.footer.getItems()[1].setVisible(false); - formEditTriggerCustom.footer.getItems()[0].style.addProperties({'margin-right': "10px"}); - formEditTriggerCustom.footer.style.addProperties({width: '880px'}); - codeMirrorControl.refresh(); - } - }); - - buttonCancel = new PMUI.ui.Button({ - id: 'cancelTriggerButton', - text: "Cancel".translate(), - buttonType: 'error', - handler: function (event) { - clickedClose = false; - isDirtyFormTrigger(); + }); + if (data.st_type !== "ROUTING" && data.st_type !== "ASSIGNMENT") { + gridAfter.st_type = 'AFTER'; + } else if (data.st_type == "ROUTING") { + gridAfter.st_type = "AFTER_ROUTING"; + } else { + gridAfter.st_type = "AFTER_ASSIGNMENT"; + } + gridAfter.step_uid = data.step_uid; + if (jQuery.isArray(data.triggers)) { + for (i = 0; i < data.triggers.length; i += 1) { + if (gridAfter.st_type === data.triggers[i].st_type) { + gridAfter.addDataItem({ + st_condition: data.triggers[i].st_condition, + st_position: data.triggers[i].st_position, + st_type: data.triggers[i].st_type, + tri_description: data.triggers[i].tri_description, + tri_title: data.triggers[i].tri_title, + tri_uid: data.triggers[i].tri_uid, + obj_title: data.triggers[i].tri_title, + obj_uid: data.triggers[i].tri_uid + }); } - }); - - //Form to Edit the Custom trigger (we used a Form because we need buttons to save the changes) - formEditTriggerCustom = new PMUI.form.Form({ - id: "formEditTriggerCustom", - border: true, - visibleHeader: false, - width: '900px', - height: "365px", - name: "formcustom", - title: "Custom Trigger".translate(), + } + } + var accordionItem = new PMUI.item.AccordionItem({ + id: 'id' + data.step_uid_obj, + dataStep: data, + closeable: true, + body: new PMUI.core.Panel({ + layout: 'vbox', items: [ + beforeTitle, + gridBefore, + afterTitle, + gridAfter + ] + }) + }); + if (this.stepsType[data.step_type_obj]) { + accordionItem.setTitle(data.step_position + ". " + data.obj_title + ' (' + this.stepsType[data.step_type_obj] + ')'); + this.stepsAssigned.insert(accordionItem); + } else { + accordionItem.setTitle((this.stepsAssignAccordion.items.getSize() + 1) + ". " + data.obj_title); + } + return accordionItem; +}; +/** + * styles that can not be handled with the library are customized PMUI + * @chainable + */ +stepsTask.prototype.customStyles = function () { + this.mainWindow.body.style.overflow = "hidden"; +}; +/** + * run the endpoint 'activity/{activity_id}/available-steps' to get + * dynaforms, output document, input Document and external, Unassigned or Availables + * @returns {Array} + */ +stepsTask.prototype.getStepAvailables = function () { + var resp = []; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ { - id: "panelDetailsCustom", - pmType: "panel", - layout: 'vbox', - fieldset: false, - height: '380px', - legend: "DETAILS".translate(), - items: [ - { - id: "uid", - pmType: "text", - label: "ID".translate(), - value: "", - name: "uid", - readOnly: true, - visible: false, - valueType: 'string' - }, - { - id: "title", - pmType: "text", - label: "Title".translate(), - value: "", - required: true, - name: "title", - valueType: 'string' - }, - { - id: "description", - pmType: "textarea", - rows: 70, - name: 'description', - label: "Description".translate(), - valueType: 'string', - style: {cssClasses: ['mafe-textarea-resize']} - }, - { - id: "wizzard", - pmType: "text", - label: "Wizzard".translate(), - value: "", - name: "wizzard", - readOnly: true, - visible: false, - valueType: 'string' - } - ] - } - ], - buttons: [ - { - text: "@@", - id: "selectPickerButton", - handler: function () { - var picker = new VariablePicker(); - picker.open({ - success: function (variable) { - var codeMirror = formEditTriggerCustom.getItems()[1].controls[0].cm; - var cursorPos = codeMirror.getCursor(); - codeMirror.replaceSelection(variable); - codeMirror.setCursor(cursorPos.line, cursorPos.ch); - } - }); - }, - style: { - cssProperties: { - "margin-left": '208px', - "background": "rgb(30, 145, 209)", - "border": "0px solid rgb(30, 145, 209)" - } - } - }, { - text: "Open Editor".translate(), - id: "openEditorButton", - handler: function () { - openFormEditCode(); - formEditCode.showFooter(); - - var codeMirrorCustom = formEditTriggerCustom.getItems()[1].controls[0].cm; - var value = codeMirrorCustom.getValue(); - - var codeMirrorCopy = formEditCode.getItems()[0].controls[0].cm; - - if (codeMirrorCopy != undefined) { - codeMirrorCopy.setSize(810, 315); //CodeMirror Size - $($('#codeEditor .CodeMirror.cm-s-default.CodeMirror-wrap')[0]).css({'border': '1px solid #c0c0c0'}); - - } - - formEditCode.getItems()[0].setHeight(325); - - codeMirrorCopy.setValue(value); - formEditCode.getItems()[0].setValue(value); - formEditCode.setDirty(false); - - $('#codeEditor .pmui-field-label').hide(); - $('#formEditCode').children().last().css({ - 'margin-top': '-352px', - 'border': '0px', - 'margin-right': '-15px' - }).find('a').css('padding', '10px 5px'); - $($('#codeEditor .CodeMirror.cm-s-default.CodeMirror-wrap')[0]).css({ - 'margin-left': '10px', - 'width': '850px', - 'height': '360px' - }); - $('#triggerWindow .pmui-window-body').css('overflow', 'hidden'); - codeMirrorCopy.refresh(); - }, - style: { - cssProperties: { - "margin-right": 2 - } - } + url: 'activity/' + PMDesigner.act_uid + '/available-steps', + method: 'GET' } ] - }); - cd = new PMCodeMirrorField({ - labelWidth: '23.8%' - }); - cd.setLabel("Code".translate()); - formEditTriggerCustom.addItem(cd); - formEditTriggerCustom.getItems()[1].setName('code'); - formEditTriggerCustom.getItems()[1].setID('code'); - - formEditCode = new PMUI.form.Form({ - id: "formEditCode", - border: true, - visibleHeader: false, - width: '925px', - name: "formeditcode", - title: "Editor".translate(), - items: [], - buttons: [ - { - text: "@@", - id: "selectPickerButton", - handler: function () { - var picker = new VariablePicker(); - picker.open({ - success: function (variable) { - var codeMirror = formEditCode.getItems()[0].controls[0].cm; - var cursorPos = codeMirror.getCursor(); - codeMirror.replaceSelection(variable); - codeMirror.setCursor(cursorPos.line, cursorPos.ch); - } - }); - }, - style: { - cssProperties: { - "margin-left": '229px', - "background": "rgb(45, 62, 80)", - "border": "1px solid rgb(45, 62, 80)" - } - } - } + }, + functionSuccess: function (xhr, response) { + if (jQuery.isArray(response)) { + resp = response[0] ? response[0].response : []; + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + return resp; +}; +/** + * run the endpoint 'activity/{activity_id}/available-steps' to get all Availables + * triggres and dynaforms Unassigned or Availables + * @returns {Array} + */ +stepsTask.prototype.getTreePanelData = function () { + var resp = []; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [{ + url: 'activity/' + PMDesigner.act_uid + '/available-steps', + method: 'GET' + }, { + url: 'triggers', + method: 'GET' + } ] + }, + functionSuccess: function (xhr, response) { + resp = response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + return resp; +} +/** + * this method loads the data to stepsAssignTree + * @param response, the answer is an array containing all the elements + * that will be loaded into the step stepsAssignTree + * @chainable + */ +stepsTask.prototype.loadTreePanelData = function (response) { + var that = this, + data, + i, + j, + type, + label, + items, + labelTrigger, + dataTree = [], + treeNode; + data = response[1].response; + labelTrigger = 'Trigger (s)'.translate(); + if (data.length === 0) { + dataTree.push({ + obj_title: labelTrigger, + items: [this.notItemConfig()] }); - editCode = new PMCodeMirrorField({ - labelWidth: '9%' + } else { + items = []; + for (i = 0; i < data.length; i += 1) { + items.push({ + obj_title: data[i]['tri_title'], + obj_type: data[i]['tri_type'], + obj_uid: data[i]['tri_uid'] + }); + } + dataTree.push({ + obj_title: labelTrigger, + items: items, + id: "TRIGGER" }); - editCode.setLabel("Code".translate()); - formEditCode.addItem(editCode); - formEditCode.getItems()[0].setName('codeEditor'); - formEditCode.getItems()[0].setID('codeEditor'); - - //Trigger Window - triggerWindow = new PMUI.ui.Window({ - id: "triggerWindow", - title: "Triggers".translate(), - width: DEFAULT_WINDOW_WIDTH, - height: DEFAULT_WINDOW_HEIGHT, - footerItems: [ - buttonCancel, - buttonSave, - btnEditSourceCode, - applyButton, - copyButton - ], - buttonPanelPosition: "bottom", - footerAling: "right", - onBeforeClose: function () { - clickedClose = true; - isDirtyFormTrigger(); + } + data = response[0].response; + type = this.groupType; + label = this.groupLabel; + items = []; + for (i = 0; i < type.length; i += 1) { + items = []; + for (j = 0; j < data.length; j += 1) { + if (type[i] === data[j].obj_type) { + items.push({ + obj_title: data[j]['obj_title'], + obj_type: data[j]['obj_type'], + obj_uid: data[j]['obj_uid'] + }); } - }); - - - triggerWindow.addItem(gridListTrigger); - triggerWindow.addItem(formEditTriggerCustom); - triggerWindow.addItem(formEditTriggerWizard); - triggerWindow.addItem(formCopyTrigger); - triggerWindow.addItem(formEditCode); - triggerWindow.addItem(accordionNewTrigger); - - if (typeof listTriggers !== "undefined") { - triggerWindow.open(); - codMirr.dom.labelTextContainer.style.width = "23.8%"; - codMirr.html.style.padding = "10px"; - formEditTriggerCustom.panel.html.style.padding = "10px 10px"; - $('#listTriggers .pmui-textcontrol').css({'margin-top': '5px', width: '250px'}); - applyStyleWindowForm(triggerWindow); - triggerWindow.hideFooter(); - openListTriggers(); - - gridListTrigger.dom.toolbar.appendChild(buttonNew.getHTML()); - buttonNew.defineEvents(); - - gridListTrigger.dom.toolbar.appendChild(buttonCopy.getHTML()); - buttonCopy.defineEvents(); - - gridListTrigger.dom.toolbar.appendChild(buttonWizard.getHTML()); - buttonWizard.defineEvents(); - - triggerWindow.defineEvents(); - gridListTrigger.sort('tri_title', 'asc'); - formEditTriggerCustom.panel.style.addProperties({'overflow': 'hidden'}); - - formcustom = triggerWindow.getItems()[1]; - valuesCustom=formcustom.getItems()[0]; } - }; - - PMDesigner.trigger.create = function () { - var codeMirrorControl, cmControlCopyTrigger; - openFormCustom("Create".translate()); - formEditTriggerCustom.getField("code").dom.labelTextContainer.style.width = "23.8%"; - $('.pmui-pmseparatorlinefield .pmui-field-label').css({display: 'none'}); - formEditTriggerCustom.showFooter(); - - codeMirrorControl = formEditTriggerCustom.getItems()[1].controls[0].cm; - formEditTriggerCustom.getItems()[1].html.style.padding = "10px"; - if (codeMirrorControl !== undefined) { - codeMirrorControl.setSize(580, 150); - codeMirrorControl.refresh(); - } - codeMirrorControl.refresh(); - formEditTriggerCustom.getItems()[1].setHeight(170); - formEditTriggerCustom.reset(); - }; -}()); + if (items.length === 0) { + dataTree.push({ + obj_title: label[i].translate(), + items: [this.notItemConfig()], + behavior: '', + id: type[i] + }); + } else { + dataTree.push({ + obj_title: label[i].translate(), + items: items, + behavior: 'drag', + id: type[i] + }); + } + } + this.stepsAssignTree.clearItems(); + for (i = 0; i < dataTree.length; i += 1) { + this.stepsAssignTree.addDataItem(dataTree[i]); + treeNode = this.stepsAssignTree.getItem(i); + treeNode.setID(dataTree[i].id); + this.updateIndexPosition(treeNode); + } + return this; +}; /** - * new stepTask module + * run the endpoint 'activity/{activity_id}/steps' and 'activity/{activity_id}/step/triggers' + * to get all triggres and dynaforms assigned + * @returns {Array} */ -var stepsTask = function (activity) { - this.mainWindow = null; - this.secondaryWindow = null; - this.stepsAssignTree = null; - this.mainContainer = null; - this.labelsPanel = null; - this.stepsMainContainer = null; - this.stepsAssignAccordion = null; - this.confirmWindow = null; - this.elementAccordionOpen = null; - this.groupType = null; - this.groupLabel = null; - this.stepsType = null; - this.stepsAssigned = null; - stepsTask.prototype.initialize.call(this, activity); +stepsTask.prototype.getAccordionData = function () { + var resp = [], + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'activity/' + PMDesigner.act_uid + '/steps', + method: 'GET' + }, { + url: 'activity/' + PMDesigner.act_uid + '/step/triggers', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + resp = response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems getting the Steps, please try again.'.translate() + }); + restClient.executeRestClient(); + return resp; }; /** - * initialization method steps settings, constants are created. - * components are created - * the data is loaded - * styles are customized - * It extends behaviors and events + * checks whether a trigger is already assigned in a grid + * @param grid, is instanceof PMUI.grid.Grid, in conducting the search + * @param tri_uid, search parameter in the rows of the grid + * @returns {boolean} */ -stepsTask.prototype.initialize = function () { - this.groupType = ['DYNAFORM', 'INPUT_DOCUMENT', 'OUTPUT_DOCUMENT', 'EXTERNAL']; - this.groupLabel = ['Dynaform (s)'.translate(), 'Input Document (s)'.translate(), 'OutPut Document (s)'.translate(), 'External (s)'.translate()]; - this.stepsType = { - "DYNAFORM": "Dynaform".translate(), - "INPUT_DOCUMENT": "Input Document".translate(), - "OUTPUT_DOCUMENT": "Output Document".translate(), - "EXTERNAL": "External".translate() - }; - this.stepsAssigned = new PMUI.util.ArrayList(); - this.elementAccordionOpen = new PMUI.util.ArrayList(); - this.createWidgets(); - this.mainWindow.addItem(this.mainContainer); - this.mainWindow.open(); - this.loadInitialData(); - this.customStyles(); - this.elementsAccordionOpenFixed(); - this.addEventSortableInAccordionElements(); - this.addEventSortableInTreePanelElements(); +stepsTask.prototype.isTriggerAssigned = function (grid, tri_uid) { + var data, i, exist = false; + data = grid.getData(); + if (grid && jQuery.isArray(data)) { + for (i = 0; i < data.length; i += 1) { + if (data[i].tri_uid === tri_uid) { + exist = true; + break; + } + } + } + return exist; }; /** - * the components are created PMUI UI - * - confirmWindow - * - mainWindow - * - labelsPanel - * - stepsAssignTree - * - stepsAssignAccordion - * - stepsMainContainer - * - mainContainer - * - secondaryWindow + * retorna el tipo de de step, para la ejecucion de "endpoint" + * @param st_type, this a step type, the accepted parameters are: + * - BEFORE_ASSIGNMENT + * - BEFORE_ROUTING + * - AFTER_ROUTING + * - BEFORE + * - AFTER + * @returns {string} */ -stepsTask.prototype.createWidgets = function () { - var that = this; - this.confirmWindow = new PMUI.ui.MessageWindow({ - id: 'confirmWindowDeleteAcceptedValue', - windowMessageType: 'warning', - width: 490, - bodyHeight: 'auto', - title: '', - message: '', - footerItems: [ - { - id: 'confirmWindow-footer-no', - text: 'No'.translate(), - visible: true, - buttonType: "error" - }, { - id: 'confirmWindow-footer-yes', - text: 'Yes'.translate(), - visible: true, - buttonType: "success" - } - ], - visibleFooter: true - }); - this.mainWindow = new PMUI.ui.Window({ - id: "stepsForTask", - title: "Steps for task".translate(), - height: DEFAULT_WINDOW_HEIGHT, - width: DEFAULT_WINDOW_WIDTH +stepsTask.prototype.getStepType = function (st_type) { + var value; + switch (st_type) { + case 'BEFORE_ASSIGNMENT': + value = 'before-assignment'; + break; + case 'BEFORE_ROUTING': + value = 'before-routing'; + break; + case 'AFTER_ROUTING': + value = 'after-routing'; + break; + case 'BEFORE': + value = 'before'; + break; + case 'AFTER': + value = 'after'; + break; + default: + value = ''; + break; + } + return value; +}; +/** + * This method is executed when editing a "trigger" in a row of the grid. + * secondary window opens with the current configuration of the trigger + * @param trigger, is the return value when is update 'trigger' action in the enpoint + * @param triggerID, is the id of the trigger to update + * @chainable + */ +stepsTask.prototype.editTrigger = function (trigger, triggerID) { + var codeMirror, + saveButton, + cancelButton, + criteriaButton, + that = this; + this.resetSecondaryWindow(); + codeMirror = new PMCodeMirror({ + id: "codeMirror" }); - this.labelsPanel = new PMUI.core.Panel({ - width: DEFAULT_WINDOW_WIDTH, - proportion: 0.08, - layout: "hbox", - items: [ - new PMUI.field.TextAnnotationField({ - text: 'Available Elements'.translate(), - text_Align: 'center', - proportion: 1.4 - }), - new PMUI.field.TextAnnotationField({ - text: 'Assigned Elements (Drop here)'.translate(), - text_Align: 'center', - proportion: 1.3 - }), - new PMUI.ui.Button({ - buttonType: "link", - "text": "Expand all".translate(), - id: "expand-button", - proportion: 0.6, - handler: function () { - var items, i, item, buttonAfected; - items = that.stepsAssignAccordion.getItems(); - buttonAfected = that.labelsPanel.getItem("collapse-button"); - buttonAfected.setDisabled(false); - this.setDisabled(true); - that.elementAccordionOpen.clear(); - for (i = 0; i < items.length; i += 1) { - item = items[i]; - item.expand(); - that.elementAccordionOpen.insert(item); - } + CodeMirror.commands.autocomplete = function (cm) { + CodeMirror.showHint(cm, CodeMirror.phpHint); + }; + codeMirror.setValue(trigger); + this.secondaryWindow.setWidth(DEFAULT_WINDOW_WIDTH); + this.secondaryWindow.setHeight(DEFAULT_WINDOW_HEIGHT); + this.secondaryWindow.setTitle("Trigger".translate()); + saveButton = this.secondaryWindow.footer.getItem("secondaryWindow-save"); + cancelButton = this.secondaryWindow.footer.getItem("secondaryWindow-cancel"); + criteriaButton = this.secondaryWindow.footer.getItem("secondaryWindow-criteria"); + if (saveButton) { + saveButton.setHandler(function () { + var restClient = new PMRestClient({ + endpoint: 'trigger/' + triggerID, + typeRequest: 'update', + data: { + tri_param: '', + tri_webbot: codeMirror.getValue() + }, + messageError: 'There are problems updating the trigger, please try again.'.translate(), + messageSuccess: 'Trigger updated correctly'.translate(), + flashContainer: that.mainWindow, + functionSuccess: function () { + that.secondaryWindow.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); } - }), - new PMUI.ui.Button({ - buttonType: "link", - "text": "Collapse all".translate(), - id: "collapse-button", - proportion: 0.7, - disabled: true, - handler: function () { - var items, i, item, buttonAfected; - buttonAfected = that.labelsPanel.getItem("expand-button"); - buttonAfected.setDisabled(false); - this.setDisabled(true); - items = that.stepsAssignAccordion.getItems(); - for (i = 0; i < items.length; i += 1) { - item = items[i]; - that.elementAccordionOpen.remove(item); - item.collapse(); - } + }); + restClient.executeRestClient(); + }); + } + if (cancelButton) { + cancelButton.setHandler(function () { + that.secondaryWindow.close(); + }); + } + if (criteriaButton) { + criteriaButton.setVisible(true); + criteriaButton.setHandler(function () { + var picker = new VariablePicker(); + picker.open({ + success: function (variable) { + var cursorPos, + codemirror; + codemirror = codeMirror.cm; + cursorPos = codemirror.getCursor(); + codemirror.replaceSelection(variable); + codemirror.setCursor(cursorPos.line, cursorPos.ch); } - }) - ] - }); - this.stepsAssignTree = new PMUI.panel.TreePanel({ - id: 'stepsAssignTree', - proportion: 0.5, - height: 475, - filterable: true, - autoBind: true, - filterPlaceholder: 'Search ...'.translate(), - emptyMessage: 'No records found'.translate(), - nodeDefaultSettings: { - labelDataBind: 'obj_title', - autoBind: true, - collapsed: false, - itemsDataBind: 'items', - childrenDefaultSettings: { - labelDataBind: 'obj_title', - autoBind: true - }, - behavior: 'drag' - }, - style: { - cssProperties: { - margin: '0px 0px 0px 0px', - float: 'left', - overflow: 'auto' - }, - cssClasses: ['mafe-border-panel'] - } - }); - this.stepsAssignAccordion = new PMUI.panel.AccordionPanel({ - id: 'stepsAssignAccordion', - multipleSelection: true, - hiddenTitle: true, - proportion: 1.5, - style: { - cssProperties: { - margin: '0px 0px 0px 0px' - }, - cssClasses: ['mafe-border-panel'] - }, - listeners: { - select: function (accordionItem, event) { - var buttonExpand, buttonCollapse, itemsAccod; - itemsAccod = that.stepsAssignAccordion.items; - if (accordionItem.collapsed) { - if (that.elementAccordionOpen.indexOf(accordionItem) > -1) { - that.elementAccordionOpen.remove(accordionItem); - } - } else { - if (that.elementAccordionOpen.indexOf(accordionItem) === -1) { - that.elementAccordionOpen.insert(accordionItem); - } - } - buttonCollapse = that.labelsPanel.getItem("collapse-button"); - buttonExpand = that.labelsPanel.getItem("expand-button"); - if (that.elementAccordionOpen.getSize() === 0) { - buttonExpand.setDisabled(false); - buttonCollapse.setDisabled(true); - } else if (that.elementAccordionOpen.getSize() === itemsAccod.getSize()) { - buttonExpand.setDisabled(true); - buttonCollapse.setDisabled(false); - } else { - buttonExpand.setDisabled(false); - buttonCollapse.setDisabled(false); - } - } - } - }); - this.stepsMainContainer = new PMUI.core.Panel({ - id: "stepsMainContainer", - width: DEFAULT_WINDOW_WIDTH, - height: DEFAULT_WINDOW_HEIGHT - 45, - layout: 'hbox', - height: 475, - items: [ - this.stepsAssignTree, - this.stepsAssignAccordion - ] - }); - this.mainContainer = new PMUI.core.Panel({ - id: "mainContainer", - width: DEFAULT_WINDOW_WIDTH, - height: DEFAULT_WINDOW_HEIGHT - 45, - layout: 'vbox', + }); + }); + } + this.secondaryWindow.open(); + this.secondaryWindow.addItem(codeMirror); + codeMirror.cm.setSize(this.secondaryWindow.getWidth(), 380); + $(".CodeMirror.cm-s-default.CodeMirror-wrap").after($ctrlSpaceMessage.css({ + "padding-left": "10px", + "margin": "3px 0px 0px 0px" + })); + $(".pmui-window-body").css("overflow", "hidden"); + codeMirror.cm.refresh(); +}; +/** + * edit the selected trigger condition + * @param stepID, It is the id of the step to upgrade + * @param triggerID, is the id of the trigger to update + * @param stepType, It is the kind of step to update + * @param row, PMUI.grid.GridPanelRow, is the row affected + */ +stepsTask.prototype.editCondition = function (stepID, triggerID, stepType, row) { + var saveButton, + cancelButton, + criteriaButton, + form, + dataRow, + that = this; + dataRow = row.getData(); + this.resetSecondaryWindow(); + this.secondaryWindow.setWidth(500); + this.secondaryWindow.setHeight(350); + this.secondaryWindow.setTitle('Condition Trigger'.translate()); + this.secondaryWindow.setTitle("Trigger".translate()); + form = new PMUI.form.Form({ + id: 'idFormEditCondition', + width: 500, + title: 'Condition Trigger'.translate(), + visibleHeader: false, items: [ - this.labelsPanel, - this.stepsMainContainer + new CriteriaField({ + id: 'st_condition', + pmType: 'textarea', + name: 'st_condition', + valueType: 'string', + label: 'Condition'.translate(), + placeholder: 'Insert a condition'.translate(), + rows: 150, + controlsWidth: 250, + renderType: 'textarea', + value: dataRow.st_condition + }) ] }); - this.secondaryWindow = new PMUI.ui.Window({ - visibleFooter: true, - title: 'Trigger'.translate(), - footerAlign: 'right', - footerItems: [ - { - text: "@@", - id: "secondaryWindow-criteria", - handler: function () { - }, - style: { - cssProperties: { - "background": "rgb(45, 62, 80)", - "border": "1px solid rgb(45, 62, 80)" - }, - cssClasses: ["mafe-button-condition-trigger"] - } - }, { - id: 'secondaryWindow-cancel', - text: 'Cancel'.translate(), - buttonType: 'error', - height: 31, - style: { - cssClasses: ["mafe-button-condition-trigger"] - }, - handler: function () { - } - }, { - id: 'secondaryWindow-save', - text: 'Save'.translate(), - buttonType: 'success', - height: 31, - style: { - cssClasses: ["mafe-button-condition-trigger"] + this.secondaryWindow.addItem(form); + saveButton = this.secondaryWindow.footer.getItem("secondaryWindow-save"); + cancelButton = this.secondaryWindow.footer.getItem("secondaryWindow-cancel"); + criteriaButton = this.secondaryWindow.footer.getItem("secondaryWindow-criteria"); + if (saveButton) { + saveButton.setHandler(function () { + var data, + restClient; + data = form.getData(); + data.st_type = stepType; + restClient = new PMRestClient({ + endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + ((typeof(stepID) != "undefined") ? stepID + "/" : "") + 'trigger/' + triggerID, + typeRequest: 'update', + data: data, + messageError: 'There are problems update the Step Trigger, please try again.'.translate(), + functionSuccess: function (xhr, response) { + dataRow.st_condition = data.st_condition; + row.setData(dataRow); }, - handler: function () { + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); } - } - ] - }); + }); + restClient.executeRestClient(); + that.secondaryWindow.close(); + }); + } + if (cancelButton) { + cancelButton.setHandler(function () { + that.secondaryWindow.close(); + }); + } + if (criteriaButton) { + criteriaButton.setVisible(false); + criteriaButton.handler = null; + } + this.secondaryWindow.open(); }; /** - * This method loads the initial data module steps,for the components: - * - stepsAssignTree - * - stepsAssignAccordion + * eliminates the elements of the secondary window + * @chainable */ -stepsTask.prototype.loadInitialData = function () { - this.loadTreePanelData(this.getTreePanelData()); - this.loadAccordionItems(this.getAccordionData()); +stepsTask.prototype.resetSecondaryWindow = function () { + var i, items; + if (this.secondaryWindow && this.secondaryWindow.items.getSize() > 0) { + items = this.secondaryWindow.items; + for (i = 0; i < items.getSize(); i += 1) { + this.secondaryWindow.removeItem(items.get(i)); + } + } }; /** - * This method loads the options to stepsAssignAccordion - * @param {Array} response An array where each element can be a {Element} object or a JSON object + * It establishes a PMUI.util.ArrayList that stores the + * elements of "stepsAssignAccordion" that are open + * @chainable */ -stepsTask.prototype.loadAccordionItems = function (response) { - var firstResp = [], - secondResp = [], - i, - item, - assigmentConfig, - firstRes = 0, - secondRes = 1; - if (jQuery.isArray(response) && response.length) { - if (typeof response[firstRes] === "object") { - firstResp = response[firstRes].response ? response[firstRes].response : []; - } - if (typeof response[secondRes] === "object") { - secondResp = response[secondRes].response ? response[secondRes].response : []; - } - } - if (firstResp.length) { - for (i = 0; i < firstResp.length; i += 1) { - item = this.createAccordionItem(firstResp[i], true, true); - this.stepsAssignAccordion.addItem(item); - item.dataItem = firstResp[i]; - this.customAccordionItemButtons(item.html, firstResp[i], item); +stepsTask.prototype.elementsAccordionOpenFixed = function () { + var i, + accordionItems; + if (this.stepsAssignAccordion) { + accordionItems = this.stepsAssignAccordion.getItems(); + if ($.isArray(accordionItems)) { + for (i = 0; i < accordionItems.length; i += 1) { + if (!accordionItems[i].collapsed) { + this.elementAccordionOpen.insert(accordionItems[i]); + } + } } } - assigmentConfig = { - step_type_obj: "Assignment".translate(), - triggers: secondResp, - st_type: "ASSIGNMENT", - obj_title: "Assignment".translate(), - step_uid_obj: "Assignment" - }; - item = this.createAccordionItem(assigmentConfig); - this.stepsAssignAccordion.addItem(item); - item.dataItem = assigmentConfig; - assigmentConfig = { - step_type_obj: "Routing".translate(), - triggers: secondResp, - obj_title: "Routing".translate(), - st_type: 'ROUTING', - step_uid_obj: "Routing" - }; - item = this.createAccordionItem(assigmentConfig); - this.stepsAssignAccordion.addItem(item); - item.dataItem = assigmentConfig; - this.stepsAssignAccordion.defineEvents(); }; /** - * This method creates an element for stepsAssignAccordion - * @param {data} It is an object with the settings to create the element - * @returns {PMUI.item.AccordionItem} + * It is an extension to add the "sortable" event "stepAssignAccordion". + * when a node "treePanel" is added to stop runs and is where you choose if it's a sort or aggregation. + * @chainable */ -stepsTask.prototype.createAccordionItem = function (data) { - var that = this, - gridBefore, - gridAfter, - beforeTitle, - afterTitle, - i, - textLabel; - if (this.stepsType[data.step_type_obj]) { - textLabel = this.stepsType[data.step_type_obj]; - } else { - textLabel = data.step_type_obj; - } - beforeTitle = new PMUI.field.TextAnnotationField({ - text: 'Before'.translate() + ' ' + textLabel, - proportion: 0.5, - text_Align: 'left' - }); - afterTitle = new PMUI.field.TextAnnotationField({ - text: 'After'.translate() + ' ' + textLabel, - proportion: 0.5, - text_Align: 'left', - visible: data.st_type === "ASSIGNMENT" ? false : true - }); - - gridBefore = new PMUI.grid.GridPanel({ - behavior: 'dragdropsort', - filterable: false, - visibleHeaders: false, - data: data.triggers, - st_type: 'BEFORE', - step_uid: data.step_uid, - visibleFooter: false, - width: '96%', - emptyMessage: 'No records found'.translate(), - style: { - cssClasses: ['mafe-gridPanel'] - }, - customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { - return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); - }, - columns: [ - { - title: '', - dataType: 'string', - alignmentCell: 'center', - columnData: "st_position", - width: 20 - }, { - title: 'Before Output Document'.translate(), - dataType: 'string', - alignmentCell: 'left', - columnData: 'tri_title', - width: 360 - }, { - title: '', - dataType: 'button', - buttonLabel: function (row, data) { - return data.st_condition === '' ? 'Condition'.translate() : 'Condition *'.translate(); - }, - buttonStyle: {cssClasses: ['mafe-button-edit']}, - onButtonClick: function (row, grid) { - var data = row.getData(); - that.editCondition(grid.step_uid, data.tri_uid, data.st_type, row); +stepsTask.prototype.addEventSortableInAccordionElements = function () { + var tagContainer, + newIndex, + index, + treeNodeObject, + treeNodeData, + that = this; + if (this.stepsAssignAccordion && this.stepsAssignAccordion.html) { + tagContainer = this.stepsAssignAccordion.body; + $(tagContainer).sortable({ + items: '>div:not(#idAssignment,#idRouting)', + placeholder: 'steps-placeholder', + receive: function (event, ui) { + var item = ui ? ui.item : null; + if (item && item instanceof jQuery && item.length) { + treeNodeObject = PMUI.getPMUIObject(item.get(0)); + treeNodeData = treeNodeObject.getData(); } - }, { - title: '', - dataType: 'button', - buttonLabel: 'Edit'.translate(), - buttonStyle: {cssClasses: ['mafe-button-edit']}, - onButtonClick: function (row, grid) { - var data = row.getData(), - restClient; - restClient = new PMRestClient({ - endpoint: 'trigger/' + data.tri_uid, - typeRequest: 'get', - functionSuccess: function (xhr, response) { - that.editTrigger(response.tri_webbot, response.tri_uid); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); + }, + stop: function (event, ui) { + var itemClone = ui ? ui.item : null, + accordionItems, + accordionItem, + dataEdited, + restClientMultipart, + restClient; + var newIndex = ui.item.index(); + accordionItems = that.stepsAssignAccordion.getItems(); + if (itemClone && itemClone instanceof jQuery && itemClone.length) { + if (treeNodeObject) { + itemClone.remove(); + if (newIndex + 1 > accordionItems.length) { + newIndex = that.stepsAssigned.getSize(); } - }); - restClient.executeRestClient(); - } - }, { - title: '', - dataType: 'button', - buttonLabel: 'Remove'.translate(), - buttonStyle: {cssClasses: ['mafe-button-delete']}, - onButtonClick: function (row, grid) { - that.removeTrigger(row, grid); + restClient = new PMRestClient({ + endpoint: 'activity/' + PMDesigner.act_uid + '/step', + typeRequest: 'post', + data: { + step_type_obj: treeNodeData.obj_type, + step_uid_obj: treeNodeData.obj_uid, + step_condition: '', + step_position: newIndex + 1, + step_mode: 'EDIT' + }, + functionSuccess: function (xhr, response) { + var item, buttonAfected, treeNode; + that.stepsAssignTree.removeItem(treeNodeObject); + treeNode = that.stepsAssignTree.items.find("id", response.step_type_obj); + if (treeNode.items.getSize() === 0) { + treeNode.addDataItem(that.notItemConfig()); + } + response.obj_description = ''; + response.obj_title = treeNodeData.obj_title; + response.triggers = []; + item = that.createAccordionItem(response, true, true); + item.dataItem = response; + if (that.stepsAssignAccordion.items.getSize() === 2) { + that.stepsAssignAccordion.addItem(item, 0); + } else { + that.stepsAssignAccordion.addItem(item, newIndex); + } + that.stepsAssignAccordion.defineEvents(); + that.customAccordionItemButtons(item.html, response, item); + that.updateItemIndexToAccordion(); + that.addEventSortableInAccordionElements(); + that.addEventSortableInTreePanelElements(); + buttonAfected = that.labelsPanel.getItem("expand-button"); + buttonAfected.setDisabled(false); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'An unexpected error while assigning the step, please try again later.'.translate(), + messageSuccess: 'Step assigned successfully.'.translate(), + flashContainer: that.stepsAssignAccordion.getParent() + }); + restClient.executeRestClient(); + } else { + accordionItem = PMUI.getPMUIObject(ui.item.get(0)); + index = that.stepsAssignAccordion.items.indexOf(accordionItem); + if (newIndex !== index) { + that.stepsAssignAccordion.items.remove(accordionItem); + that.stepsAssignAccordion.items.insertAt(accordionItem, newIndex); + dataEdited = { + step_position: newIndex + 1, + step_uid: accordionItem.dataItem.step_uid, + step_type_obj: accordionItem.dataItem.step_type_obj, + step_uid_obj: accordionItem.dataItem.step_uid_obj + }; + restClientMultipart = new PMRestClient({ + endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + accordionItem.dataItem.step_uid, + typeRequest: 'update', + data: dataEdited, + functionSuccess: function (xhr, response) { + that.updateItemIndexToAccordion(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'An unexpected error while editing the step, please try again later.'.translate(), + messageSuccess: 'Step editing successfully.'.translate(), + flashContainer: this.mainWindow + }); + restClientMultipart.executeRestClient(); + } + } } + }, + start: function (e, ui) { + newIndex = ui.item.index(); } - ], - onDrop: function (container, draggableItem, index) { - var receiveData = draggableItem.getData(); - if (draggableItem instanceof PMUI.item.TreeNode) { - that.receiveTreeNodeItem(receiveData, this, index); - } else { - that.receiveRowItem(receiveData, this, index, draggableItem); - } - that.updateIndexToGrid(this); - return false; - }, - onSort: function (container, item, index) { - var receiveData = item.getData(); - that.sortableRowHandler(receiveData, this, index); - that.updateIndexToGrid(this); - } - }); - if (data.st_type !== "ROUTING" && data.st_type !== "ASSIGNMENT") { - gridBefore.st_type = 'BEFORE'; - } else if (data.st_type === "ROUTING") { - gridBefore.st_type = "BEFORE_ROUTING"; - } else { - gridBefore.st_type = "BEFORE_ASSIGNMENT"; - } - gridBefore.step_uid = data.step_uid; - gridBefore.clearItems(); - if (jQuery.isArray(data.triggers)) { - for (i = 0; i < data.triggers.length; i += 1) { - if (gridBefore.st_type === data.triggers[i].st_type) { - gridBefore.addDataItem({ - st_condition: data.triggers[i].st_condition, - st_position: data.triggers[i].st_position, - st_type: data.triggers[i].st_type, - tri_description: data.triggers[i].tri_description, - tri_title: data.triggers[i].tri_title, - tri_uid: data.triggers[i].tri_uid, - obj_title: data.triggers[i].tri_title, - obj_uid: data.triggers[i].tri_uid - }); - } - } + }); } - gridAfter = new PMUI.grid.GridPanel({ - behavior: 'dragdropsort', - filterable: false, - visibleHeaders: false, - data: data.triggers, - visibleFooter: false, - width: '96%', - visible: data.st_type === "ASSIGNMENT" ? false : true, - emptyMessage: 'No records found'.translate(), - style: { - cssClasses: ['mafe-gridPanel'] - }, - customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { - return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); - }, - columns: [ - { - title: '', - dataType: 'string', - alignmentCell: 'center', - columnData: 'st_position', - width: 20 - }, { - title: 'Before Output Document'.translate(), - dataType: 'string', - alignmentCell: 'left', - columnData: 'tri_title', - width: 360 - }, { - title: '', - dataType: 'button', - buttonLabel: function (row, data) { - return data.st_condition === '' ? 'Condition'.translate() : 'Condition *'.translate(); +}; +/** + * It is an extension to add the "sortable" event "stepsAssignTree". + * when choosing a node treePanel and you want to add to the accordion or the grid + * @chainable + */ +stepsTask.prototype.addEventSortableInTreePanelElements = function () { + var items = this.stepsAssignTree.getItems(), + connect, + i, + sw, + that = this, + nodeItems; + for (i = 0; i < items.length; i += 1) { + nodeItems = items[i].getItems(); + if (nodeItems.length && nodeItems[0].getData().obj_type) { + sw = items[i].getItems()[0].getData().obj_type === "SCRIPT"; + connect = sw ? ".pmui-gridpanel-tbody" : ".pmui-accordion-panel-body"; + $(items[i].html).find('ul').find('>li').draggable({ + appendTo: document.body, + revert: "invalid", + helper: "clone", + cursor: "move", + zIndex: 1000, + connectToSortable: connect, + start: function (e) { + var i, nodeTag, node, nodeData, accordionItems, item; + nodeTag = e.target; + node = PMUI.getPMUIObject(nodeTag); + nodeData = node.getData(); + accordionItems = that.stepsAssignAccordion.getItems(); + $(that.stepsAssignAccordion.body).hide(); + if (nodeData.obj_type !== "SCRIPT") { + for (i = 0; i < accordionItems.length; i += 1) { + item = accordionItems[i]; + item.collapse(); + } + } + $(that.stepsAssignAccordion.body).show(); }, - buttonStyle: {cssClasses: ['mafe-button-edit']}, - onButtonClick: function (row, grid) { - var data = row.getData(); - that.editCondition(grid.step_uid, data.tri_uid, data.st_type, row); - } - }, { - title: '', - dataType: 'button', - buttonLabel: 'Edit'.translate(), - buttonStyle: {cssClasses: ['mafe-button-edit']}, - onButtonClick: function (row, grid) { - var data = row.getData(), - restClient; - restClient = new PMRestClient({ - endpoint: 'trigger/' + data.tri_uid, - typeRequest: 'get', - functionSuccess: function (xhr, response) { - that.editTrigger(response.tri_webbot, response.tri_uid); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); + stop: function () { + var i = 0, max; + if (that.elementAccordionOpen) { + max = that.elementAccordionOpen.getSize(); + for (i = 0; i < max; i += 1) { + that.elementAccordionOpen.get(i).expand(); } - }); - restClient.executeRestClient(); - } - }, { - title: '', - dataType: 'button', - buttonLabel: 'Remove'.translate(), - buttonStyle: {cssClasses: ['mafe-button-delete']}, - onButtonClick: function (row, grid) { - that.removeTrigger(row, grid); + } } - } - ], - onDrop: function (container, draggableItem, index) { - var receiveData = draggableItem.getData(); - if (draggableItem instanceof PMUI.item.TreeNode) { - that.receiveTreeNodeItem(receiveData, this, index); - } else { - that.receiveRowItem(receiveData, this, index, draggableItem); - } - that.updateIndexToGrid(this); - return false; - }, - onSort: function (container, item, index) { - var receiveData = item.getData(); - that.sortableRowHandler(receiveData, this, index); - that.updateIndexToGrid(this); - } - }); - if (data.st_type !== "ROUTING" && data.st_type !== "ASSIGNMENT") { - gridAfter.st_type = 'AFTER'; - } else if (data.st_type == "ROUTING") { - gridAfter.st_type = "AFTER_ROUTING"; - } else { - gridAfter.st_type = "AFTER_ASSIGNMENT"; - } - gridAfter.step_uid = data.step_uid; - if (jQuery.isArray(data.triggers)) { - for (i = 0; i < data.triggers.length; i += 1) { - if (gridAfter.st_type === data.triggers[i].st_type) { - gridAfter.addDataItem({ - st_condition: data.triggers[i].st_condition, - st_position: data.triggers[i].st_position, - st_type: data.triggers[i].st_type, - tri_description: data.triggers[i].tri_description, - tri_title: data.triggers[i].tri_title, - tri_uid: data.triggers[i].tri_uid, - obj_title: data.triggers[i].tri_title, - obj_uid: data.triggers[i].tri_uid - }); - } + }); + } else { + $(nodeItems[0].html).draggable("disable"); } } - var accordionItem = new PMUI.item.AccordionItem({ - id: 'id' + data.step_uid_obj, - dataStep: data, - closeable: true, - body: new PMUI.core.Panel({ - layout: 'vbox', - items: [ - beforeTitle, - gridBefore, - afterTitle, - gridAfter - ] - }) - }); - if (this.stepsType[data.step_type_obj]) { - accordionItem.setTitle(data.step_position + ". " + data.obj_title + ' (' + this.stepsType[data.step_type_obj] + ')'); - this.stepsAssigned.insert(accordionItem); - } else { - accordionItem.setTitle((this.stepsAssignAccordion.items.getSize() + 1) + ". " + data.obj_title); - } - return accordionItem; -}; -/** - * styles that can not be handled with the library are customized PMUI - * @chainable - */ -stepsTask.prototype.customStyles = function () { - this.mainWindow.body.style.overflow = "hidden"; }; /** - * run the endpoint 'activity/{activity_id}/available-steps' to get - * dynaforms, output document, input Document and external, Unassigned or Availables - * @returns {Array} + * add custom buttons on the head of an element of stepsAssignAccordion + * are three buttons + * properties + * edit + * remove + * @param html, is the html of the header accordion item + * @param step, the data of the step selected */ -stepsTask.prototype.getStepAvailables = function () { - var resp = []; - restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - calls: [ - { - url: 'activity/' + PMDesigner.act_uid + '/available-steps', - method: 'GET' - } - ] - }, - functionSuccess: function (xhr, response) { - if (jQuery.isArray(response)) { - resp = response[0] ? response[0].response : []; - } - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } - }); - restClient.executeRestClient(); - return resp; +stepsTask.prototype.customAccordionItemButtons = function (html, step, accordionItem) { + var propertiesStep, + editStep, + removeStep, + $html, + containerButtons, + that = this, + title; + if (html) { + $html = jQuery(html.getElementsByClassName("pmui-accordion-item-header")); + title = step.obj_title + ' (' + step.step_type_obj + ')'; + $html.find(".pmui-accordion-item-title").get(0).title = title; + containerButtons = $('
'); + containerButtons.addClass("propertiesTask-accordionItem"); + propertiesStep = $('' + 'Properties'.translate() + ''); + propertiesStep.addClass("mafe-button-edit propertiesTask-accordionButton"); + editStep = $('' + 'Edit'.translate() + ''); + editStep.addClass("mafe-button-edit propertiesTask-accordionButton"); + removeStep = $('' + 'Remove'.translate() + ''); + removeStep.addClass("mafe-button-delete propertiesTask-accordionButton"); + + propertiesStep.click(function (e) { + e.preventDefault(); + e.stopPropagation(); + that.propertiesStepShow(step); + return false; + }); + + editStep.click(function (e) { + e.preventDefault(); + e.stopPropagation(); + that.editStepShow(step, accordionItem); + return false; + }); + + removeStep.click(function (e) { + e.preventDefault(); + e.stopPropagation(); + that.removeStepShow(step); + return false; + }); + containerButtons.append(propertiesStep); + containerButtons.append(editStep); + containerButtons.append(removeStep); + $html.append(containerButtons); + } }; /** - * run the endpoint 'activity/{activity_id}/available-steps' to get all Availables - * triggres and dynaforms Unassigned or Availables - * @returns {Array} + * opens the properties of the selected step with the current settings + * @param step, is the data of selected step + * @chainable */ -stepsTask.prototype.getTreePanelData = function () { - var resp = []; - restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - calls: [{ - url: 'activity/' + PMDesigner.act_uid + '/available-steps', - method: 'GET' - }, { - url: 'triggers', - method: 'GET' - } - ] - }, +stepsTask.prototype.propertiesStepShow = function (step) { + var form, + saveButton, + cancelButton, + criteriaButton, + that = this; + this.resetSecondaryWindow(); + this.secondaryWindow.setWidth(520); + this.secondaryWindow.setHeight(370); + this.secondaryWindow.setTitle('Step Properties'.translate()); + form = new PMUI.form.Form({ + id: 'stepsEditCondition', + width: 500, + title: 'Condition Trigger'.translate(), + visibleHeader: false, + items: [ + { + id: 'step_mode', + pmType: 'radio', + label: 'Mode'.translate(), + value: '', + visible: step.step_type_obj === "DYNAFORM" ? true : false, + name: 'step_mode', + options: [ + { + id: 'modeEdit', + label: 'Edit'.translate(), + value: 'EDIT', + selected: true + }, { + id: 'modeView', + label: 'View'.translate(), + value: 'VIEW' + } + ] + }, + new CriteriaField({ + id: 'step_condition', + pmType: 'textarea', + name: 'step_condition', + valueType: 'string', + label: 'Condition'.translate(), + placeholder: 'Insert a condition'.translate(), + rows: 150, + controlsWidth: 250, + renderType: 'textarea' + }) + ] + }); + this.secondaryWindow.addItem(form); + + var restClient = new PMRestClient({ + endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + step.step_uid, + typeRequest: 'get', functionSuccess: function (xhr, response) { - resp = response; + form.getField('step_mode').setValue(response.step_mode); + form.getField('step_condition').setValue(response.step_condition); }, functionFailure: function (xhr, response) { PMDesigner.msgWinError(response.error.message); } }); restClient.executeRestClient(); - return resp; -} -/** - * this method loads the data to stepsAssignTree - * @param response, the answer is an array containing all the elements - * that will be loaded into the step stepsAssignTree - * @chainable - */ -stepsTask.prototype.loadTreePanelData = function (response) { - var that = this, - data, - i, - j, - type, - label, - items, - labelTrigger, - dataTree = [], - treeNode; - data = response[1].response; - labelTrigger = 'Trigger (s)'.translate(); - if (data.length === 0) { - dataTree.push({ - obj_title: labelTrigger, - items: [this.notItemConfig()] - }); - } else { - items = []; - for (i = 0; i < data.length; i += 1) { - items.push({ - obj_title: data[i]['tri_title'], - obj_type: data[i]['tri_type'], - obj_uid: data[i]['tri_uid'] - }); - } - dataTree.push({ - obj_title: labelTrigger, - items: items, - id: "TRIGGER" - }); - } - data = response[0].response; - type = this.groupType; - label = this.groupLabel; - items = []; - for (i = 0; i < type.length; i += 1) { - items = []; - for (j = 0; j < data.length; j += 1) { - if (type[i] === data[j].obj_type) { - items.push({ - obj_title: data[j]['obj_title'], - obj_type: data[j]['obj_type'], - obj_uid: data[j]['obj_uid'] + saveButton = this.secondaryWindow.footer.getItem("secondaryWindow-save"); + cancelButton = this.secondaryWindow.footer.getItem("secondaryWindow-cancel"); + criteriaButton = this.secondaryWindow.footer.getItem("secondaryWindow-criteria"); + if (saveButton) { + saveButton.setHandler(function () { + var restClient; + if (form.isValid()) { + restClient = new PMRestClient({ + endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + step.step_uid, + typeRequest: 'update', + data: form.getData(), + functionSuccess: function () { + that.secondaryWindow.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems update the Step Trigger, please try again.'.translate() }); + restClient.executeRestClient(); } - } - if (items.length === 0) { - dataTree.push({ - obj_title: label[i].translate(), - items: [this.notItemConfig()], - behavior: '', - id: type[i] - }); - } else { - dataTree.push({ - obj_title: label[i].translate(), - items: items, - behavior: 'drag', - id: type[i] - }); - } - } - this.stepsAssignTree.clearItems(); - for (i = 0; i < dataTree.length; i += 1) { - this.stepsAssignTree.addDataItem(dataTree[i]); - treeNode = this.stepsAssignTree.getItem(i); - treeNode.setID(dataTree[i].id); - this.updateIndexPosition(treeNode); + }); } - return this; -}; -/** - * run the endpoint 'activity/{activity_id}/steps' and 'activity/{activity_id}/step/triggers' - * to get all triggres and dynaforms assigned - * @returns {Array} - */ -stepsTask.prototype.getAccordionData = function () { - var resp = [], - restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - calls: [ - { - url: 'activity/' + PMDesigner.act_uid + '/steps', - method: 'GET' - }, { - url: 'activity/' + PMDesigner.act_uid + '/step/triggers', - method: 'GET' - } - ] - }, - functionSuccess: function (xhr, response) { - resp = response; - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: 'There are problems getting the Steps, please try again.'.translate() + if (cancelButton) { + cancelButton.setHandler(function () { + that.secondaryWindow.close(); }); - restClient.executeRestClient(); - return resp; -}; -/** - * checks whether a trigger is already assigned in a grid - * @param grid, is instanceof PMUI.grid.Grid, in conducting the search - * @param tri_uid, search parameter in the rows of the grid - * @returns {boolean} - */ -stepsTask.prototype.isTriggerAssigned = function (grid, tri_uid) { - var data, i, exist = false; - data = grid.getData(); - if (grid && jQuery.isArray(data)) { - for (i = 0; i < data.length; i += 1) { - if (data[i].tri_uid === tri_uid) { - exist = true; - break; - } - } } - return exist; -}; -/** - * retorna el tipo de de step, para la ejecucion de "endpoint" - * @param st_type, this a step type, the accepted parameters are: - * - BEFORE_ASSIGNMENT - * - BEFORE_ROUTING - * - AFTER_ROUTING - * - BEFORE - * - AFTER - * @returns {string} - */ -stepsTask.prototype.getStepType = function (st_type) { - var value; - switch (st_type) { - case 'BEFORE_ASSIGNMENT': - value = 'before-assignment'; - break; - case 'BEFORE_ROUTING': - value = 'before-routing'; - break; - case 'AFTER_ROUTING': - value = 'after-routing'; - break; - case 'BEFORE': - value = 'before'; - break; - case 'AFTER': - value = 'after'; - break; - default: - value = ''; - break; + if (criteriaButton) { + criteriaButton.handler = null; + criteriaButton.setVisible(false); } - return value; + this.secondaryWindow.open(); }; /** - * This method is executed when editing a "trigger" in a row of the grid. - * secondary window opens with the current configuration of the trigger - * @param trigger, is the return value when is update 'trigger' action in the enpoint - * @param triggerID, is the id of the trigger to update + * opens the step of the selected step with the current settings + * @param step, is the data of selected step * @chainable */ -stepsTask.prototype.editTrigger = function (trigger, triggerID) { - var codeMirror, - saveButton, - cancelButton, - criteriaButton, - that = this; - this.resetSecondaryWindow(); - codeMirror = new PMCodeMirror({ - id: "codeMirror" - }); - CodeMirror.commands.autocomplete = function (cm) { - CodeMirror.showHint(cm, CodeMirror.phpHint); - }; - codeMirror.setValue(trigger); - this.secondaryWindow.setWidth(DEFAULT_WINDOW_WIDTH); - this.secondaryWindow.setHeight(DEFAULT_WINDOW_HEIGHT); - this.secondaryWindow.setTitle("Trigger".translate()); - saveButton = this.secondaryWindow.footer.getItem("secondaryWindow-save"); - cancelButton = this.secondaryWindow.footer.getItem("secondaryWindow-cancel"); - criteriaButton = this.secondaryWindow.footer.getItem("secondaryWindow-criteria"); - if (saveButton) { - saveButton.setHandler(function () { - var restClient = new PMRestClient({ - endpoint: 'trigger/' + triggerID, - typeRequest: 'update', - data: { - tri_param: '', - tri_webbot: codeMirror.getValue() - }, - messageError: 'There are problems updating the trigger, please try again.'.translate(), - messageSuccess: 'Trigger updated correctly'.translate(), - flashContainer: that.mainWindow, - functionSuccess: function () { - that.secondaryWindow.close(); +stepsTask.prototype.editStepShow = function (step, accordioItem) { + var inputDocument, + that = this; + switch (step.step_type_obj) { + case 'DYNAFORM': + var restProxy = new PMRestClient({ + endpoint: 'dynaform/' + step.step_uid_obj, + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var old = PMUI.activeCanvas, + formDesigner; + PMUI.activeCanvas = false; + formDesigner = PMDesigner.dynaformDesigner(response); + formDesigner.onHide = function () { + var assignedDynaform, + i, + data, + title; + assignedDynaform = that.getStepsAssignedByCriteria("DYNAFORM"); + if (jQuery.isArray(assignedDynaform)) { + for (i = 0; i < assignedDynaform.length; i += 1) { + data = assignedDynaform[i]; + if (typeof data === "object") { + if (data.step_uid === step.step_uid) { + title = data.step_position + ". " + data.obj_title; + title = title + ' (' + that.stepsType["DYNAFORM"] + ')'; + accordioItem.setTitle(title); + accordioItem.dataItem = data; + } + } + } + } + PMUI.activeCanvas = old; + }; }, functionFailure: function (xhr, response) { PMDesigner.msgWinError(response.error.message); } }); - restClient.executeRestClient(); - }); - } - if (cancelButton) { - cancelButton.setHandler(function () { - that.secondaryWindow.close(); - }); - } - if (criteriaButton) { - criteriaButton.setVisible(true); - criteriaButton.setHandler(function () { - var picker = new VariablePicker(); - picker.open({ - success: function (variable) { - var cursorPos, - codemirror; - codemirror = codeMirror.cm; - cursorPos = codemirror.getCursor(); - codemirror.replaceSelection(variable); - codemirror.setCursor(cursorPos.line, cursorPos.ch); + restProxy.executeRestClient(); + break; + case 'OUTPUT_DOCUMENT': + PMDesigner.output(); + PMDesigner.output.showTiny(step.step_uid_obj); + break; + case 'INPUT_DOCUMENT': + inputDocument = new InputDocument({ + onUpdateInputDocumentHandler: function (data, inputDoc) { + var position, title; + position = accordioItem.dataItem.step_position; + title = position + ". " + data.inp_doc_title; + title = title + ' (' + that.stepsType["INPUT_DOCUMENT"] + ')'; + accordioItem.dataItem.obj_title = data.inp_doc_title; + accordioItem.setTitle(title); + inputDoc.winMainInputDocument.close(); } }); - }); + inputDocument.build(); + inputDocument.openFormInMainWindow(); + inputDocument.inputDocumentFormGetProxy(step.step_uid_obj); + break; } - this.secondaryWindow.open(); - this.secondaryWindow.addItem(codeMirror); - codeMirror.cm.setSize(this.secondaryWindow.getWidth(), 380); - $(".CodeMirror.cm-s-default.CodeMirror-wrap").after($ctrlSpaceMessage.css({ - "padding-left": "10px", - "margin": "3px 0px 0px 0px" - })); - $(".pmui-window-body").css("overflow", "hidden"); - codeMirror.cm.refresh(); }; /** - * edit the selected trigger condition - * @param stepID, It is the id of the step to upgrade - * @param triggerID, is the id of the trigger to update - * @param stepType, It is the kind of step to update - * @param row, PMUI.grid.GridPanelRow, is the row affected + * the window opens for confirmation of the removal step + * @param step, the current step to remove + * @chainable */ -stepsTask.prototype.editCondition = function (stepID, triggerID, stepType, row) { - var saveButton, - cancelButton, - criteriaButton, - form, - dataRow, - that = this; - dataRow = row.getData(); - this.resetSecondaryWindow(); - this.secondaryWindow.setWidth(500); - this.secondaryWindow.setHeight(350); - this.secondaryWindow.setTitle('Condition Trigger'.translate()); - this.secondaryWindow.setTitle("Trigger".translate()); - form = new PMUI.form.Form({ - id: 'idFormEditCondition', - width: 500, - title: 'Condition Trigger'.translate(), - visibleHeader: false, - items: [ - new CriteriaField({ - id: 'st_condition', - pmType: 'textarea', - name: 'st_condition', - valueType: 'string', - label: 'Condition'.translate(), - placeholder: 'Insert a condition'.translate(), - rows: 150, - controlsWidth: 250, - renderType: 'textarea', - value: dataRow.st_condition - }) - ] - }); - this.secondaryWindow.addItem(form); - saveButton = this.secondaryWindow.footer.getItem("secondaryWindow-save"); - cancelButton = this.secondaryWindow.footer.getItem("secondaryWindow-cancel"); - criteriaButton = this.secondaryWindow.footer.getItem("secondaryWindow-criteria"); - if (saveButton) { - saveButton.setHandler(function () { - var data, - restClient; - data = form.getData(); - data.st_type = stepType; +stepsTask.prototype.removeStepShow = function (step) { + var title, + yesButton, + noButton, + that = this, + restClient; + if (this.stepsType[step.step_type_obj] !== undefined) { + title = "Step {0} ( {1} )".translate([step.obj_title, this.stepsType[step.step_type_obj]]); + this.confirmWindow.setTitle(title); + } else { + this.confirmWindow.setTitle("Step " + step.step_type_obj.capitalize()); + } + this.confirmWindow.setMessage("Do you want to remove the step '{0}'?".translate([step.obj_title])); + yesButton = this.confirmWindow.footer.getItem("confirmWindow-footer-yes"); + noButton = this.confirmWindow.footer.getItem("confirmWindow-footer-no"); + if (yesButton) { + yesButton.setHandler(function () { restClient = new PMRestClient({ - endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + ((typeof(stepID) != "undefined") ? stepID + "/" : "") + 'trigger/' + triggerID, - typeRequest: 'update', - data: data, - messageError: 'There are problems update the Step Trigger, please try again.'.translate(), + endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + step.step_uid, + typeRequest: 'remove', functionSuccess: function (xhr, response) { - dataRow.st_condition = data.st_condition; - row.setData(dataRow); + that.removingStepTask(step, response); + that.confirmWindow.close(); + that.updateItemIndexToAccordion(); }, functionFailure: function (xhr, response) { PMDesigner.msgWinError(response.error.message); - } + }, + messageError: 'An unexpected error while deleting the step, please try again later.'.translate(), + messageSuccess: 'Step removed successfully'.translate(), + flashContainer: that.mainWindow.getParent() }); restClient.executeRestClient(); - that.secondaryWindow.close(); }); } - if (cancelButton) { - cancelButton.setHandler(function () { - that.secondaryWindow.close(); + if (noButton) { + noButton.setHandler(function () { + that.confirmWindow.close(); }); } - if (criteriaButton) { - criteriaButton.setVisible(false); - criteriaButton.handler = null; - } - this.secondaryWindow.open(); + this.confirmWindow.open(); }; /** - * eliminates the elements of the secondary window - * @chainable + * eliminates the step of step Assign Accordion + * @param step, the current step to remove + * @param response, data from the endpoint */ -stepsTask.prototype.resetSecondaryWindow = function () { - var i, items; - if (this.secondaryWindow && this.secondaryWindow.items.getSize() > 0) { - items = this.secondaryWindow.items; - for (i = 0; i < items.getSize(); i += 1) { - this.secondaryWindow.removeItem(items.get(i)); +stepsTask.prototype.removingStepTask = function (step, response) { + var stepObject, + stepAvailable, + treeNodeObject, + stepAvailables, + i, + itemsTreeNode = [], + items = []; + stepObject = this.stepsAssignAccordion.getItem("id" + step.step_uid_obj); + this.elementAccordionOpen.remove(stepObject); + this.stepsAssigned.remove(stepObject); + this.stepsAssignAccordion.removeItem(stepObject); + if (stepObject) { + stepAvailable = this.getStepAvailables(); + stepAvailables = this.getAvailablesStepsByCriteria(step.step_type_obj, stepAvailable); + for (i = 0; i < stepAvailables.length; i += 1) { + items.push({ + obj_title: stepAvailables[i]['obj_title'], + obj_type: stepAvailables[i]['obj_type'], + obj_uid: stepAvailables[i]['obj_uid'] + }); + } + treeNodeObject = this.stepsAssignTree.getItem(step.step_type_obj); + itemsTreeNode = treeNodeObject.getItems(); + for (i = 0; i < itemsTreeNode.length; i += 1) { + treeNodeObject.removeItem(itemsTreeNode[i]); } + treeNodeObject.clearItems(); + treeNodeObject.setDataItems(items); + this.updateIndexPosition(treeNodeObject); + this.addEventSortableInTreePanelElements(); + this.addEventSortableInAccordionElements(); } }; /** - * It establishes a PMUI.util.ArrayList that stores the - * elements of "stepsAssignAccordion" that are open - * @chainable - */ -stepsTask.prototype.elementsAccordionOpenFixed = function () { - var i, - accordionItems; - if (this.stepsAssignAccordion) { - accordionItems = this.stepsAssignAccordion.getItems(); - if ($.isArray(accordionItems)) { - for (i = 0; i < accordionItems.length; i += 1) { - if (!accordionItems[i].collapsed) { - this.elementAccordionOpen.insert(accordionItems[i]); - } + * get the steps is not assigned by a criterion + * @param criteria, It is the filter criteria search + * @param stepAvailable, all steps Unassigned + * @returns {Array}, filtered items + */ +stepsTask.prototype.getAvailablesStepsByCriteria = function (criteria, stepAvailable) { + var items = [], + i; + if (jQuery.isArray(stepAvailable)) { + for (i = 0; i < stepAvailable.length; i += 1) { + if (stepAvailable[i].obj_type === criteria) { + items.push(stepAvailable[i]); } } } + return items; }; /** - * It is an extension to add the "sortable" event "stepAssignAccordion". - * when a node "treePanel" is added to stop runs and is where you choose if it's a sort or aggregation. - * @chainable + * This method is executed when an element stepsAssignTree, is assigned in a grid + * @param receiveData, data of the droppable item + * @param grid, the affected grid + * @param index, the index position row + * @returns {stepsTask} */ -stepsTask.prototype.addEventSortableInAccordionElements = function () { - var tagContainer, - newIndex, - index, - treeNodeObject, - treeNodeData, - that = this; - if (this.stepsAssignAccordion && this.stepsAssignAccordion.html) { - tagContainer = this.stepsAssignAccordion.body; - $(tagContainer).sortable({ - items: '>div:not(#idAssignment,#idRouting)', - placeholder: 'steps-placeholder', - receive: function (event, ui) { - var item = ui ? ui.item : null; - if (item && item instanceof jQuery && item.length) { - treeNodeObject = PMUI.getPMUIObject(item.get(0)); - treeNodeData = treeNodeObject.getData(); - } - }, - stop: function (event, ui) { - var itemClone = ui ? ui.item : null, - accordionItems, - accordionItem, - dataEdited, - restClientMultipart, - restClient; - var newIndex = ui.item.index(); - accordionItems = that.stepsAssignAccordion.getItems(); - if (itemClone && itemClone instanceof jQuery && itemClone.length) { - if (treeNodeObject) { - itemClone.remove(); - if (newIndex + 1 > accordionItems.length) { - newIndex = that.stepsAssigned.getSize(); - } - restClient = new PMRestClient({ - endpoint: 'activity/' + PMDesigner.act_uid + '/step', - typeRequest: 'post', - data: { - step_type_obj: treeNodeData.obj_type, - step_uid_obj: treeNodeData.obj_uid, - step_condition: '', - step_position: newIndex + 1, - step_mode: 'EDIT' - }, - functionSuccess: function (xhr, response) { - var item, buttonAfected, treeNode; - that.stepsAssignTree.removeItem(treeNodeObject); - treeNode = that.stepsAssignTree.items.find("id", response.step_type_obj); - if (treeNode.items.getSize() === 0) { - treeNode.addDataItem(that.notItemConfig()); - } - response.obj_description = ''; - response.obj_title = treeNodeData.obj_title; - response.triggers = []; - item = that.createAccordionItem(response, true, true); - item.dataItem = response; - if (that.stepsAssignAccordion.items.getSize() === 2) { - that.stepsAssignAccordion.addItem(item, 0); - } else { - that.stepsAssignAccordion.addItem(item, newIndex); - } - that.stepsAssignAccordion.defineEvents(); - that.customAccordionItemButtons(item.html, response, item); - that.updateItemIndexToAccordion(); - that.addEventSortableInAccordionElements(); - that.addEventSortableInTreePanelElements(); - buttonAfected = that.labelsPanel.getItem("expand-button"); - buttonAfected.setDisabled(false); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: 'An unexpected error while assigning the step, please try again later.'.translate(), - messageSuccess: 'Step assigned successfully.'.translate(), - flashContainer: that.stepsAssignAccordion.getParent() - }); - restClient.executeRestClient(); - } else { - accordionItem = PMUI.getPMUIObject(ui.item.get(0)); - index = that.stepsAssignAccordion.items.indexOf(accordionItem); - if (newIndex !== index) { - that.stepsAssignAccordion.items.remove(accordionItem); - that.stepsAssignAccordion.items.insertAt(accordionItem, newIndex); - dataEdited = { - step_position: newIndex + 1, - step_uid: accordionItem.dataItem.step_uid, - step_type_obj: accordionItem.dataItem.step_type_obj, - step_uid_obj: accordionItem.dataItem.step_uid_obj - }; - restClientMultipart = new PMRestClient({ - endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + accordionItem.dataItem.step_uid, - typeRequest: 'update', - data: dataEdited, - functionSuccess: function (xhr, response) { - that.updateItemIndexToAccordion(); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: 'An unexpected error while editing the step, please try again later.'.translate(), - messageSuccess: 'Step editing successfully.'.translate(), - flashContainer: this.mainWindow - }); - restClientMultipart.executeRestClient(); - } - } - } - }, - start: function (e, ui) { - newIndex = ui.item.index(); - } +stepsTask.prototype.receiveTreeNodeItem = function (receiveData, grid, index) { + var restClient, that = this, message; + if (that.isTriggerAssigned(grid, receiveData.obj_uid)) { + message = new PMUI.ui.FlashMessage({ + message: 'Trigger is assigned.'.translate(), + duration: 3000, + severity: 'error', + appendTo: that.mainWindow }); + message.show(); + return; } -}; -/** - * It is an extension to add the "sortable" event "stepsAssignTree". - * when choosing a node treePanel and you want to add to the accordion or the grid - * @chainable - */ -stepsTask.prototype.addEventSortableInTreePanelElements = function () { - var items = this.stepsAssignTree.getItems(), - connect, - i, - sw, - that = this, - nodeItems; - for (i = 0; i < items.length; i += 1) { - nodeItems = items[i].getItems(); - if (nodeItems.length && nodeItems[0].getData().obj_type) { - sw = items[i].getItems()[0].getData().obj_type === "SCRIPT"; - connect = sw ? ".pmui-gridpanel-tbody" : ".pmui-accordion-panel-body"; - $(items[i].html).find('ul').find('>li').draggable({ - appendTo: document.body, - revert: "invalid", - helper: "clone", - cursor: "move", - zIndex: 1000, - connectToSortable: connect, - start: function (e) { - var i, nodeTag, node, nodeData, accordionItems, item; - nodeTag = e.target; - node = PMUI.getPMUIObject(nodeTag); - nodeData = node.getData(); - accordionItems = that.stepsAssignAccordion.getItems(); - $(that.stepsAssignAccordion.body).hide(); - if (nodeData.obj_type !== "SCRIPT") { - for (i = 0; i < accordionItems.length; i += 1) { - item = accordionItems[i]; - item.collapse(); - } - } - $(that.stepsAssignAccordion.body).show(); - }, - stop: function () { - var i = 0, max; - if (that.elementAccordionOpen) { - max = that.elementAccordionOpen.getSize(); - for (i = 0; i < max; i += 1) { - that.elementAccordionOpen.get(i).expand(); - } - } - } - }); - } else { - $(nodeItems[0].html).draggable("disable"); + restClient = new PMRestClient({ + endpoint: grid.step_uid === undefined ? + 'activity/' + PMDesigner.act_uid + '/step/trigger' : + 'activity/' + PMDesigner.act_uid + '/step/' + grid.step_uid + '/trigger', + typeRequest: 'post', + data: { + tri_uid: receiveData.obj_uid, + st_type: grid.st_type, + st_condition: '', + st_position: index + 1 + }, + functionSuccess: function (xhr, response) { + grid.addDataItem({ + st_condition: '', + st_position: index + 1, + st_type: grid.st_type, + tri_description: '', + tri_title: receiveData.obj_title, + tri_uid: receiveData.obj_uid, + obj_title: receiveData.obj_title, + obj_uid: receiveData.obj_uid + }, index); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); } - } + }); + restClient.executeRestClient(); + return this; }; /** - * add custom buttons on the head of an element of stepsAssignAccordion - * are three buttons - * properties - * edit - * remove - * @param html, is the html of the header accordion item - * @param step, the data of the step selected + * This method is executed when a row is drop in another grid + * @param receiveData, data of the droppable item + * @param grid, the affected grid + * @param index, the index position row + * @param draggableItem + * @returns {*} */ -stepsTask.prototype.customAccordionItemButtons = function (html, step, accordionItem) { - var propertiesStep, - editStep, - removeStep, - $html, - containerButtons, - that = this, - title; - if (html) { - $html = jQuery(html.getElementsByClassName("pmui-accordion-item-header")); - title = step.obj_title + ' (' + step.step_type_obj + ')'; - $html.find(".pmui-accordion-item-title").get(0).title = title; - containerButtons = $('
'); - containerButtons.addClass("propertiesTask-accordionItem"); - propertiesStep = $('' + 'Properties'.translate() + ''); - propertiesStep.addClass("mafe-button-edit propertiesTask-accordionButton"); - editStep = $('' + 'Edit'.translate() + ''); - editStep.addClass("mafe-button-edit propertiesTask-accordionButton"); - removeStep = $('' + 'Remove'.translate() + ''); - removeStep.addClass("mafe-button-delete propertiesTask-accordionButton"); - - propertiesStep.click(function (e) { - e.preventDefault(); - e.stopPropagation(); - that.propertiesStepShow(step); - return false; - }); - - editStep.click(function (e) { - e.preventDefault(); - e.stopPropagation(); - that.editStepShow(step, accordionItem); - return false; - }); - - removeStep.click(function (e) { - e.preventDefault(); - e.stopPropagation(); - that.removeStepShow(step); - return false; +stepsTask.prototype.receiveRowItem = function (receiveData, grid, index, draggableItem) { + var receiveParent = draggableItem.getParent(), + message, + restClient, + that = this; + if (this.isTriggerAssigned(grid, receiveData.obj_uid)) { + message = new PMUI.ui.FlashMessage({ + message: 'Trigger is assigned.'.translate(), + duration: 3000, + severity: 'error', + appendTo: that.mainWindow }); - containerButtons.append(propertiesStep); - containerButtons.append(editStep); - containerButtons.append(removeStep); - $html.append(containerButtons); + index = receiveParent.items.indexOf(draggableItem); + receiveParent.items.remove(draggableItem); + receiveParent.addItem(draggableItem, index); + message.show(); + return false; } -}; -/** - * opens the properties of the selected step with the current settings - * @param step, is the data of selected step - * @chainable - */ -stepsTask.prototype.propertiesStepShow = function (step) { - var form, - saveButton, - cancelButton, - criteriaButton, - that = this; - this.resetSecondaryWindow(); - this.secondaryWindow.setWidth(520); - this.secondaryWindow.setHeight(370); - this.secondaryWindow.setTitle('Step Properties'.translate()); - form = new PMUI.form.Form({ - id: 'stepsEditCondition', - width: 500, - title: 'Condition Trigger'.translate(), - visibleHeader: false, - items: [ - { - id: 'step_mode', - pmType: 'radio', - label: 'Mode'.translate(), - value: '', - visible: step.step_type_obj === "DYNAFORM" ? true : false, - name: 'step_mode', - options: [ - { - id: 'modeEdit', - label: 'Edit'.translate(), - value: 'EDIT', - selected: true - }, { - id: 'modeView', - label: 'View'.translate(), - value: 'VIEW' + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: grid.step_uid === undefined ? + 'activity/' + PMDesigner.act_uid + '/step/trigger' : + 'activity/' + PMDesigner.act_uid + '/step/' + grid.step_uid + '/trigger', + method: 'POST', + data: { + tri_uid: receiveData.obj_uid, + st_type: grid.st_type, + st_condition: receiveData.st_condition, + st_position: index + 1 } - ] - }, - new CriteriaField({ - id: 'step_condition', - pmType: 'textarea', - name: 'step_condition', - valueType: 'string', - label: 'Condition'.translate(), - placeholder: 'Insert a condition'.translate(), - rows: 150, - controlsWidth: 250, - renderType: 'textarea' - }) + }, { + url: receiveParent.step_uid === undefined ? + 'activity/' + PMDesigner.act_uid + '/step/trigger/' + receiveData.obj_uid + '/' + that.getStepType(receiveParent.st_type) : + 'activity/' + PMDesigner.act_uid + '/step/' + receiveParent.step_uid + '/trigger/' + receiveData.obj_uid + '/' + receiveParent.st_type.toLowerCase(), + method: 'DELETE' + } + ] + }, + functionSuccess: function (xhr, response) { + var data; + data = receiveData; + if (data.hasOwnProperty("st_type")) { + data.st_type = grid.st_type; + grid.addDataItem(receiveData, index); + } + receiveParent.removeItem(draggableItem); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + flashContainer: that.mainWindow, + messageError: [ + 'An unexpected error while assigning the trigger, please try again later.'.translate() + ], + messageSuccess: [ + 'Trigger assigned successfully.'.translate() ] }); - this.secondaryWindow.addItem(form); - - var restClient = new PMRestClient({ - endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + step.step_uid, - typeRequest: 'get', - functionSuccess: function (xhr, response) { - form.getField('step_mode').setValue(response.step_mode); - form.getField('step_condition').setValue(response.step_condition); + restClient.executeRestClient(); + return this; +}; +/** + * This method is executed when a row is sorted in the grid + * @param receiveData, data of the droppable item + * @param grid, the affected grid + * @param index, the new index position row + * @returns {stepsTask} + */ +stepsTask.prototype.sortableRowHandler = function (receiveData, grid, index) { + var that = this, + restClient; + restClient = new PMRestClient({ + endpoint: grid.step_uid === undefined ? + 'activity/' + PMDesigner.act_uid + "/step/trigger/" + receiveData.tri_uid : + 'activity/' + PMDesigner.act_uid + "/step/" + grid.step_uid + "/trigger/" + receiveData.tri_uid, + typeRequest: 'update', + data: { + st_type: receiveData.st_type, + st_condition: receiveData.st_condition, + st_position: index + 1 }, functionFailure: function (xhr, response) { PMDesigner.msgWinError(response.error.message); - } + }, + flashContainer: that.mainWindow, + messageError: 'An unexpected error while assigning the trigger, please try again later.'.translate(), + messageSuccess: 'Trigger assigned successfully.'.translate() }); restClient.executeRestClient(); - saveButton = this.secondaryWindow.footer.getItem("secondaryWindow-save"); - cancelButton = this.secondaryWindow.footer.getItem("secondaryWindow-cancel"); - criteriaButton = this.secondaryWindow.footer.getItem("secondaryWindow-criteria"); - if (saveButton) { - saveButton.setHandler(function () { - var restClient; - if (form.isValid()) { - restClient = new PMRestClient({ - endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + step.step_uid, - typeRequest: 'update', - data: form.getData(), - functionSuccess: function () { - that.secondaryWindow.close(); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: 'There are problems update the Step Trigger, please try again.'.translate() - }); - restClient.executeRestClient(); - } + return this; +}; +/** + * This method eliminates the list of triggers trigger an assigned step + * @param row, the row affected or selected + * @param grid, It is affected or grid to remove selected row + */ +stepsTask.prototype.removeTrigger = function (row, grid) { + var message = 'Do you want to remove the trigger "', + messageData = row.getData().tri_title ? row.getData().tri_title : "", + yesButton, + noButton, + that = this, + restClient; + message = message + messageData + '"?'; + this.confirmWindow.setMessage(message.translate()); + yesButton = this.confirmWindow.footer.getItem("confirmWindow-footer-yes"); + if (yesButton) { + yesButton.setHandler(function () { + restClient = new PMRestClient({ + endpoint: grid.step_uid === undefined ? + 'activity/' + PMDesigner.act_uid + '/step/trigger/' + row.getData().tri_uid + '/' + that.getStepType(row.getData().st_type) : + 'activity/' + PMDesigner.act_uid + '/step/' + grid.step_uid + '/trigger/' + row.getData().tri_uid + '/' + that.getStepType(row.getData().st_type), + typeRequest: 'remove', + functionSuccess: function (xhr, response) { + grid.removeItem(row); + that.confirmWindow.close(); + that.updateIndexToGrid(grid); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + flashContainer: that.mainWindow, + messageError: 'An unexpected error while deleting the trigger, please try again later.'.translate(), + messageSuccess: 'Trigger removed successfully'.translate() + }); + restClient.executeRestClient(); }); } - if (cancelButton) { - cancelButton.setHandler(function () { - that.secondaryWindow.close(); + noButton = this.confirmWindow.footer.getItem("confirmWindow-footer-no"); + if (noButton) { + noButton.setHandler(function () { + that.confirmWindow.close(); }); } - if (criteriaButton) { - criteriaButton.handler = null; - criteriaButton.setVisible(false); - } - this.secondaryWindow.open(); + this.confirmWindow.open(); }; /** - * opens the step of the selected step with the current settings - * @param step, is the data of selected step - * @chainable + * updates indexes of elements selected grid + * @param grid, It is affected or grid to remove selected row + * @returns {stepsTask} */ -stepsTask.prototype.editStepShow = function (step, accordioItem) { - var inputDocument, - that = this; - switch (step.step_type_obj) { - case 'DYNAFORM': - var restProxy = new PMRestClient({ - endpoint: 'dynaform/' + step.step_uid_obj, - typeRequest: 'get', - functionSuccess: function (xhr, response) { - var old = PMUI.activeCanvas, - formDesigner; - PMUI.activeCanvas = false; - formDesigner = PMDesigner.dynaformDesigner(response); - formDesigner.onHide = function () { - var assignedDynaform, - i, - data, - title; - assignedDynaform = that.getStepsAssignedByCriteria("DYNAFORM"); - if (jQuery.isArray(assignedDynaform)) { - for (i = 0; i < assignedDynaform.length; i += 1) { - data = assignedDynaform[i]; - if (typeof data === "object") { - if (data.step_uid === step.step_uid) { - title = data.step_position + ". " + data.obj_title; - title = title + ' (' + that.stepsType["DYNAFORM"] + ')'; - accordioItem.setTitle(title); - accordioItem.dataItem = data; - } - } - } - } - PMUI.activeCanvas = old; - }; - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } - }); - restProxy.executeRestClient(); - break; - case 'OUTPUT_DOCUMENT': - PMDesigner.output(); - PMDesigner.output.showTiny(step.step_uid_obj); - break; - case 'INPUT_DOCUMENT': - inputDocument = new InputDocument({ - onUpdateInputDocumentHandler: function (data, inputDoc) { - var position, title; - position = accordioItem.dataItem.step_position; - title = position + ". " + data.inp_doc_title; - title = title + ' (' + that.stepsType["INPUT_DOCUMENT"] + ')'; - accordioItem.dataItem.obj_title = data.inp_doc_title; - accordioItem.setTitle(title); - inputDoc.winMainInputDocument.close(); +stepsTask.prototype.updateIndexToGrid = function (grid) { + var cell, rows, i, row; + if (grid) { + rows = grid.getItems(); + if (jQuery.isArray(rows)) { + for (i = 0; i < rows.length; i += 1) { + row = rows[i]; + cell = row.cells.find("columnData"); + if (cell) { + cell.setContent(i + 1); } - }); - inputDocument.build(); - inputDocument.openFormInMainWindow(); - inputDocument.inputDocumentFormGetProxy(step.step_uid_obj); - break; + } + } } + return this; }; /** - * the window opens for confirmation of the removal step - * @param step, the current step to remove - * @chainable + * get the steps assigned by a search criterion + * @param criteria, search filter, after running the endpoint getAccordionData method + * @returns {Array}, response with criteria */ -stepsTask.prototype.removeStepShow = function (step) { - var title, - yesButton, - noButton, - that = this, - restClient; - if (this.stepsType[step.step_type_obj] !== undefined) { - title = "Step {0} ( {1} )".translate([step.obj_title, this.stepsType[step.step_type_obj]]); - this.confirmWindow.setTitle(title); - } else { - this.confirmWindow.setTitle("Step " + step.step_type_obj.capitalize()); - } - this.confirmWindow.setMessage("Do you want to remove the step '{0}'?".translate([step.obj_title])); - yesButton = this.confirmWindow.footer.getItem("confirmWindow-footer-yes"); - noButton = this.confirmWindow.footer.getItem("confirmWindow-footer-no"); - if (yesButton) { - yesButton.setHandler(function () { - restClient = new PMRestClient({ - endpoint: 'activity/' + PMDesigner.act_uid + '/step/' + step.step_uid, - typeRequest: 'remove', - functionSuccess: function (xhr, response) { - that.removingStepTask(step, response); - that.confirmWindow.close(); - that.updateItemIndexToAccordion(); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: 'An unexpected error while deleting the step, please try again later.'.translate(), - messageSuccess: 'Step removed successfully'.translate(), - flashContainer: that.mainWindow.getParent() - }); - restClient.executeRestClient(); - }); - } - if (noButton) { - noButton.setHandler(function () { - that.confirmWindow.close(); - }); +stepsTask.prototype.getStepsAssignedByCriteria = function (criteria) { + var allAssigned, + i, + elements, + j, + resp, + response = []; + allAssigned = this.getAccordionData(); + if (jQuery.isArray(allAssigned)) { + for (i = 0; i < allAssigned.length; i += 1) { + resp = allAssigned[i]; + if (typeof resp === "object") { + elements = resp.response ? resp.response : []; + for (j = 0; j < elements.length; j += 1) { + data = elements[j]; + if (typeof data === "object") { + if (data.step_type_obj && data.step_type_obj === criteria) { + response.push(data); + } + } + } + } + } } - this.confirmWindow.open(); + return response; }; /** - * eliminates the step of step Assign Accordion - * @param step, the current step to remove - * @param response, data from the endpoint + * updates indexes of elements assigned + * @returns {stepsTask} */ -stepsTask.prototype.removingStepTask = function (step, response) { - var stepObject, - stepAvailable, - treeNodeObject, - stepAvailables, +stepsTask.prototype.updateItemIndexToAccordion = function () { + var title, i, - itemsTreeNode = [], - items = []; - stepObject = this.stepsAssignAccordion.getItem("id" + step.step_uid_obj); - this.elementAccordionOpen.remove(stepObject); - this.stepsAssigned.remove(stepObject); - this.stepsAssignAccordion.removeItem(stepObject); - if (stepObject) { - stepAvailable = this.getStepAvailables(); - stepAvailables = this.getAvailablesStepsByCriteria(step.step_type_obj, stepAvailable); - for (i = 0; i < stepAvailables.length; i += 1) { - items.push({ - obj_title: stepAvailables[i]['obj_title'], - obj_type: stepAvailables[i]['obj_type'], - obj_uid: stepAvailables[i]['obj_uid'] - }); - } - treeNodeObject = this.stepsAssignTree.getItem(step.step_type_obj); - itemsTreeNode = treeNodeObject.getItems(); - for (i = 0; i < itemsTreeNode.length; i += 1) { - treeNodeObject.removeItem(itemsTreeNode[i]); + item, + dataItem, + items = this.stepsAssignAccordion.items, + position, + max; + max = items.getSize(); + for (i = 0; i < max; i += 1) { + item = items.get(i); + position = items.indexOf(item); + dataItem = item.dataItem; + title = (position + 1) + ". " + dataItem.obj_title; + if (this.stepsType[dataItem.step_type_obj]){ + title = title + ' (' + this.stepsType[dataItem.step_type_obj] + ')'; } - treeNodeObject.clearItems(); - treeNodeObject.setDataItems(items); - this.updateIndexPosition(treeNodeObject); - this.addEventSortableInTreePanelElements(); - this.addEventSortableInAccordionElements(); + item.dataItem.step_position = i + 1; + item.setTitle(title); } + return this; }; /** - * get the steps is not assigned by a criterion - * @param criteria, It is the filter criteria search - * @param stepAvailable, all steps Unassigned - * @returns {Array}, filtered items + * add tooltip in treeNode elements + * @returns {stepsTask} */ -stepsTask.prototype.getAvailablesStepsByCriteria = function (criteria, stepAvailable) { - var items = [], - i; - if (jQuery.isArray(stepAvailable)) { - for (i = 0; i < stepAvailable.length; i += 1) { - if (stepAvailable[i].obj_type === criteria) { - items.push(stepAvailable[i]); +stepsTask.prototype.updateIndexPosition = function (treeNode) { + var items, i, item, $item, text, data; + if (treeNode && treeNode.html) { + items = treeNode.getItems(); + if (jQuery.isArray(items)) { + for (i = 0; i < items.length; i += 1) { + item = items[i]; + if (item.html) { + $item = $(item.html); + data = item.getData(); + text = $item.find("a").get(0); + text.title = data.obj_title; + } } } } - return items; + return this; }; /** - * This method is executed when an element stepsAssignTree, is assigned in a grid - * @param receiveData, data of the droppable item - * @param grid, the affected grid - * @param index, the index position row - * @returns {stepsTask} + * return the not items config. + * @returns {{obj_title: *, obj_uid: string, id: string}} */ -stepsTask.prototype.receiveTreeNodeItem = function (receiveData, grid, index) { - var restClient, that = this, message; - if (that.isTriggerAssigned(grid, receiveData.obj_uid)) { - message = new PMUI.ui.FlashMessage({ - message: 'Trigger is assigned.'.translate(), - duration: 3000, - severity: 'error', - appendTo: that.mainWindow - }); - message.show(); - return; - } - restClient = new PMRestClient({ - endpoint: grid.step_uid === undefined ? - 'activity/' + PMDesigner.act_uid + '/step/trigger' : - 'activity/' + PMDesigner.act_uid + '/step/' + grid.step_uid + '/trigger', - typeRequest: 'post', - data: { - tri_uid: receiveData.obj_uid, - st_type: grid.st_type, - st_condition: '', - st_position: index + 1 - }, - functionSuccess: function (xhr, response) { - grid.addDataItem({ - st_condition: '', - st_position: index + 1, - st_type: grid.st_type, - tri_description: '', - tri_title: receiveData.obj_title, - tri_uid: receiveData.obj_uid, - obj_title: receiveData.obj_title, - obj_uid: receiveData.obj_uid - }, index); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } - }); - restClient.executeRestClient(); - return this; +stepsTask.prototype.notItemConfig = function () { + var config = { + obj_title: 'N/A'.translate(), + obj_uid: '', + id: "notItem" + }; + return config; }; -/** - * This method is executed when a row is drop in another grid - * @param receiveData, data of the droppable item - * @param grid, the affected grid - * @param index, the index position row - * @param draggableItem - * @returns {*} - */ -stepsTask.prototype.receiveRowItem = function (receiveData, grid, index, draggableItem) { - var receiveParent = draggableItem.getParent(), - message, - restClient, - that = this; - if (this.isTriggerAssigned(grid, receiveData.obj_uid)) { - message = new PMUI.ui.FlashMessage({ - message: 'Trigger is assigned.'.translate(), - duration: 3000, - severity: 'error', - appendTo: that.mainWindow - }); - index = receiveParent.items.indexOf(draggableItem); - receiveParent.items.remove(draggableItem); - receiveParent.addItem(draggableItem, index); - message.show(); - return false; - } - restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - calls: [ - { - url: grid.step_uid === undefined ? - 'activity/' + PMDesigner.act_uid + '/step/trigger' : - 'activity/' + PMDesigner.act_uid + '/step/' + grid.step_uid + '/trigger', - method: 'POST', +( + function () { + var processPermissionsSetForm; + PMDesigner.processPermissions = function (event) { + var PROCESS_PERMISSIONS_OPTION = "", + PROCESS_PERMISSIONS_UID = "", + arrayCboGroup = [], + arrayCboUser = [], + winGrdpnlProcessPermissions, + grdpnlProcessPermissions, + frmProcessPermissions, + processPermissionsData, + btnCreate, btnSave, btnCancel, + loadDataFromServerToFields, + disableAllItems, + listProcessPermissions, + isDirty2, + isDirtyFormProcessPermission, + refreshGridPanelInMainWindow, + processPermissionsGetRestProxy, + processPermissionsPostRestProxy, + processPermissionGetRestProxy, + processPermissionsPutRestProxy, + cboTargetCboOriginTaskSetOptionsRestProxy, + cboDynaFormSetOptionsRestProxy, + cboInputDocumentSetOptionsRestProxy, + cboOutputDocumentSetOptionsRestProxy, + processPermissionsSetFormByType, + processPermissionsDeleteRestProxy, + cboStatusCase, + cboTargetTask, + cboGroupOrUser, + cboOriginTask, + optionsType, + cboType, + cboDynaForm, + cboInputDocument, + cboOutputDocument, + cboPermission, + cboParticipationRequired, + processPermissionsDataIni = {}; + + loadDataFromServerToFields = function () { + var restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, data: { - tri_uid: receiveData.obj_uid, - st_type: grid.st_type, - st_condition: receiveData.st_condition, - st_position: index + 1 + calls: [ + { + url: 'project/' + PMDesigner.project.id + '/', + method: 'GET' + }, { + url: 'project/' + PMDesigner.project.id + '/dynaforms', + method: 'GET' + }, { + url: 'project/' + PMDesigner.project.id + '/input-documents', + method: 'GET' + }, { + url: 'project/' + PMDesigner.project.id + '/output-documents', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + var i; + data = response[0].response; + cboTargetTask.clearOptions(); + cboOriginTask.clearOptions(); + cboTargetTask.addOption({value: '', label: 'All Tasks'.translate()}); + cboOriginTask.addOption({value: '', label: 'All Tasks'.translate()}); + for (i = 0; i <= data.diagrams[0].activities.length - 1; i += 1) { + cboTargetTask.addOption({ + value: data.diagrams[0].activities[i].act_uid, + label: data.diagrams[0].activities[i].act_name + }); + cboOriginTask.addOption({ + value: data.diagrams[0].activities[i].act_uid, + label: data.diagrams[0].activities[i].act_name + }); + } + //project/dynaforms + data = response[1].response; + cboDynaForm.clearOptions(); + cboDynaForm.addOption({value: '', label: 'All'.translate()}); + for (i = 0; i <= data.length - 1; i += 1) { + cboDynaForm.addOption({value: data[i].dyn_uid, label: data[i].dyn_title}); + } + //project/input-documents + data = response[2].response; + cboInputDocument.clearOptions(); + cboInputDocument.addOption({value: '', label: 'All'.translate()}); + for (i = 0; i <= data.length - 1; i += 1) { + cboInputDocument.addOption({value: data[i].inp_doc_uid, label: data[i].inp_doc_title}); + } + //project/output-documents + data = response[3].response; + cboOutputDocument.clearOptions(); + cboOutputDocument.addOption({value: '', label: 'All'.translate()}); + for (i = 0; i <= data.length - 1; i += 1) { + cboOutputDocument.addOption({value: data[i].out_doc_uid, label: data[i].out_doc_title}); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); } - }, { - url: receiveParent.step_uid === undefined ? - 'activity/' + PMDesigner.act_uid + '/step/trigger/' + receiveData.obj_uid + '/' + that.getStepType(receiveParent.st_type) : - 'activity/' + PMDesigner.act_uid + '/step/' + receiveParent.step_uid + '/trigger/' + receiveData.obj_uid + '/' + receiveParent.st_type.toLowerCase(), - method: 'DELETE' + }); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + }; + + disableAllItems = function () { + winGrdpnlProcessPermissions.getItems()[0].setVisible(false); + winGrdpnlProcessPermissions.getItems()[1].setVisible(false); + winGrdpnlProcessPermissions.hideFooter(); + }; + + isDirty2 = function () { + var user, + dynaForm, + inputDocument, + outputDocument, + flagInsert = (typeof(processPermissionsData.op_case_status) === "undefined") ? true : false; + + if (flagInsert) { + processPermissionsData = processPermissionsDataIni; } - ] - }, - functionSuccess: function (xhr, response) { - var data; - data = receiveData; - if (data.hasOwnProperty("st_type")) { - data.st_type = grid.st_type; - grid.addDataItem(receiveData, index); - } - receiveParent.removeItem(draggableItem); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - flashContainer: that.mainWindow, - messageError: [ - 'An unexpected error while assigning the trigger, please try again later.'.translate() - ], - messageSuccess: [ - 'Trigger assigned successfully.'.translate() - ] - }); - restClient.executeRestClient(); - return this; -}; -/** - * This method is executed when a row is sorted in the grid - * @param receiveData, data of the droppable item - * @param grid, the affected grid - * @param index, the new index position row - * @returns {stepsTask} - */ -stepsTask.prototype.sortableRowHandler = function (receiveData, grid, index) { - var that = this, - restClient; - restClient = new PMRestClient({ - endpoint: grid.step_uid === undefined ? - 'activity/' + PMDesigner.act_uid + "/step/trigger/" + receiveData.tri_uid : - 'activity/' + PMDesigner.act_uid + "/step/" + grid.step_uid + "/trigger/" + receiveData.tri_uid, - typeRequest: 'update', - data: { - st_type: receiveData.st_type, - st_condition: receiveData.st_condition, - st_position: index + 1 - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - flashContainer: that.mainWindow, - messageError: 'An unexpected error while assigning the trigger, please try again later.'.translate(), - messageSuccess: 'Trigger assigned successfully.'.translate() - }); - restClient.executeRestClient(); - return this; -}; -/** - * This method eliminates the list of triggers trigger an assigned step - * @param row, the row affected or selected - * @param grid, It is affected or grid to remove selected row - */ -stepsTask.prototype.removeTrigger = function (row, grid) { - var message = 'Do you want to remove the trigger "', - messageData = row.getData().tri_title ? row.getData().tri_title : "", - yesButton, - noButton, - that = this, - restClient; - message = message + messageData + '"?'; - this.confirmWindow.setMessage(message.translate()); - yesButton = this.confirmWindow.footer.getItem("confirmWindow-footer-yes"); - if (yesButton) { - yesButton.setHandler(function () { - restClient = new PMRestClient({ - endpoint: grid.step_uid === undefined ? - 'activity/' + PMDesigner.act_uid + '/step/trigger/' + row.getData().tri_uid + '/' + that.getStepType(row.getData().st_type) : - 'activity/' + PMDesigner.act_uid + '/step/' + grid.step_uid + '/trigger/' + row.getData().tri_uid + '/' + that.getStepType(row.getData().st_type), - typeRequest: 'remove', - functionSuccess: function (xhr, response) { - grid.removeItem(row); - that.confirmWindow.close(); - that.updateIndexToGrid(grid); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - flashContainer: that.mainWindow, - messageError: 'An unexpected error while deleting the trigger, please try again later.'.translate(), - messageSuccess: 'Trigger removed successfully'.translate() - }); - restClient.executeRestClient(); - }); - } - noButton = this.confirmWindow.footer.getItem("confirmWindow-footer-no"); - if (noButton) { - noButton.setHandler(function () { - that.confirmWindow.close(); - }); - } - this.confirmWindow.open(); -}; -/** - * updates indexes of elements selected grid - * @param grid, It is affected or grid to remove selected row - * @returns {stepsTask} - */ -stepsTask.prototype.updateIndexToGrid = function (grid) { - var cell, rows, i, row; - if (grid) { - rows = grid.getItems(); - if (jQuery.isArray(rows)) { - for (i = 0; i < rows.length; i += 1) { - row = rows[i]; - cell = row.cells.find("columnData"); - if (cell) { - cell.setContent(i + 1); + + if (cboStatusCase.getValue() != processPermissionsData.op_case_status) { + return true; } - } - } - } - return this; -}; -/** - * get the steps assigned by a search criterion - * @param criteria, search filter, after running the endpoint getAccordionData method - * @returns {Array}, response with criteria - */ -stepsTask.prototype.getStepsAssignedByCriteria = function (criteria) { - var allAssigned, - i, - elements, - j, - resp, - response = []; - allAssigned = this.getAccordionData(); - if (jQuery.isArray(allAssigned)) { - for (i = 0; i < allAssigned.length; i += 1) { - resp = allAssigned[i]; - if (typeof resp === "object") { - elements = resp.response ? resp.response : []; - for (j = 0; j < elements.length; j += 1) { - data = elements[j]; - if (typeof data === "object") { - if (data.step_type_obj && data.step_type_obj === criteria) { - response.push(data); - } - } + + if (cboTargetTask.getValue() != processPermissionsData.tas_uid) { + return true; } - } - } - } - return response; -}; -/** - * updates indexes of elements assigned - * @returns {stepsTask} - */ -stepsTask.prototype.updateItemIndexToAccordion = function () { - var title, - i, - item, - dataItem, - items = this.stepsAssignAccordion.items, - position, - max; - max = items.getSize(); - for (i = 0; i < max; i += 1) { - item = items.get(i); - position = items.indexOf(item); - dataItem = item.dataItem; - title = (position + 1) + ". " + dataItem.obj_title; - if (this.stepsType[dataItem.step_type_obj]){ - title = title + ' (' + this.stepsType[dataItem.step_type_obj] + ')'; - } - item.dataItem.step_position = i + 1; - item.setTitle(title); - } - return this; -}; -/** - * add tooltip in treeNode elements - * @returns {stepsTask} - */ -stepsTask.prototype.updateIndexPosition = function (treeNode) { - var items, i, item, $item, text, data; - if (treeNode && treeNode.html) { - items = treeNode.getItems(); - if (jQuery.isArray(items)) { - for (i = 0; i < items.length; i += 1) { - item = items[i]; - if (item.html) { - $item = $(item.html); - data = item.getData(); - text = $item.find("a").get(0); - text.title = data.obj_title; + + user = (cboGroupOrUser.get("value") !== null && cboGroupOrUser.get("value")) ? cboGroupOrUser.get("value") : ""; + + if (user != processPermissionsData.usr_uid) { + return true; } - } - } - } - return this; -}; -/** - * return the not items config. - * @returns {{obj_title: *, obj_uid: string, id: string}} - */ -stepsTask.prototype.notItemConfig = function () { - var config = { - obj_title: 'N/A'.translate(), - obj_uid: '', - id: "notItem" - }; - return config; -}; -( - function () { - var processPermissionsSetForm; - PMDesigner.processPermissions = function (event) { - var PROCESS_PERMISSIONS_OPTION = "", - PROCESS_PERMISSIONS_UID = "", - arrayCboGroup = [], - arrayCboUser = [], - winGrdpnlProcessPermissions, - grdpnlProcessPermissions, - frmProcessPermissions, - processPermissionsData, - btnCreate, btnSave, btnCancel, - loadDataFromServerToFields, - disableAllItems, - listProcessPermissions, - isDirty2, - isDirtyFormProcessPermission, - refreshGridPanelInMainWindow, - processPermissionsGetRestProxy, - processPermissionsPostRestProxy, - processPermissionGetRestProxy, - processPermissionsPutRestProxy, - cboTargetCboOriginTaskSetOptionsRestProxy, - cboDynaFormSetOptionsRestProxy, - cboInputDocumentSetOptionsRestProxy, - cboOutputDocumentSetOptionsRestProxy, - processPermissionsSetFormByType, - processPermissionsDeleteRestProxy, - cboStatusCase, - cboTargetTask, - cboGroupOrUser, - cboOriginTask, - optionsType, - cboType, - cboDynaForm, - cboInputDocument, - cboOutputDocument, - cboPermission, - cboParticipationRequired, - processPermissionsDataIni = {}; - loadDataFromServerToFields = function () { - var restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - calls: [ - { - url: 'project/' + PMDesigner.project.id + '/', - method: 'GET' - }, { - url: 'project/' + PMDesigner.project.id + '/dynaforms', - method: 'GET' - }, { - url: 'project/' + PMDesigner.project.id + '/input-documents', - method: 'GET' - }, { - url: 'project/' + PMDesigner.project.id + '/output-documents', - method: 'GET' - } - ] - }, - functionSuccess: function (xhr, response) { - var i; - data = response[0].response; - cboTargetTask.clearOptions(); - cboOriginTask.clearOptions(); - cboTargetTask.addOption({value: '', label: 'All Tasks'.translate()}); - cboOriginTask.addOption({value: '', label: 'All Tasks'.translate()}); - for (i = 0; i <= data.diagrams[0].activities.length - 1; i += 1) { - cboTargetTask.addOption({ - value: data.diagrams[0].activities[i].act_uid, - label: data.diagrams[0].activities[i].act_name - }); - cboOriginTask.addOption({ - value: data.diagrams[0].activities[i].act_uid, - label: data.diagrams[0].activities[i].act_name - }); - } - //project/dynaforms - data = response[1].response; - cboDynaForm.clearOptions(); - cboDynaForm.addOption({value: '', label: 'All'.translate()}); - for (i = 0; i <= data.length - 1; i += 1) { - cboDynaForm.addOption({value: data[i].dyn_uid, label: data[i].dyn_title}); - } - //project/input-documents - data = response[2].response; - cboInputDocument.clearOptions(); - cboInputDocument.addOption({value: '', label: 'All'.translate()}); - for (i = 0; i <= data.length - 1; i += 1) { - cboInputDocument.addOption({value: data[i].inp_doc_uid, label: data[i].inp_doc_title}); - } - //project/output-documents - data = response[3].response; - cboOutputDocument.clearOptions(); - cboOutputDocument.addOption({value: '', label: 'All'.translate()}); - for (i = 0; i <= data.length - 1; i += 1) { - cboOutputDocument.addOption({value: data[i].out_doc_uid, label: data[i].out_doc_title}); - } - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } - }); - restClient.setBaseEndPoint(''); - restClient.executeRestClient(); - }; - - disableAllItems = function () { - winGrdpnlProcessPermissions.getItems()[0].setVisible(false); - winGrdpnlProcessPermissions.getItems()[1].setVisible(false); - winGrdpnlProcessPermissions.hideFooter(); - }; - - isDirty2 = function () { - var user, - dynaForm, - inputDocument, - outputDocument, - flagInsert = (typeof(processPermissionsData.op_case_status) === "undefined") ? true : false; - - if (flagInsert) { - processPermissionsData = processPermissionsDataIni; - } - - if (cboStatusCase.getValue() != processPermissionsData.op_case_status) { - return true; - } - - if (cboTargetTask.getValue() != processPermissionsData.tas_uid) { - return true; - } - - user = (cboGroupOrUser.get("value") !== null && cboGroupOrUser.get("value")) ? cboGroupOrUser.get("value") : ""; - - if (user != processPermissionsData.usr_uid) { - return true; - } - - if (cboOriginTask.getValue() != processPermissionsData.op_task_source) { - return true; - } - - if (cboParticipationRequired.getValue() != processPermissionsData.op_participate) { - return true; - } - - if (cboType.getValue() != processPermissionsData.op_obj_type) { - return true; - } - - switch (cboType.getValue()) { - case "DYNAFORM": - dynaForm = (cboDynaForm.getValue() !== "") ? cboDynaForm.getValue() : "0"; - - if (dynaForm != processPermissionsData.op_obj_uid) { - return true; + if (cboOriginTask.getValue() != processPermissionsData.op_task_source) { + return true; + } + + if (cboParticipationRequired.getValue() != processPermissionsData.op_participate) { + return true; + } + + if (cboType.getValue() != processPermissionsData.op_obj_type) { + return true; + } + + switch (cboType.getValue()) { + case "DYNAFORM": + dynaForm = (cboDynaForm.getValue() !== "") ? cboDynaForm.getValue() : "0"; + + if (dynaForm != processPermissionsData.op_obj_uid) { + return true; } if (cboPermission.getValue() != processPermissionsData.op_action) { @@ -15493,5607 +15493,4831 @@ stepsTask.prototype.notItemConfig = function () { }() ); -(function () { - var winHtmlShow, loadValuesStartMessage; - - PMDesigner.startMessage = function (element) { - var winGrdpnlStartMessage, - btnNew, - cboUser, - cboDynaForm, - btnGenerateStartMessagePage, - frmDataStartMessage, - frmHtml, - winFrmDataStartMessage, - restProxy, - disableAllItems, - winFrmStartMessageShow, - updateStartMessage, - loadDataDynaform, - loadDataUsers, - loadDataForm, - listUsers = [], - cboMethod, - listDynaforms = [], - dataForm = [], - enableGenerateWebEntry, - btnSaveStartMessagePage, - btnStartMessageCancel, - btnClose, - startMessage = element; +(function () { + var winHtmlShow, loadValuesStartMessage; + + PMDesigner.startMessage = function (element) { + var winGrdpnlStartMessage, + btnNew, + cboUser, + cboDynaForm, + btnGenerateStartMessagePage, + frmDataStartMessage, + frmHtml, + winFrmDataStartMessage, + restProxy, + disableAllItems, + winFrmStartMessageShow, + updateStartMessage, + loadDataDynaform, + loadDataUsers, + loadDataForm, + listUsers = [], + cboMethod, + listDynaforms = [], + dataForm = [], + enableGenerateWebEntry, + btnSaveStartMessagePage, + btnStartMessageCancel, + btnClose, + startMessage = element; + + disableAllItems = function () { + winGrdpnlStartMessage.getItems()[0].setVisible(false); + winGrdpnlStartMessage.getItems()[1].setVisible(false); + btnGenerateStartMessagePage.setVisible(false); + btnStartMessageCancel.setVisible(false); + btnClose.setVisible(false); + winGrdpnlStartMessage.hideFooter(); + }; + + winFrmStartMessageShow = function () { + disableAllItems(); + frmDataStartMessage.reset(); + winGrdpnlStartMessage.showFooter(); + winGrdpnlStartMessage.getItems()[0].setVisible(true); + btnGenerateStartMessagePage.setVisible(true); + btnStartMessageCancel.setVisible(true); + loadDataUsers(); + loadDataDynaform(); + loadDataForm(); + frmDataStartMessage.setFocus(); + }; + + winHtmlShow = function (msgHtml) { + if (typeof msgHtml == 'undefined') { + msgHtml = dataForm.we_data; + if (dataForm.we_method == "WS") { + window.open(msgHtml); + winGrdpnlStartMessage.close(); + return false; + } + } + disableAllItems(); + winGrdpnlStartMessage.showFooter(); + winGrdpnlStartMessage.footer.getItems()[1].setVisible(false); + btnClose.setVisible(true); + winGrdpnlStartMessage.getItems()[1].setVisible(true); + winGrdpnlStartMessage.getItems()[1].setWidth(925); + winGrdpnlStartMessage.getItems()[1].setHeight(440); + winGrdpnlStartMessage.getItems()[1].hideHeader(); + frmHtml.getFields()[0].setHeight(396); + frmHtml.getItems()[0].setValue(msgHtml); + frmHtml.panel.style.addProperties({'box-sizing': 'initial'}); + frmHtml.style.addProperties({marginLeft: '16px'}); + frmHtml.setFocus(); + return true; + }; + + loadValuesStartMessage = function (flag) { + var viewFlagForm, + restClient, + response; + listUsers = []; + listDynaforms = []; + dataForm = []; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'activity/' + startMessage.ports.get(0).connection.flo_element_dest + '/assignee/all', + method: 'GET' + }, + { + url: "activity/" + startMessage.ports.get(0).connection.flo_element_dest + "/steps", + method: 'GET' + }, { + url: 'web-entry/' + startMessage.evn_uid, + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + listUsers = response[0].response; + listDynaforms = response[1].response; + dataForm = response[2].response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + if (flag) { + viewFlagForm = false; + if (typeof dataForm == 'object' && dataForm.we_data != null) { + viewFlagForm = true; + } + response = [listUsers.length, listDynaforms.length, viewFlagForm]; + return response; + } + return true; + }; + + updateStartMessage = function (data) { + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: "web-entry/" + startMessage.evn_uid, + method: 'PUT', + data: data + }, + { + url: 'web-entry/' + startMessage.evn_uid, + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + dataForm = response[1].response; + if (data.we_method == "HTML") { + winHtmlShow(response.we_data); + } + btnGenerateStartMessagePage.setVisible(false); + btnStartMessageCancel.setVisible(false); + btnClose.setVisible(true); + winGrdpnlStartMessage.footer.getItems()[1].setVisible(false); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: ["There are problems updating the Web Entry, please try again.".translate()], + messageSuccess: ['Web Entry updated successfully'.translate()], + flashContainer: frmDataStartMessage + }); + restClient.executeRestClient(); + }; + + loadDataDynaform = function () { + var i; + cboDynaForm.clearOptions(); + for (i = 0; i <= listDynaforms.length - 1; i++) { + if (listDynaforms[i].step_type_obj == "DYNAFORM") { + cboDynaForm.addOption({ + value: listDynaforms[i].step_uid_obj, + label: listDynaforms[i].obj_title + }); + } + } + }; + + loadDataUsers = function () { + var i; + cboUser.clearOptions(); + for (i = 0; i <= listUsers.length - 1; i++) { + cboUser.addOption({ + value: listUsers[i].aas_uid, + label: listUsers[i].aas_name + ' ' + listUsers[i].aas_lastname + }); + } + }; + + loadDataForm = function () { + cboUser.setValue(dataForm.usr_uid); + cboDynaForm.setValue(dataForm.dyn_uid); + cboMethod.setValue(dataForm.we_method); + }; + + enableGenerateWebEntry = function () { + btnGenerateStartMessagePage.setVisible(true); + btnStartMessageCancel.setVisible(true); + btnClose.setVisible(false); + winGrdpnlStartMessage.footer.getItems()[1].setVisible(true); + }; + cboUser = new PMUI.field.DropDownListField({ + id: "cboUser", + name: "cboUser", + label: "User".translate(), + required: true, + options: null, + onChange: function (newVal, oldVal) { + enableGenerateWebEntry(); + }, + controlsWidth: 350 + }); + + cboDynaForm = new PMUI.field.DropDownListField({ + id: "cboDynaForm", + name: "cboDynaForm", + label: "Initial Dynaform".translate(), + options: null, + required: true, + onChange: function (newVal, oldVal) { + enableGenerateWebEntry(); + }, + controlsWidth: 350 + }); + + cboMethod = new PMUI.field.DropDownListField({ + id: "cboMethod", + name: "cboMethod", + label: "Method".translate(), + value: "WS", + options: [ + { + value: "WS", + label: "PHP pages with Web Services".translate() + }, + { + value: "HTML", + label: "Single HTML".translate() + } + ], + onChange: function (newVal, oldVal) { + enableGenerateWebEntry(); + }, + controlsWidth: 350 + }); + + btnGenerateStartMessagePage = new PMUI.ui.Button({ + id: "btnGenerateStartMessagePage", + text: "Generate Web Entry Page".translate(), + handler: function () { + var flagGenerateStartMessage = 0, data; + data = { + tas_uid: startMessage.ports.get(0).connection.flo_element_dest, + dyn_uid: cboDynaForm.getValue(), + usr_uid: cboUser.getValue(), + we_title: startMessage.evn_name, + we_description: '', + we_method: cboMethod.getValue(), + we_input_document_access: 1 + }; + + if (frmDataStartMessage.isValid()) { + updateStartMessage(data); + } + }, + buttonType: 'success', + height: 31, + visible: true + }); + btnSaveStartMessagePage = new PMUI.ui.Button({ + id: "btnGenerateStartMessagePage", + text: "Save".translate(), + handler: function () { + var flagGenerateStartMessage = 0, data; + data = { + tas_uid: startMessage.ports.get(0).connection.flo_element_dest, + dyn_uid: cboDynaForm.getValue(), + usr_uid: cboUser.getValue(), + we_title: startMessage.evn_name, + we_description: '', + we_method: cboMethod.getValue(), + we_input_document_access: 1 + }; + + if (frmDataStartMessage.isValid()) { + updateStartMessage(data); + } + }, + buttonType: 'success', + height: 31, + visible: true + }); + + frmDataStartMessage = new PMUI.form.Form({ + id: "frmDataStartMessage", + title: "", + width: DEFAULT_WINDOW_WIDTH - 70, + items: [ + cboUser, + cboDynaForm, + cboMethod + ], + visibleHeader: false + }); + + btnClose = new PMUI.ui.Button({ + id: "btnClose", + text: "Close".translate(), + handler: function () { + winGrdpnlStartMessage.close(); + }, + buttonType: 'success', + height: 31 + }); + + btnStartMessageCancel = new PMUI.ui.Button({ + id: "btnStartMessageCancel", + text: "Cancel".translate(), + handler: function () { + var message_window; + if (frmDataStartMessage.isDirty()) { + message_window = new PMUI.ui.MessageWindow({ + windowMessageType: 'warning', + id: "cancelMessageStartTimer", + title: "Start Message Event".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + bodyHeight: 'auto', + width: 490, + footerItems: [ + { + text: 'No'.translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: 'Yes'.translate(), + handler: function () { + message_window.close(); + winGrdpnlStartMessage.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + frmDataStartMessage.reset(); + winGrdpnlStartMessage.close(); + } + } + }); + + frmHtml = new PMUI.form.Form({ + id: "frmHtml", + title: "", + width: DEFAULT_WINDOW_WIDTH - 43, + items: [ + { + id: "txtHtml", + name: "txtHtml", + pmType: "textarea", + valueType: "string", + rows: 400, + value: '', + controlsWidth: DEFAULT_WINDOW_WIDTH - 50, + labelVisible: false, + style: {cssClasses: ['mafe-textarea-resize']} + } + ] + }); + + winGrdpnlStartMessage = new PMUI.ui.Window({ + id: "winGrdpnlStartMessage", + title: "Start Message Event".translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + buttonPanelPosition: "top", + buttons: [btnSaveStartMessagePage, {pmType: 'label', text: 'or'}, btnStartMessageCancel, btnClose] + }); + + winGrdpnlStartMessage.addItem(frmDataStartMessage); + + openForm = function () { + winGrdpnlStartMessage.open(); + winGrdpnlStartMessage.defineEvents(); + applyStyleWindowForm(winGrdpnlStartMessage); + winGrdpnlStartMessage.footer.html.style.textAlign = 'right'; + winFrmStartMessageShow(); + } + }; + + PMDesigner.startMessage.openForm = function (element) { + openForm(); + }; + + PMDesigner.startMessage.viewForm = function (element) { + openForm(); + }; + + PMDesigner.startMessage.validate = function (starMessageEvent) { + if (starMessageEvent.ports.isEmpty()) { + PMDesigner.msgFlash('Must connect to a Task'.translate(), document.body, 'error', 4000, 5); + return [false, false]; + } + PMDesigner.startMessage(starMessageEvent); + response = loadValuesStartMessage(true); + if (response[0] == 0) { + PMDesigner.msgFlash('The task doesn\'t have assigned users'.translate(), document.body, 'info', 4000); + return [false, false]; + } + if (response[1] == 0) { + PMDesigner.msgFlash('The task doesn\'t have assigned Dynaforms'.translate(), document.body, 'info', 4000); + return [false, false]; + } + return [true, response[2]]; + } +}()); - disableAllItems = function () { - winGrdpnlStartMessage.getItems()[0].setVisible(false); - winGrdpnlStartMessage.getItems()[1].setVisible(false); - btnGenerateStartMessagePage.setVisible(false); - btnStartMessageCancel.setVisible(false); - btnClose.setVisible(false); - winGrdpnlStartMessage.hideFooter(); - }; +(function () { + var windowPropSub; - winFrmStartMessageShow = function () { - disableAllItems(); - frmDataStartMessage.reset(); - winGrdpnlStartMessage.showFooter(); - winGrdpnlStartMessage.getItems()[0].setVisible(true); - btnGenerateStartMessagePage.setVisible(true); - btnStartMessageCancel.setVisible(true); - loadDataUsers(); - loadDataDynaform(); - loadDataForm(); - frmDataStartMessage.setFocus(); - }; + PMDesigner.propertiesSubProcess = function (activity) { + var typeVariables = ['@@', '@#', '@=', '@&'], + restClient, + isDirtyFormSubProcess, + getSubProcess, + formVarTexOriginOut, + updateSubProcess, + formVarTexOriginIn, + loadDropProcess, + formVarTexTargetOut, + formVarTexTargetIn, + windowPropertiesSub, + formProperties, + sepInputs, + gridVariablesOut, + gridVariablesIn, + formVariablesPanelOut, + formVariablesPanelIn, + validateVariable, + formVarButtonAddOut, + formVarButtonAddIn, + labelVariablesOut, + labelVariablesIn, + loadDataServer, + loadActivity, + isDirty = false; - winHtmlShow = function (msgHtml) { - if (typeof msgHtml == 'undefined') { - msgHtml = dataForm.we_data; - if (dataForm.we_method == "WS") { - window.open(msgHtml); - winGrdpnlStartMessage.close(); - return false; + restClient = new PMRestClient({ + endpoint: 'projects', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + for (var i = 0; i < response.length; i += 1) { + if (response[i].prj_uid != PMDesigner.project.projectId) { + formProperties.getField('out_doc_process').addOption({ + label: response[i].prj_name, + value: response[i].prj_uid + }); + } } - } - disableAllItems(); - winGrdpnlStartMessage.showFooter(); - winGrdpnlStartMessage.footer.getItems()[1].setVisible(false); - btnClose.setVisible(true); - winGrdpnlStartMessage.getItems()[1].setVisible(true); - winGrdpnlStartMessage.getItems()[1].setWidth(925); - winGrdpnlStartMessage.getItems()[1].setHeight(440); - winGrdpnlStartMessage.getItems()[1].hideHeader(); - frmHtml.getFields()[0].setHeight(396); - frmHtml.getItems()[0].setValue(msgHtml); - frmHtml.panel.style.addProperties({'box-sizing': 'initial'}); - frmHtml.style.addProperties({marginLeft: '16px'}); - frmHtml.setFocus(); - return true; - }; - - loadValuesStartMessage = function (flag) { - var viewFlagForm, - restClient, - response; - listUsers = []; - listDynaforms = []; - dataForm = []; - restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - calls: [ + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems getting the output documents, please try again.".translate() + }); + isDirtyFormSubProcess = function () { + var message_window; + if (formProperties.isDirty() || isDirty) { + message_window = new PMUI.ui.MessageWindow({ + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + id: "cancelSaveSubprocPropertiesWin", + title: "Sub-process Properties".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ { - url: 'activity/' + startMessage.ports.get(0).connection.flo_element_dest + '/assignee/all', - method: 'GET' + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" }, { - url: "activity/" + startMessage.ports.get(0).connection.flo_element_dest + "/steps", - method: 'GET' - }, { - url: 'web-entry/' + startMessage.evn_uid, - method: 'GET' + text: "Yes".translate(), + handler: function () { + message_window.close(); + formProperties.reset(); + gridVariablesOut.setDataItems(""); + gridVariablesIn.setDataItems(""); + formProperties.setDirty(false); + windowPropertiesSub.close(); + }, + buttonType: "success" } ] - }, - functionSuccess: function (xhr, response) { - listUsers = response[0].response; - listDynaforms = response[1].response; - dataForm = response[2].response; - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } - }); - restClient.executeRestClient(); - if (flag) { - viewFlagForm = false; - if (typeof dataForm == 'object' && dataForm.we_data != null) { - viewFlagForm = true; - } - response = [listUsers.length, listDynaforms.length, viewFlagForm]; - return response; + }); + message_window.open(); + message_window.showFooter(); + } else { + windowPropertiesSub.close(); } - return true; }; + getSubProcess = function () { + var restProxy = new PMRestClient({ + endpoint: "subprocess/" + activity.act_uid, + typeRequest: "get", + functionSuccess: function (xhr, response) { + var yout, + oout, + jout, + itemsOut, + i, + xin, + yin, + oin, + jin, + dout, + din, + itemsIn, + xout; + formProperties.getField('out_doc_title').setValue(response.spr_name); + formProperties.getField('out_doc_process').setValue(response.spr_pro); + formProperties.getField('out_doc_type').setValue(response.spr_synchronous); - updateStartMessage = function (data) { - restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - calls: [ - { - url: "web-entry/" + startMessage.evn_uid, - method: 'PUT', - data: data - }, - { - url: 'web-entry/' + startMessage.evn_uid, - method: 'GET' + if (response.spr_variables_out != false) { + xout = JSON.stringify(response.spr_variables_out); + yout = xout.substring(1, xout.length - 1); + oout = yout.replace(/"/g, ''); + jout = oout.split(','); + + itemsOut = []; + for (i = 0; i < jout.length; i += 1) { + dout = jout[i].split(':'); + itemsOut.push({ + origin: dout[0], + target: dout[1] + }); } - ] - }, - functionSuccess: function (xhr, response) { - dataForm = response[1].response; - if (data.we_method == "HTML") { - winHtmlShow(response.we_data); + gridVariablesOut.setDataItems(itemsOut); + + gridVariablesIn.setVisible(false); + formVariablesPanelIn.setVisible(false); + } + + if (response.spr_variables_in != false && response.spr_variables_in != undefined) { + xin = JSON.stringify(response.spr_variables_in); + yin = xin.substring(1, xin.length - 1); + oin = yin.replace(/"/g, ''); + jin = oin.split(','); + + itemsIn = []; + for (i = 0; i < jin.length; i += 1) { + din = jin[i].split(':'); + itemsIn.push({ + origin: din[0], + target: din[1] + }); + } + gridVariablesIn.setDataItems(itemsIn); + } + + if (response.spr_synchronous == "1") { + gridVariablesIn.setVisible(true); + formVariablesPanelIn.setVisible(true); } - btnGenerateStartMessagePage.setVisible(false); - btnStartMessageCancel.setVisible(false); - btnClose.setVisible(true); - winGrdpnlStartMessage.footer.getItems()[1].setVisible(false); }, functionFailure: function (xhr, response) { PMDesigner.msgWinError(response.error.message); - }, - messageError: ["There are problems updating the Web Entry, please try again.".translate()], - messageSuccess: ['Web Entry updated successfully'.translate()], - flashContainer: frmDataStartMessage + } }); - restClient.executeRestClient(); + restProxy.executeRestClient(); }; - loadDataDynaform = function () { - var i; - cboDynaForm.clearOptions(); - for (i = 0; i <= listDynaforms.length - 1; i++) { - if (listDynaforms[i].step_type_obj == "DYNAFORM") { - cboDynaForm.addOption({ - value: listDynaforms[i].step_uid_obj, - label: listDynaforms[i].obj_title - }); + updateSubProcess = function (data) { + var restProxy = new PMRestClient({ + endpoint: "subprocess/" + activity.act_uid, + typeRequest: "update", + data: data, + functionSuccess: function (xhr, response) { + var name = formProperties.getData().out_doc_title; + activity.setName(name); + activity.setActName(name); + PMDesigner.project.dirty = true; + + formProperties.reset(); + gridVariablesOut.setDataItems(""); + gridVariablesIn.setDataItems(""); + formProperties.setDirty(false); + windowPropertiesSub.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); } - } + }); + restProxy.executeRestClient(); }; - loadDataUsers = function () { - var i; - cboUser.clearOptions(); - for (i = 0; i <= listUsers.length - 1; i++) { - cboUser.addOption({ - value: listUsers[i].aas_uid, - label: listUsers[i].aas_name + ' ' + listUsers[i].aas_lastname - }); - } - }; + formVarTexOriginOut = new CriteriaField({ + id: 'idformVarTexOriginOut', + pmType: "text", + name: 'nmformVarTexOriginOut', + placeholder: 'Origin'.translate(), + labelVisible: false, + controlsWidth: 150 + }); - loadDataForm = function () { - cboUser.setValue(dataForm.usr_uid); - cboDynaForm.setValue(dataForm.dyn_uid); - cboMethod.setValue(dataForm.we_method); - }; + formVarTexOriginIn = new CriteriaField({ + id: 'idformVarTexOriginIn', + pmType: "text", + name: 'nmformVarTexOriginIn', + placeholder: 'Select Origin Process'.translate(), + labelVisible: false, + controlsWidth: 150 + }); - enableGenerateWebEntry = function () { - btnGenerateStartMessagePage.setVisible(true); - btnStartMessageCancel.setVisible(true); - btnClose.setVisible(false); - winGrdpnlStartMessage.footer.getItems()[1].setVisible(true); - }; - cboUser = new PMUI.field.DropDownListField({ - id: "cboUser", - name: "cboUser", - label: "User".translate(), - required: true, - options: null, - onChange: function (newVal, oldVal) { - enableGenerateWebEntry(); - }, - controlsWidth: 350 + formVarTexTargetOut = new CriteriaField({ + id: 'idformVarTexTargetOut', + pmType: "text", + name: 'nmformVarTexTargetOut', + placeholder: 'Select Target Process'.translate(), + labelVisible: false, + controlsWidth: 150, + required: true }); - cboDynaForm = new PMUI.field.DropDownListField({ - id: "cboDynaForm", - name: "cboDynaForm", - label: "Initial Dynaform".translate(), - options: null, - required: true, - onChange: function (newVal, oldVal) { - enableGenerateWebEntry(); - }, - controlsWidth: 350 + formVarTexTargetIn = new CriteriaField({ + id: 'idformVarTexTargetIn', + pmType: "text", + name: 'nmformVarTexTargetIn', + placeholder: 'Target'.translate(), + labelVisible: false, + controlsWidth: 150 }); - cboMethod = new PMUI.field.DropDownListField({ - id: "cboMethod", - name: "cboMethod", - label: "Method".translate(), - value: "WS", - options: [ + windowPropertiesSub = new PMUI.ui.Window({ + id: 'propSubWindow', + title: "Sub-process Properties".translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + bodyHeight: '465px', + bodyWidth: '900px', + onBeforeClose: function () { + isDirtyFormSubProcess(); + }, + buttons: [ { - value: "WS", - label: "PHP pages with Web Services".translate() + id: 'propSubButtonClose', + text: "Close".translate(), + buttonType: 'error', + handler: function () { + isDirtyFormSubProcess(); + } }, { - value: "HTML", - label: "Single HTML".translate() - } - ], - onChange: function (newVal, oldVal) { - enableGenerateWebEntry(); - }, - controlsWidth: 350 - }); - - btnGenerateStartMessagePage = new PMUI.ui.Button({ - id: "btnGenerateStartMessagePage", - text: "Generate Web Entry Page".translate(), - handler: function () { - var flagGenerateStartMessage = 0, data; - data = { - tas_uid: startMessage.ports.get(0).connection.flo_element_dest, - dyn_uid: cboDynaForm.getValue(), - usr_uid: cboUser.getValue(), - we_title: startMessage.evn_name, - we_description: '', - we_method: cboMethod.getValue(), - we_input_document_access: 1 - }; + id: 'propSubButtonSave', + text: "Save".translate(), + buttonType: 'success', + handler: function () { + if (!formProperties.isValid()) { + return; + } + var propertiesData = formProperties.getData(); + var variablesOutData = gridVariablesOut.getData(); + var variablesOut = {}; + if (variablesOutData.length > "0") { + for (i = 0; i < variablesOutData.length; i += 1) { + variablesOut[variablesOutData[i].origin] = variablesOutData[i].target; + } + } + var variablesIn = {}; + if (propertiesData.out_doc_type == "1") { + var variablesInData = gridVariablesIn.getData(); + if (variablesInData.length > "0") { + for (j = 0; j < variablesInData.length; j += 1) { + variablesIn[variablesInData[j].origin] = variablesInData[j].target; + } + } + } - if (frmDataStartMessage.isValid()) { - updateStartMessage(data); - } - }, - buttonType: 'success', - height: 31, - visible: true - }); - btnSaveStartMessagePage = new PMUI.ui.Button({ - id: "btnGenerateStartMessagePage", - text: "Save".translate(), - handler: function () { - var flagGenerateStartMessage = 0, data; - data = { - tas_uid: startMessage.ports.get(0).connection.flo_element_dest, - dyn_uid: cboDynaForm.getValue(), - usr_uid: cboUser.getValue(), - we_title: startMessage.evn_name, - we_description: '', - we_method: cboMethod.getValue(), - we_input_document_access: 1 - }; + var dataToSend = { + spr_pro: propertiesData.out_doc_process, + spr_tas: propertiesData.spr_tas, + spr_name: propertiesData.out_doc_title, + spr_synchronous: propertiesData.out_doc_type, + spr_variables_out: variablesOut, + spr_variables_in: variablesIn + }; - if (frmDataStartMessage.isValid()) { - updateStartMessage(data); + updateSubProcess(dataToSend); + } } - }, - buttonType: 'success', - height: 31, - visible: true + ], + buttonPanelPosition: 'bottom', + buttonsPosition: 'right' }); - frmDataStartMessage = new PMUI.form.Form({ - id: "frmDataStartMessage", + formProperties = new PMUI.form.Form({ + id: 'propSubForm', title: "", - width: DEFAULT_WINDOW_WIDTH - 70, + fieldset: true, + visibleHeader: false, + width: 926, + height: 'auto', items: [ - cboUser, - cboDynaForm, - cboMethod + { + id: 'propSubFormTitle', + pmType: "text", + name: 'out_doc_title', + label: "Sub-Process name".translate(), + required: true, + controlsWidth: 300 + }, + { + id: 'propSubFormProcess', + pmType: "dropdown", + name: 'out_doc_process', + label: "Process".translate(), + controlsWidth: 300, + required: true, + options: [ + { + label: "- Select a process -".translate(), + value: "", + disabled: true, + selected: true + } + ], + value: "", + onChange: function (a, b) { + if (a.trim().length !== 0) { + formVarTexTargetOut.buttonHTML.enable(); + formVarTexOriginIn.buttonHTML.enable(); + formVarTexTargetOut.controls[0].setPlaceholder("Target"); + formVarTexOriginIn.controls[0].setPlaceholder("Origin"); + } else { + formVarTexTargetOut.buttonHTML.disable(); + formVarTexOriginIn.buttonHTML.disable(); + } + formVarTexTargetOut.setProcess(a); + formVarTexOriginIn.setProcess(a); + loadActivity(a); + } + }, + { + id: 'propSubFormActivity', + pmType: "dropdown", + name: 'spr_tas', + label: "Starting activity".translate(), + controlsWidth: 300, + required: true, + options: [ + { + label: "- Select starting activity -".translate(), + value: "", + disabled: true, + selected: true + } + ], + value: "", + onChange: function (a, b) { + } + }, + { + id: 'propSubFormType', + pmType: "dropdown", + name: 'out_doc_type', + label: "Type".translate(), + controlsWidth: 150, + required: true, + options: [ + { + label: "Asynchronous".translate(), + value: "0" + }, + { + label: "Synchronous".translate(), + value: "1" + } + ], + value: "0", + onChange: function (a, b) { + isDirty = true; + } + } ], - visibleHeader: false + onChange: function (newValue, prevValue) { + switch (newValue.value) { + case "1" : + gridVariablesIn.setVisible(true); + gridVariablesIn.style.addProperties({marginLeft: '45px'}); + formVariablesPanelIn.setVisible(true); + formVariablesPanelIn.getItems()[2].setWidth(80); + $(formVariablesPanelIn.html).css({width: '850px', marginLeft: '45px'}); + windowPropertiesSub.getItems()[4].setVisible(true); + break; + case "0": + gridVariablesIn.setVisible(false); + formVariablesPanelIn.setVisible(false); + windowPropertiesSub.getItems()[4].setVisible(false); + break; + default : + break; + } + } }); - btnClose = new PMUI.ui.Button({ - id: "btnClose", - text: "Close".translate(), - handler: function () { - winGrdpnlStartMessage.close(); - }, - buttonType: 'success', - height: 31 - }); + sepInputs = new PMSeparatorLineField({ + controlHeight: '1px', + controlColor: "#CDCDCD", + controlsWidth: "890px", + marginLeft: '0%' + }); - btnStartMessageCancel = new PMUI.ui.Button({ - id: "btnStartMessageCancel", - text: "Cancel".translate(), - handler: function () { - var message_window; - if (frmDataStartMessage.isDirty()) { - message_window = new PMUI.ui.MessageWindow({ - windowMessageType: 'warning', - id: "cancelMessageStartTimer", - title: "Start Message Event".translate(), - message: 'Are you sure you want to discard your changes?'.translate(), - bodyHeight: 'auto', - width: 490, - footerItems: [ - { - text: 'No'.translate(), - handler: function () { - message_window.close(); - }, - buttonType: "error" - }, - { - text: 'Yes'.translate(), - handler: function () { - message_window.close(); - winGrdpnlStartMessage.close(); - }, - buttonType: "success" - } + formProperties.addItem(sepInputs); + + gridVariablesOut = new PMUI.grid.GridPanel({ + id: 'propSubGridVariablesOut', + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + pageSize: 10, + style: { + cssClasses: ["mafe-gridPanel"] + }, + columns: [ + { + title: 'Origin'.translate(), + dataType: 'string', + width: '40%', + alignmentCell: 'left', + columnData: "origin" + }, + { + title: 'Target'.translate(), + dataType: 'string', + width: '40%', + alignmentCell: 'left', + columnData: "target" + }, + { + id: 'propSubGridVariablesOutButtonDelete', + title: '', + dataType: 'button', + width: '20%', + buttonLabel: 'Delete'.translate(), + onButtonClick: function (row, grid) { + grid.removeItem(row); + isDirty = true; + }, + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' ] - }); - message_window.open(); - message_window.showFooter(); - } else { - frmDataStartMessage.reset(); - winGrdpnlStartMessage.close(); + } + } - } + ] }); - frmHtml = new PMUI.form.Form({ - id: "frmHtml", - title: "", - width: DEFAULT_WINDOW_WIDTH - 43, - items: [ + gridVariablesIn = new PMUI.grid.GridPanel({ + id: 'propSubGridVariablesIn', + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + pageSize: 10, + columns: [ { - id: "txtHtml", - name: "txtHtml", - pmType: "textarea", - valueType: "string", - rows: 400, - value: '', - controlsWidth: DEFAULT_WINDOW_WIDTH - 50, - labelVisible: false, - style: {cssClasses: ['mafe-textarea-resize']} + title: 'Origin'.translate(), + dataType: 'string', + width: '40%', + alignmentCell: 'left', + columnData: "origin" + }, + { + title: 'Target'.translate(), + dataType: 'string', + width: '40%', + alignmentCell: 'left', + columnData: "target" + }, + { + id: 'propSubGridVariablesInButtonDelete', + title: '', + dataType: 'button', + width: '20%', + buttonLabel: 'Delete'.translate(), + onButtonClick: function (row, grid) { + grid.removeItem(row); + isDirty = true; + }, + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + } } ] }); - winGrdpnlStartMessage = new PMUI.ui.Window({ - id: "winGrdpnlStartMessage", - title: "Start Message Event".translate(), - height: DEFAULT_WINDOW_HEIGHT, - width: DEFAULT_WINDOW_WIDTH, - buttonPanelPosition: "top", - buttons: [btnSaveStartMessagePage, {pmType: 'label', text: 'or'}, btnStartMessageCancel, btnClose] + formVariablesPanelOut = new PMUI.core.Panel({ + id: "formVariablesPanelOut", + layout: "hbox", + fieldset: true, + width: DEFAULT_WINDOW_WIDTH - 70 }); - winGrdpnlStartMessage.addItem(frmDataStartMessage); + formVariablesPanelIn = new PMUI.core.Panel({ + id: "formVariablesPanelIn", + layout: "hbox", + fieldset: true, + legend: "Variables In".translate(), + width: DEFAULT_WINDOW_WIDTH - 70 + }); - openForm = function () { - winGrdpnlStartMessage.open(); - winGrdpnlStartMessage.defineEvents(); - applyStyleWindowForm(winGrdpnlStartMessage); - winGrdpnlStartMessage.footer.html.style.textAlign = 'right'; - winFrmStartMessageShow(); - } - }; + validateVariable = function (field) { + var value; + field.controls[0].style.removeClasses(['error']) + value = field.getValue(); + if (value == '') { + PMDesigner.msgWinWarning('Please insert variable before adding to the list.'.translate()); + field.controls[0].style.addClasses(['error']) + return false; + } + if (typeVariables.indexOf(String(value.substring(0, 2))) != -1) { + return true; + } + PMDesigner.msgWinWarning("The value introduced doesn\'t have the correct format with a vallid prefix (@@, @#, @=, @&)".translate()); + field.controls[0].style.addClasses(['error']) + return false; + }; - PMDesigner.startMessage.openForm = function (element) { - openForm(); - }; + formVarButtonAddOut = new PMUI.ui.Button({ + id: 'formVarButtonAddOut', + text: 'Add'.translate(), + width: 60, + visible: false, + buttonType: "success", + buttonStyle: { + cssClasses: [ + 'mafe-button-properties' + ] + }, + style: { + cssProperties: { + padding: "5px" + } + }, + handler: function () { + var gridOut, i; + if (validateVariable(formVarTexOriginOut) && validateVariable(formVarTexTargetOut)) { + a = formVarTexOriginOut.getValue(); + b = formVarTexTargetOut.getValue(); + gridVariablesOut.addDataItem({origin: a, target: b}); + formVarTexOriginOut.setValue(""); + formVarTexTargetOut.setValue(""); + isDirty = true; - PMDesigner.startMessage.viewForm = function (element) { - openForm(); - }; + gridOut = document.getElementById("propSubGridVariablesOut").getElementsByTagName("table")[0]; + i = gridOut.rows.length - 1; + gridOut.getElementsByClassName("pmui pmui-button")[i].style.marginTop = "2px"; + } + } + }); - PMDesigner.startMessage.validate = function (starMessageEvent) { - if (starMessageEvent.ports.isEmpty()) { - PMDesigner.msgFlash('Must connect to a Task'.translate(), document.body, 'error', 4000, 5); - return [false, false]; - } - PMDesigner.startMessage(starMessageEvent); - response = loadValuesStartMessage(true); - if (response[0] == 0) { - PMDesigner.msgFlash('The task doesn\'t have assigned users'.translate(), document.body, 'info', 4000); - return [false, false]; - } - if (response[1] == 0) { - PMDesigner.msgFlash('The task doesn\'t have assigned Dynaforms'.translate(), document.body, 'info', 4000); - return [false, false]; - } - return [true, response[2]]; - } -}()); + formVarButtonAddIn = new PMUI.ui.Button({ + id: 'formVarButtonAddIn', + text: 'Add'.translate(), + width: 60, + buttonStyle: { + cssClasses: [ + 'mafe-button-properties' + ] + }, + style: { + cssProperties: { + padding: "5px", + } + }, + buttonType: 'success', + handler: function () { + var gridOut, i; + if (validateVariable(formVarTexOriginIn) && validateVariable(formVarTexTargetIn)) { + a = formVarTexOriginIn.getValue(); + b = formVarTexTargetIn.getValue(); + gridVariablesIn.addDataItem({origin: a, target: b}); + formVarTexOriginIn.setValue(""); + formVarTexTargetIn.setValue(""); + isDirty = true; -(function () { - var windowPropSub; + gridOut = document.getElementById("propSubGridVariablesIn").getElementsByTagName("table")[0]; + i = gridOut.rows.length - 1; + gridOut.getElementsByClassName("pmui pmui-button")[i].style.marginTop = "2px"; + } + } + }); - PMDesigner.propertiesSubProcess = function (activity) { - var typeVariables = ['@@', '@#', '@=', '@&'], - restClient, - isDirtyFormSubProcess, - getSubProcess, - formVarTexOriginOut, - updateSubProcess, - formVarTexOriginIn, - loadDropProcess, - formVarTexTargetOut, - formVarTexTargetIn, - windowPropertiesSub, - formProperties, - sepInputs, - gridVariablesOut, - gridVariablesIn, - formVariablesPanelOut, - formVariablesPanelIn, - validateVariable, - formVarButtonAddOut, - formVarButtonAddIn, - labelVariablesOut, - labelVariablesIn, - loadDataServer, - loadActivity, - isDirty = false; + labelVariablesOut = new PMUI.ui.TextLabel({ + textMode: 'plain', + text: 'Variables Out'.translate() + }); - restClient = new PMRestClient({ - endpoint: 'projects', - typeRequest: 'get', - functionSuccess: function (xhr, response) { - for (var i = 0; i < response.length; i += 1) { - if (response[i].prj_uid != PMDesigner.project.projectId) { - formProperties.getField('out_doc_process').addOption({ - label: response[i].prj_name, - value: response[i].prj_uid - }); - } - } - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: "There are problems getting the output documents, please try again.".translate() + labelVariablesIn = new PMUI.ui.TextLabel({ + textMode: 'plain', + text: 'Variables In'.translate() }); - isDirtyFormSubProcess = function () { - var message_window; - if (formProperties.isDirty() || isDirty) { - message_window = new PMUI.ui.MessageWindow({ - windowMessageType: 'warning', - width: 490, - bodyHeight: 'auto', - id: "cancelSaveSubprocPropertiesWin", - title: "Sub-process Properties".translate(), - message: 'Are you sure you want to discard your changes?'.translate(), - footerItems: [ + + loadDropProcess = function () { + formProperties.getField('out_doc_process').clearOptions(); + formProperties.getField('out_doc_process').addOption({ + label: "- Select a process -".translate(), + value: "", + disabled: true, + selected: true + }); + }; + loadDataServer = function () { + var restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ { - text: "No".translate(), - handler: function () { - message_window.close(); - }, - buttonType: "error" + url: 'projects', + method: 'GET' }, { - text: "Yes".translate(), - handler: function () { - message_window.close(); - formProperties.reset(); - gridVariablesOut.setDataItems(""); - gridVariablesIn.setDataItems(""); - formProperties.setDirty(false); - windowPropertiesSub.close(); - }, - buttonType: "success" + url: 'project/' + PMDesigner.project.id + '/subprocess/' + activity.act_uid, + method: 'GET' } ] - }); - message_window.open(); - message_window.showFooter(); - } else { - windowPropertiesSub.close(); - } - }; - getSubProcess = function () { - var restProxy = new PMRestClient({ - endpoint: "subprocess/" + activity.act_uid, - typeRequest: "get", + }, functionSuccess: function (xhr, response) { - var yout, + var dt, + itemsOut, + yout, oout, jout, - itemsOut, - i, + dout, xin, yin, oin, jin, - dout, din, itemsIn, xout; - formProperties.getField('out_doc_title').setValue(response.spr_name); - formProperties.getField('out_doc_process').setValue(response.spr_pro); - formProperties.getField('out_doc_type').setValue(response.spr_synchronous); - if (response.spr_variables_out != false) { - xout = JSON.stringify(response.spr_variables_out); - yout = xout.substring(1, xout.length - 1); - oout = yout.replace(/"/g, ''); - jout = oout.split(','); + //projects + dt = response[0].response; + for (var i = 0; i < dt.length; i += 1) { + if (dt[i].prj_uid !== PMDesigner.project.projectId) { + formProperties.getField('out_doc_process').addOption({ + label: dt[i].prj_name, + value: dt[i].prj_uid + }); + } + } + //subprocess + dt = response[1].response; + formProperties.getField('out_doc_title').setValue(dt.spr_name); + formProperties.getField('out_doc_process').setValue(dt.spr_pro === '0' ? '' : dt.spr_pro); + formProperties.getField('out_doc_type').setValue(dt.spr_synchronous); + if (dt.spr_variables_out !== false) { //Asynchronous + xout = JSON.stringify(dt.spr_variables_out); itemsOut = []; - for (i = 0; i < jout.length; i += 1) { - dout = jout[i].split(':'); - itemsOut.push({ - origin: dout[0], - target: dout[1] - }); + if (xout != "[]") { + yout = xout.substring(1, xout.length - 1); + oout = yout.replace(/"/g, ''); + jout = oout.split(','); + for (i = 0; i < jout.length; i += 1) { + dout = jout[i].split(':'); + itemsOut.push({ + origin: dout[0], + target: dout[1] + }); + } } gridVariablesOut.setDataItems(itemsOut); - gridVariablesIn.setVisible(false); formVariablesPanelIn.setVisible(false); } - if (response.spr_variables_in != false && response.spr_variables_in != undefined) { - xin = JSON.stringify(response.spr_variables_in); - yin = xin.substring(1, xin.length - 1); - oin = yin.replace(/"/g, ''); - jin = oin.split(','); - + if (dt.spr_variables_in !== false && dt.spr_variables_in !== undefined) { //Synchronous + xin = JSON.stringify(dt.spr_variables_in); itemsIn = []; - for (i = 0; i < jin.length; i += 1) { - din = jin[i].split(':'); - itemsIn.push({ - origin: din[0], - target: din[1] - }); + if (xin != "[]") { + yin = xin.substring(1, xin.length - 1); + oin = yin.replace(/"/g, ''); + jin = oin.split(','); + for (i = 0; i < jin.length; i += 1) { + din = jin[i].split(':'); + itemsIn.push({ + origin: din[0], + target: din[1] + }); + } } gridVariablesIn.setDataItems(itemsIn); } - if (response.spr_synchronous == "1") { + if (dt.spr_synchronous === "1") { gridVariablesIn.setVisible(true); formVariablesPanelIn.setVisible(true); } + if (formProperties.getField('out_doc_process').getValue() !== '') { + loadActivity(formProperties.getField('out_doc_process').getValue()); + } + formProperties.getField('spr_tas').setValue(dt.spr_tas === '0' ? '' : dt.spr_tas); }, functionFailure: function (xhr, response) { PMDesigner.msgWinError(response.error.message); } }); - restProxy.executeRestClient(); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); }; - - updateSubProcess = function (data) { - var restProxy = new PMRestClient({ - endpoint: "subprocess/" + activity.act_uid, - typeRequest: "update", - data: data, + loadActivity = function (value) { + var restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'project/' + value + '/starting-tasks', + method: 'GET' + } + ] + }, functionSuccess: function (xhr, response) { - var name = formProperties.getData().out_doc_title; - activity.setName(name); - activity.setActName(name); - PMDesigner.project.dirty = true; - - formProperties.reset(); - gridVariablesOut.setDataItems(""); - gridVariablesIn.setDataItems(""); - formProperties.setDirty(false); - windowPropertiesSub.close(); + var dropdown, + i, + dt = response[0].response; + dt = dt.sort(function (a, b) { + return a.act_name.toString().toLowerCase() > b.act_name.toString().toLowerCase(); + }); + dropdown = formProperties.getField('spr_tas'); + dropdown.clearOptions(); + dropdown.addOption({ + value: '', + label: '- Select starting activity -'.translate() + }); + for (i = 0; i < dt.length; i += 1) { + dropdown.addOption({ + value: dt[i].act_uid, + label: dt[i].act_name + }); + } }, functionFailure: function (xhr, response) { PMDesigner.msgWinError(response.error.message); } }); - restProxy.executeRestClient(); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); }; - formVarTexOriginOut = new CriteriaField({ - id: 'idformVarTexOriginOut', - pmType: "text", - name: 'nmformVarTexOriginOut', - placeholder: 'Origin'.translate(), - labelVisible: false, - controlsWidth: 150 - }); - - formVarTexOriginIn = new CriteriaField({ - id: 'idformVarTexOriginIn', - pmType: "text", - name: 'nmformVarTexOriginIn', - placeholder: 'Select Origin Process'.translate(), - labelVisible: false, - controlsWidth: 150 - }); + formVariablesPanelOut.addItem(formVarTexOriginOut); + formVariablesPanelOut.addItem(formVarTexTargetOut); + formVariablesPanelOut.addItem(formVarButtonAddOut); - formVarTexTargetOut = new CriteriaField({ - id: 'idformVarTexTargetOut', - pmType: "text", - name: 'nmformVarTexTargetOut', - placeholder: 'Select Target Process'.translate(), - labelVisible: false, - controlsWidth: 150, - required: true - }); + formVariablesPanelIn.addItem(formVarTexOriginIn); + formVariablesPanelIn.addItem(formVarTexTargetIn); + formVariablesPanelIn.addItem(formVarButtonAddIn); - formVarTexTargetIn = new CriteriaField({ - id: 'idformVarTexTargetIn', - pmType: "text", - name: 'nmformVarTexTargetIn', - placeholder: 'Target'.translate(), - labelVisible: false, - controlsWidth: 150 - }); + gridVariablesIn.setVisible(false); + formVariablesPanelIn.setVisible(false); - windowPropertiesSub = new PMUI.ui.Window({ - id: 'propSubWindow', - title: "Sub-process Properties".translate(), - height: DEFAULT_WINDOW_HEIGHT, - width: DEFAULT_WINDOW_WIDTH, - bodyHeight: '465px', - bodyWidth: '900px', - onBeforeClose: function () { - isDirtyFormSubProcess(); + windowPropertiesSub.addItem(formProperties); + windowPropertiesSub.addItem(new PMUI.ui.TextLabel({ + width: 890, + text: 'Variables Out'.translate(), + style: { + cssProperties: { + background: '#aaaaaa', + margin: '-15px 10px 10px 15px', + color: 'white', + padding: '6px', + 'font-weight': 'bold' + } }, - buttons: [ - { - id: 'propSubButtonClose', - text: "Close".translate(), - buttonType: 'error', - handler: function () { - isDirtyFormSubProcess(); - } - }, - { - id: 'propSubButtonSave', - text: "Save".translate(), - buttonType: 'success', - handler: function () { - if (!formProperties.isValid()) { - return; - } - var propertiesData = formProperties.getData(); - var variablesOutData = gridVariablesOut.getData(); - var variablesOut = {}; - if (variablesOutData.length > "0") { - for (i = 0; i < variablesOutData.length; i += 1) { - variablesOut[variablesOutData[i].origin] = variablesOutData[i].target; - } - } - var variablesIn = {}; - if (propertiesData.out_doc_type == "1") { - var variablesInData = gridVariablesIn.getData(); - if (variablesInData.length > "0") { - for (j = 0; j < variablesInData.length; j += 1) { - variablesIn[variablesInData[j].origin] = variablesInData[j].target; - } - } - } - - var dataToSend = { - spr_pro: propertiesData.out_doc_process, - spr_tas: propertiesData.spr_tas, - spr_name: propertiesData.out_doc_title, - spr_synchronous: propertiesData.out_doc_type, - spr_variables_out: variablesOut, - spr_variables_in: variablesIn - }; + display: 'block' + })); + windowPropertiesSub.addItem(formVariablesPanelOut); + windowPropertiesSub.addItem(gridVariablesOut); - updateSubProcess(dataToSend); - } + windowPropertiesSub.addItem(new PMUI.ui.TextLabel({ + width: 890, + text: 'Variables In'.translate(), + style: { + cssProperties: { + background: '#aaaaaa', + margin: '15px 10px 10px 15px', + color: 'white', + padding: '6px', + 'font-weight': 'bold' } - ], - buttonPanelPosition: 'bottom', - buttonsPosition: 'right' - }); + }, + display: 'block', + visible: false + })); - formProperties = new PMUI.form.Form({ - id: 'propSubForm', - title: "", - fieldset: true, - visibleHeader: false, - width: 926, - height: 'auto', - items: [ - { - id: 'propSubFormTitle', - pmType: "text", - name: 'out_doc_title', - label: "Sub-Process name".translate(), - required: true, - controlsWidth: 300 - }, - { - id: 'propSubFormProcess', - pmType: "dropdown", - name: 'out_doc_process', - label: "Process".translate(), - controlsWidth: 300, - required: true, - options: [ - { - label: "- Select a process -".translate(), - value: "", - disabled: true, - selected: true - } - ], - value: "", - onChange: function (a, b) { - if (a.trim().length !== 0) { - formVarTexTargetOut.buttonHTML.enable(); - formVarTexOriginIn.buttonHTML.enable(); - formVarTexTargetOut.controls[0].setPlaceholder("Target"); - formVarTexOriginIn.controls[0].setPlaceholder("Origin"); - } else { - formVarTexTargetOut.buttonHTML.disable(); - formVarTexOriginIn.buttonHTML.disable(); - } - formVarTexTargetOut.setProcess(a); - formVarTexOriginIn.setProcess(a); - loadActivity(a); - } - }, - { - id: 'propSubFormActivity', - pmType: "dropdown", - name: 'spr_tas', - label: "Starting activity".translate(), - controlsWidth: 300, - required: true, - options: [ - { - label: "- Select starting activity -".translate(), - value: "", - disabled: true, - selected: true - } - ], - value: "", - onChange: function (a, b) { - } - }, - { - id: 'propSubFormType', - pmType: "dropdown", - name: 'out_doc_type', - label: "Type".translate(), - controlsWidth: 150, - required: true, - options: [ - { - label: "Asynchronous".translate(), - value: "0" - }, - { - label: "Synchronous".translate(), - value: "1" - } - ], - value: "0", - onChange: function (a, b) { - isDirty = true; - } - } - ], - onChange: function (newValue, prevValue) { - switch (newValue.value) { - case "1" : - gridVariablesIn.setVisible(true); - gridVariablesIn.style.addProperties({marginLeft: '45px'}); - formVariablesPanelIn.setVisible(true); - formVariablesPanelIn.getItems()[2].setWidth(80); - $(formVariablesPanelIn.html).css({width: '850px', marginLeft: '45px'}); - windowPropertiesSub.getItems()[4].setVisible(true); - break; - case "0": - gridVariablesIn.setVisible(false); - formVariablesPanelIn.setVisible(false); - windowPropertiesSub.getItems()[4].setVisible(false); - break; - default : - break; - } - } - }); + windowPropertiesSub.addItem(formVariablesPanelIn); + windowPropertiesSub.addItem(gridVariablesIn); - sepInputs = new PMSeparatorLineField({ - controlHeight: '1px', - controlColor: "#CDCDCD", - controlsWidth: "890px", - marginLeft: '0%' - }); + loadDropProcess(); + gridVariablesOut.setDataItems(""); + gridVariablesIn.setDataItems(""); + loadDataServer(); - formProperties.addItem(sepInputs); + if (formProperties.getItems()[1].getValue() != "0") { + formVarTexTargetOut.setProcess(formProperties.getItems()[1].getValue()); + formVarTexOriginIn.setProcess(formProperties.getItems()[1].getValue()); + } + windowPropertiesSub.open(); + if (formProperties.getField('out_doc_process').getValue().trim().length === 0) { + formVarTexTargetOut.buttonHTML.disable(); + formVarTexOriginIn.buttonHTML.disable(); + } else { + formVarTexTargetOut.buttonHTML.enable(); + formVarTexOriginIn.buttonHTML.enable(); + } + windowPropertiesSub.showFooter(); + applyStyleWindowForm(windowPropertiesSub); + formVariablesPanelIn.getItems()[0].dom.labelTextContainer.style.display = "none"; + formVariablesPanelIn.getItems()[1].dom.labelTextContainer.style.display = "none"; + formVariablesPanelOut.getItems()[0].dom.labelTextContainer.style.display = "none"; + formVariablesPanelOut.getItems()[1].dom.labelTextContainer.style.display = "none"; + formVariablesPanelOut.style.addProperties({marginLeft: '45px'}); + gridVariablesOut.style.addProperties({marginLeft: '45px'}); + if (formVariablesPanelIn.visible == true) { + gridVariablesIn.setVisible(true); + gridVariablesIn.style.addProperties({marginLeft: '45px'}); + formVariablesPanelIn.setVisible(true); + formVariablesPanelIn.getItems()[2].setWidth(80); + $(formVariablesPanelIn.html).css({width: '850px', marginLeft: '45px'}); + windowPropertiesSub.getItems()[4].setVisible(true); + } - gridVariablesOut = new PMUI.grid.GridPanel({ - id: 'propSubGridVariablesOut', - emptyMessage: 'No records found'.translate(), - nextLabel: 'Next'.translate(), - previousLabel: 'Previous'.translate(), - customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { - return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); - }, - pageSize: 10, - style: { - cssClasses: ["mafe-gridPanel"] - }, - columns: [ - { - title: 'Origin'.translate(), - dataType: 'string', - width: '40%', - alignmentCell: 'left', - columnData: "origin" - }, - { - title: 'Target'.translate(), - dataType: 'string', - width: '40%', - alignmentCell: 'left', - columnData: "target" - }, - { - id: 'propSubGridVariablesOutButtonDelete', - title: '', - dataType: 'button', - width: '20%', - buttonLabel: 'Delete'.translate(), - onButtonClick: function (row, grid) { - grid.removeItem(row); - isDirty = true; - }, - buttonStyle: { - cssClasses: [ - 'mafe-button-delete' - ] - } - - } - ] - }); - - gridVariablesIn = new PMUI.grid.GridPanel({ - id: 'propSubGridVariablesIn', - emptyMessage: 'No records found'.translate(), - nextLabel: 'Next'.translate(), - previousLabel: 'Previous'.translate(), - customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { - return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); - }, - pageSize: 10, - columns: [ - { - title: 'Origin'.translate(), - dataType: 'string', - width: '40%', - alignmentCell: 'left', - columnData: "origin" - }, - { - title: 'Target'.translate(), - dataType: 'string', - width: '40%', - alignmentCell: 'left', - columnData: "target" - }, - { - id: 'propSubGridVariablesInButtonDelete', - title: '', - dataType: 'button', - width: '20%', - buttonLabel: 'Delete'.translate(), - onButtonClick: function (row, grid) { - grid.removeItem(row); - isDirty = true; - }, - buttonStyle: { - cssClasses: [ - 'mafe-button-delete' - ] - } - } - ] - }); - - formVariablesPanelOut = new PMUI.core.Panel({ - id: "formVariablesPanelOut", - layout: "hbox", - fieldset: true, - width: DEFAULT_WINDOW_WIDTH - 70 - }); - - formVariablesPanelIn = new PMUI.core.Panel({ - id: "formVariablesPanelIn", - layout: "hbox", - fieldset: true, - legend: "Variables In".translate(), - width: DEFAULT_WINDOW_WIDTH - 70 - }); + formVariablesPanelOut.style.addProperties({width: '870px'}); + $(gridVariablesIn.html).find(".pmui-gridpanel-footer").css("position", "static"); + $(gridVariablesIn.html).find(".pmui-gridpanel-footer").css("margin-top", "0px"); + $(gridVariablesOut.html).find(".pmui-gridpanel-footer").css("position", "static"); + $(gridVariablesOut.html).find(".pmui-gridpanel-footer").css("margin-top", "0px"); + windowPropertiesSub.defineEvents(); + gridVariablesOut.html.children[0].style.display = "none"; + gridVariablesIn.html.children[0].style.display = "none"; + formProperties.getField('out_doc_title').setFocus(); + formVarButtonAddOut.setWidth(80); + formVarButtonAddOut.setVisible(true); - validateVariable = function (field) { - var value; - field.controls[0].style.removeClasses(['error']) - value = field.getValue(); - if (value == '') { - PMDesigner.msgWinWarning('Please insert variable before adding to the list.'.translate()); - field.controls[0].style.addClasses(['error']) - return false; - } - if (typeVariables.indexOf(String(value.substring(0, 2))) != -1) { - return true; + }; +}()); +if (typeof(consolidated) == 'undefined') { + consolidated = '0'; +} +PMDesigner.activityProperties = function (activity) { + switch (activity.getActivityType()) { + case "SUB_PROCESS": + PMDesigner.propertiesSubProcess(activity); + break; + case "TASK": + if (activity.getTaskType() === "SCRIPTTASK") { + PMDesigner.scriptTaskProperties(activity); + } else { + PMDesigner.taskProperties(activity); } - PMDesigner.msgWinWarning("The value introduced doesn\'t have the correct format with a vallid prefix (@@, @#, @=, @&)".translate()); - field.controls[0].style.addClasses(['error']) - return false; - }; + break; + } +}; - formVarButtonAddOut = new PMUI.ui.Button({ - id: 'formVarButtonAddOut', - text: 'Add'.translate(), - width: 60, - visible: false, - buttonType: "success", - buttonStyle: { - cssClasses: [ - 'mafe-button-properties' - ] - }, - style: { - cssProperties: { - padding: "5px" - } - }, - handler: function () { - var gridOut, i; - if (validateVariable(formVarTexOriginOut) && validateVariable(formVarTexTargetOut)) { - a = formVarTexOriginOut.getValue(); - b = formVarTexTargetOut.getValue(); - gridVariablesOut.addDataItem({origin: a, target: b}); - formVarTexOriginOut.setValue(""); - formVarTexTargetOut.setValue(""); - isDirty = true; +PMDesigner.taskProperties = function (activity) { + var formDefinitions, + featuresForms = [], + propertiesTabs, + formCaseLabels, + dataProperties, + formTimingControl, + configurationForms, + customGrid, + formNotifications, + buttonFieldCancel, + buttonFieldAdd, + abeForm, + MobilePanel, + enableTaskMobile, + routeCaseMobile, + abeMainPanel, + abeAddOption, + abeTemplates, + abeDynaforms, + abeEmailAcount, + abeFields, + warningChanges, + windowProperties, + processDataProperties, + i, + editRow = null, + arrayTrue = '["TRUE"]', + arrayFalse = '["FALSE"]', + stringTrue = "TRUE", + stringFalse = "FALSE", + defaultServerlabel = "Mail (PHP)".translate(); - gridOut = document.getElementById("propSubGridVariablesOut").getElementsByTagName("table")[0]; - i = gridOut.rows.length - 1; - gridOut.getElementsByClassName("pmui pmui-button")[i].style.marginTop = "2px"; + configurationForms = [ + { + id: 'windowPropertiesTabPanelDefinitions', + icon: '', + title: 'Definitions'.translate(), + panel: formDefinitions = new PMUI.form.Form({ + id: 'formDefinitions', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 250, + items: [{ + id: 'formDefinitionsUID', + pmType: 'text', + name: 'UID', + valueType: 'string', + label: 'UID'.translate(), + controlsWidth: 300 + }, { + id: 'formDefinitionsTitle', + pmType: 'text', + name: 'tas_title', + valueType: 'string', + label: 'Title'.translate(), + placeholder: 'Insert a title'.translate(), + required: true, + controlsWidth: 300 + }, { + id: 'formDefinitionsDescription', + pmType: 'textarea', + name: 'tas_description', + valueType: 'string', + label: 'Description'.translate(), + placeholder: 'Insert a description'.translate(), + rows: 100, + controlsWidth: 300, + style: {cssClasses: ['mafe-textarea-resize']} + }, new CriteriaField({ + id: 'formDefinitionsVariable', + pmType: 'text', + name: 'tas_priority_variable', + valueType: 'string', + label: 'Variable for Case priority'.translate(), + controlsWidth: 300 + }), { + id: 'formDefinitionsRouting', + pmType: 'dropdown', + name: 'tas_derivation_screen_tpl', + valueType: 'string', + label: 'Routing Screen Template'.translate(), + controlsWidth: 150, + style: { + cssProperties: { + float: "left" + } + } } - } - }); - - formVarButtonAddIn = new PMUI.ui.Button({ - id: 'formVarButtonAddIn', - text: 'Add'.translate(), - width: 60, - buttonStyle: { - cssClasses: [ - 'mafe-button-properties' ] - }, - style: { - cssProperties: { - padding: "5px", - } - }, - buttonType: 'success', - handler: function () { - var gridOut, i; - if (validateVariable(formVarTexOriginIn) && validateVariable(formVarTexTargetIn)) { - a = formVarTexOriginIn.getValue(); - b = formVarTexTargetIn.getValue(); - gridVariablesIn.addDataItem({origin: a, target: b}); - formVarTexOriginIn.setValue(""); - formVarTexTargetIn.setValue(""); - isDirty = true; - - gridOut = document.getElementById("propSubGridVariablesIn").getElementsByTagName("table")[0]; - i = gridOut.rows.length - 1; - gridOut.getElementsByClassName("pmui pmui-button")[i].style.marginTop = "2px"; - } - } - }); - - labelVariablesOut = new PMUI.ui.TextLabel({ - textMode: 'plain', - text: 'Variables Out'.translate() - }); - - labelVariablesIn = new PMUI.ui.TextLabel({ - textMode: 'plain', - text: 'Variables In'.translate() - }); - - loadDropProcess = function () { - formProperties.getField('out_doc_process').clearOptions(); - formProperties.getField('out_doc_process').addOption({ - label: "- Select a process -".translate(), - value: "", - disabled: true, - selected: true - }); - }; - loadDataServer = function () { - var restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - calls: [ + }) + }, + { + id: 'windowPropertiesTabPanelCaseLabels', + icon: '', + title: 'Case Labels'.translate(), + panel: formCaseLabels = new PMUI.form.Form({ + id: 'formCaseLabels', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 250, + items: [new CriteriaField({ + id: 'formCaseLabelsTitle', + pmType: 'text', + name: 'tas_def_title', + valueType: 'string', + label: 'Title'.translate(), + placeholder: 'Insert a title'.translate(), + controlsWidth: DEFAULT_WINDOW_WIDTH - 527 + }), new CriteriaField({ + id: 'formCaseLabelsDescription', + pmType: 'textarea', + name: 'tas_def_description', + valueType: 'string', + label: 'Description'.translate(), + placeholder: 'Insert a description'.translate(), + rows: 100, + controlsWidth: DEFAULT_WINDOW_WIDTH - 527, + renderType: 'textarea' + }) + ] + }) + }, + { + id: 'windowPropertiesTabPanelTimingControl', + icon: '', + title: 'Timing Control'.translate(), + panel: formTimingControl = new PMUI.form.Form({ + id: 'formTimingControl', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 250, + items: [{ + id: 'formTimingControlFly', + pmType: 'checkbox', + name: 'tas_transfer_fly', + labelVisible: false, + options: [ { - url: 'projects', - method: 'GET' + id: 'formTimingControlOption', + label: 'Allow users to change the task duration in runtime'.translate(), + value: '1' + } + ], + onChange: function (val) { + changeTimingControl(this.controls[0].selected); + } + }, { + id: 'formTimingMainPanel', + pmType: 'panel', + items: [ + { + id: 'formTimingControlTask', + pmType: 'text', + name: 'tas_duration', + valueType: 'string', + label: 'Task duration'.translate(), + required: true, + maxLength: 3, + controlsWidth: 200, + validators: [ + { + pmType: "regexp", + criteria: /^\d*$/, + errorMessage: "Please enter a positive integer value".translate() + } + ] }, { - url: 'project/' + PMDesigner.project.id + '/subprocess/' + activity.act_uid, - method: 'GET' + id: 'formTimingControlAverage', + pmType: 'text', + name: 'tas_average', + valueType: 'string', + label: 'Average'.translate(), + maxLength: 3, + readOnly: true, + controlsWidth: 200 + }, + { + id: 'formTimingControlSdv', + pmType: 'text', + name: 'tas_sdv', + valueType: 'string', + label: 'SDV'.translate(), + maxLength: 3, + readOnly: true, + controlsWidth: 200 + }, + { + id: 'formTimingControlTime', + pmType: 'dropdown', + name: 'tas_timeunit', + label: 'Time unit'.translate(), + controlsWidth: 100, + options: [{ + id: 'formTimingControlTime1', + label: 'Hours'.translate(), + value: 'HOURS' + }, { + id: 'formTimingControlTime2', + label: 'Days'.translate(), + value: 'DAYS' + }, { + id: 'formTimingControlTime3', + label: 'Minutes'.translate(), + value: 'MINUTES' + } + ] + }, { + id: 'formTimingControlCount', + pmType: 'dropdown', + name: 'tas_type_day', + label: 'Count days by'.translate(), + controlsWidth: 150, + options: [{ + id: 'formTimingControlCount1', + label: 'Work Days'.translate(), + value: 1 + }, { + id: 'formTimingControlCount2', + label: 'Calendar Days'.translate(), + value: 2 + } + ] + }, { + id: 'formTimingControlCalendar', + pmType: 'dropdown', + name: 'tas_calendar', + label: 'Calendar'.translate(), + options: [], + controlsWidth: 150 } ] - }, - functionSuccess: function (xhr, response) { - var dt, - itemsOut, - yout, - oout, - jout, - dout, - xin, - yin, - oin, - jin, - din, - itemsIn, - xout; - - //projects - dt = response[0].response; - for (var i = 0; i < dt.length; i += 1) { - if (dt[i].prj_uid !== PMDesigner.project.projectId) { - formProperties.getField('out_doc_process').addOption({ - label: dt[i].prj_name, - value: dt[i].prj_uid - }); + } + ] + }) + }, + { + id: 'windowPropertiesTabPanelNotifications', + icon: '', + title: 'Notifications'.translate(), + panel: formNotifications = new PMUI.form.Form({ + id: 'formNotifications', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 250, + items: [ + { + id: 'formNotificationsTasSend', + pmType: 'checkbox', + name: 'tas_send_last_email', + labelVisible: false, + options: [{ + id: 'formNotificationsTasSend1', + label: 'After routing notify the next assigned user(s)'.translate(), + value: '1' } - } - //subprocess - dt = response[1].response; - formProperties.getField('out_doc_title').setValue(dt.spr_name); - formProperties.getField('out_doc_process').setValue(dt.spr_pro === '0' ? '' : dt.spr_pro); - formProperties.getField('out_doc_type').setValue(dt.spr_synchronous); - - if (dt.spr_variables_out !== false) { //Asynchronous - xout = JSON.stringify(dt.spr_variables_out); - itemsOut = []; - if (xout != "[]") { - yout = xout.substring(1, xout.length - 1); - oout = yout.replace(/"/g, ''); - jout = oout.split(','); - for (i = 0; i < jout.length; i += 1) { - dout = jout[i].split(':'); - itemsOut.push({ - origin: dout[0], - target: dout[1] - }); - } + ], + onChange: function (val) { + changeFormNotifications(this.controls[0].selected, 'text'); } - gridVariablesOut.setDataItems(itemsOut); - gridVariablesIn.setVisible(false); - formVariablesPanelIn.setVisible(false); - } - - if (dt.spr_variables_in !== false && dt.spr_variables_in !== undefined) { //Synchronous - xin = JSON.stringify(dt.spr_variables_in); - itemsIn = []; - if (xin != "[]") { - yin = xin.substring(1, xin.length - 1); - oin = yin.replace(/"/g, ''); - jin = oin.split(','); - for (i = 0; i < jin.length; i += 1) { - din = jin[i].split(':'); - itemsIn.push({ - origin: din[0], - target: din[1] - }); + }, { + id: 'formNotificationsMainPanel', + pmType: 'panel', + items: [ + { + id: 'tas_email_server_uid', + name: 'tas_email_server_uid', + pmType: 'dropdown', + label: 'Email account'.translate(), + controlsWidth: 300, + labelWidth: "27%", + options: [ + { + label: 'Default email account'.translate(), + value: '' + } + ] + }, + { + id: 'tas_not_email_from_format', + name: 'tas_not_email_from_format', + pmType: 'dropdown', + label: 'Email From Format'.translate(), + controlsWidth: 300, + labelWidth: "27%", + options: [ + { + id: 'assignedUser', + label: 'Assigned User'.translate(), + value: 0 + }, { + id: 'emailAccountSettings', + label: 'Email Account Settings'.translate(), + value: 1 + } + ] + }, + new CriteriaField({ + id: 'formNotificationsSubject', + pmType: 'text', + name: 'tas_def_subject_message', + valueType: 'string', + label: 'Subject'.translate(), + placeholder: 'Insert a title'.translate(), + required: true, + controlsWidth: 300, + labelWidth: "27%" + }), { + id: 'formNotificationsContent', + pmType: 'dropdown', + name: 'tas_def_message_type', + label: 'Content Type'.translate(), + controlsWidth: 150, + labelWidth: "27%", + options: [{ + id: 'formNotificationsContent1', + value: 'text', + label: 'Plain Text'.translate() + }, { + id: 'formNotificationsContent2', + value: 'template', + label: 'Html Template'.translate() + } + ], + onChange: function (value) { + visibleContentType(value); + } + }, new CriteriaField({ + id: 'formNotificationsMessage', + pmType: 'textarea', + name: 'tas_def_message', + valueType: 'string', + label: 'Message'.translate(), + placeholder: 'Insert a message'.translate(), + rows: 100, + width: 10, + required: true, + controlsWidth: 300, + renderType: 'textarea', + labelWidth: "27%" + }), { + id: 'formNotificationsTemplate', + pmType: 'dropdown', + name: 'tas_def_message_template', + label: 'Template'.translate(), + options: [{ + value: '', + label: '' + }], + labelWidth: "27%" } + ] + }, + { + id: 'formNotificationsTasReceive', + pmType: 'checkbox', + name: 'tas_receive_last_email', + labelVisible: false, + options: [{ + id: 'formNotificationsTasReceive', + label: 'Notify the assigned user to this task'.translate(), + value: '1' } - gridVariablesIn.setDataItems(itemsIn); - } + ], + onChange: function (val) { + changeFormNotificationsReceive(this.controls[0].selected, 'text'); + } + }, + { + id: 'formNotificationsReceivePanel', + pmType: 'panel', + items: [ + { + id: 'tas_receive_server_uid', + name: 'tas_receive_server_uid', + pmType: 'dropdown', + label: 'Email account'.translate(), + controlsWidth: 300, + labelWidth: "27%", + options: [ + { + label: 'Default email account'.translate(), + value: '' + } + ] + }, + { + id: 'tas_receive_email_from_format', + name: 'tas_receive_email_from_format', + pmType: 'dropdown', + label: 'Email From Format'.translate(), + controlsWidth: 300, + labelWidth: "27%", + options: [ + { + id: 'assignedUser', + label: 'Assigned User'.translate(), + value: 0 + }, { + id: 'emailAccountSettings', + label: 'Email Account Settings'.translate(), + value: 1 + } + ] + }, + new CriteriaField({ + id: 'tas_receive_subject_message', + pmType: 'text', + name: 'tas_receive_subject_message', + valueType: 'string', + label: 'Subject'.translate(), + placeholder: 'Insert a title'.translate(), + required: true, + controlsWidth: 300, + labelWidth: "27%" + }), + { + id: 'tas_receive_message_type', + pmType: 'dropdown', + name: 'tas_receive_message_type', + label: 'Content Type'.translate(), + controlsWidth: 150, + labelWidth: "27%", + options: [{ + id: 'formNotificationsReceive1', + value: 'text', + label: 'Plain Text'.translate() + }, { + id: 'formNotificationsReceive2', + value: 'template', + label: 'Html Template'.translate() + } + ], + onChange: function (value) { + visibleContentTypeReceive(value); + } + }, + new CriteriaField({ + id: 'tas_receive_message', + pmType: 'textarea', + name: 'tas_receive_message', + valueType: 'string', + label: 'Message'.translate(), + placeholder: 'Insert a message'.translate(), + rows: 100, + width: 10, + required: true, + controlsWidth: 300, + renderType: 'textarea', + labelWidth: "27%" + }), + { + id: 'tas_receive_message_template', + pmType: 'dropdown', + name: 'tas_receive_message_template', + label: 'Template'.translate(), + options: [{ + value: '', + label: '' + }], + labelWidth: "27%" + } - if (dt.spr_synchronous === "1") { - gridVariablesIn.setVisible(true); - formVariablesPanelIn.setVisible(true); - } - if (formProperties.getField('out_doc_process').getValue() !== '') { - loadActivity(formProperties.getField('out_doc_process').getValue()); + ] } - formProperties.getField('spr_tas').setValue(dt.spr_tas === '0' ? '' : dt.spr_tas); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } - }); - restClient.setBaseEndPoint(''); - restClient.executeRestClient(); - }; - loadActivity = function (value) { - var restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - calls: [ - { - url: 'project/' + value + '/starting-tasks', - method: 'GET' - } - ] - }, - functionSuccess: function (xhr, response) { - var dropdown, - i, - dt = response[0].response; - dt = dt.sort(function (a, b) { - return a.act_name.toString().toLowerCase() > b.act_name.toString().toLowerCase(); - }); - dropdown = formProperties.getField('spr_tas'); - dropdown.clearOptions(); - dropdown.addOption({ - value: '', - label: '- Select starting activity -'.translate() - }); - for (i = 0; i < dt.length; i += 1) { - dropdown.addOption({ - value: dt[i].act_uid, - label: dt[i].act_name - }); + ] + }) + } + ]; + if (consolidated == '1') { + configurationForms.push({ + id: 'windowPropertiesTabPanelConsolidated', + icon: '', + title: 'Consolidated Case '.translate(), + panel: formConsolidated = new PMUI.form.Form({ + id: 'formConsolidated', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 250, + items: [ + { + id: 'formConsolidatedEnable', + pmType: 'checkbox', + name: 'consolidated_enable', + labelVisible: false, + options: [{ + label: 'Enable consolidate for this task.'.translate(), + value: '1' + } + ], + onChange: function (val) { + changeConsolidated(this.controls[0].selected); + } + }, { + id: 'formConsolidatedMainPanel', + pmType: 'panel', + items: [ + { + id: 'formConsolidatedReportTable', + pmType: 'text', + name: 'consolidated_report_table', + visible: false, + valueType: 'string', + controlsWidth: 300 + }, { + id: 'formConsolidatedDynaform', + pmType: 'dropdown', + name: 'consolidated_dynaform', + label: 'Dynaform Template'.translate(), + options: [], + required: true, + controlsWidth: 300 + }, { + id: 'formConsolidatedTable', + pmType: 'text', + name: 'consolidated_table', + valueType: 'string', + label: 'Table Name'.translate(), + placeholder: 'Insert a table name'.translate(), + required: true, + controlsWidth: 300, + style: { + cssProperties: { + float: "left" + } + }, + validators: [{ + pmType: "regexp", + criteria: /^[a-zA-Z0-9_]+$/, + errorMessage: "The table name can not contain spaces".translate() + }] + }, { + id: 'formConsolidatedTitle', + pmType: 'text', + name: 'consolidated_title', + valueType: 'string', + label: 'Title'.translate(), + placeholder: 'Insert a title'.translate(), + required: true, + controlsWidth: 300, + style: { + cssProperties: { + float: "left" + } + } + } + ] } - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } - }); - restClient.setBaseEndPoint(''); - restClient.executeRestClient(); - }; - - formVariablesPanelOut.addItem(formVarTexOriginOut); - formVariablesPanelOut.addItem(formVarTexTargetOut); - formVariablesPanelOut.addItem(formVarButtonAddOut); - - formVariablesPanelIn.addItem(formVarTexOriginIn); - formVariablesPanelIn.addItem(formVarTexTargetIn); - formVariablesPanelIn.addItem(formVarButtonAddIn); + ] + }) + }); + } - gridVariablesIn.setVisible(false); - formVariablesPanelIn.setVisible(false); + /*----------------------------------********---------------------------------*/ - windowPropertiesSub.addItem(formProperties); - windowPropertiesSub.addItem(new PMUI.ui.TextLabel({ - width: 890, - text: 'Variables Out'.translate(), - style: { - cssProperties: { - background: '#aaaaaa', - margin: '-15px 10px 10px 15px', - color: 'white', - padding: '6px', - 'font-weight': 'bold' - } + warningChanges = new PMUI.ui.MessageWindow({ + id: 'warningChanges', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: 'Activity Properties'.translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + id: 'warningChangesButtonNo', + text: "No".translate(), + handler: function () { + warningChanges.close(); + }, + buttonType: "error" }, - display: 'block' - })); - windowPropertiesSub.addItem(formVariablesPanelOut); - windowPropertiesSub.addItem(gridVariablesOut); - - windowPropertiesSub.addItem(new PMUI.ui.TextLabel({ - width: 890, - text: 'Variables In'.translate(), - style: { - cssProperties: { - background: '#aaaaaa', - margin: '15px 10px 10px 15px', - color: 'white', - padding: '6px', - 'font-weight': 'bold' + { + id: 'warningChangesButtonYes', + text: "Yes".translate(), + handler: function () { + windowProperties.close(); + warningChanges.close(); + }, + buttonType: "success" + } + ] + }); + windowProperties = new PMUI.ui.Window({ + id: 'windowProperties', + title: 'Activity Properties'.translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + onOpen: function () { + loadServerData(); + }, + items: [ + propertiesTabs = new PMUI.panel.TabPanel({ + id: 'windowPropertiesTabPanel', + height: 435, + width: DEFAULT_WINDOW_WIDTH - 50, + style: { + cssProperties: { + 'margin-left': '10px' + } + }, + items: configurationForms.concat(featuresForms), + itemsPosition: { + position: 'left' + }, + onTabClick: function (tab) { + setFocusTab(tab); } + }), + customGrid + ], + onBeforeClose: function () { + if (isDirty()) { + warningChanges.open(); + warningChanges.showFooter(); + } else { + windowProperties.close(); + } + }, + buttonPanelPosition: 'bottom', + buttonsPosition: 'right', + buttons: [ + { + id: 'windowPropertiesButtonCancel', + text: 'Cancel'.translate(), + handler: function () { + if (isDirty()) { + warningChanges.open(); + warningChanges.showFooter(); + } else { + windowProperties.close(); + } + }, + buttonType: "error" }, - display: 'block', - visible: false - })); - - windowPropertiesSub.addItem(formVariablesPanelIn); - windowPropertiesSub.addItem(gridVariablesIn); + { + id: 'windowPropertiesButtonSave', + text: 'Save'.translate(), + handler: function () { + saveData(); + }, + buttonType: 'success' + } + ] + }); - loadDropProcess(); - gridVariablesOut.setDataItems(""); - gridVariablesIn.setDataItems(""); - loadDataServer(); + function changeConsolidated(value) { + var panel = formConsolidated.getItem('formConsolidatedMainPanel'); + formConsolidated.getField('consolidated_enable').setValue(value ? '["1"]' : '[]'); - if (formProperties.getItems()[1].getValue() != "0") { - formVarTexTargetOut.setProcess(formProperties.getItems()[1].getValue()); - formVarTexOriginIn.setProcess(formProperties.getItems()[1].getValue()); + if (panel) { + panel.setVisible(value); + if (value) { + panel.enable(); + } else { + panel.disable(); + } } - windowPropertiesSub.open(); - if (formProperties.getField('out_doc_process').getValue().trim().length === 0) { - formVarTexTargetOut.buttonHTML.disable(); - formVarTexOriginIn.buttonHTML.disable(); - } else { - formVarTexTargetOut.buttonHTML.enable(); - formVarTexOriginIn.buttonHTML.enable(); + + formConsolidated.getField('consolidated_report_table').setVisible(false); + } + + function changeTimingControl(value) { + var mainPanel = formTimingControl.getItem('formTimingMainPanel'); + formTimingControl.getField('tas_transfer_fly').setValue(value ? '["1"]' : '[]'); + if (mainPanel) { + if (value) { + mainPanel.disable(); + + } else { + mainPanel.enable(); + } + mainPanel.setVisible(!value); } - windowPropertiesSub.showFooter(); - applyStyleWindowForm(windowPropertiesSub); - formVariablesPanelIn.getItems()[0].dom.labelTextContainer.style.display = "none"; - formVariablesPanelIn.getItems()[1].dom.labelTextContainer.style.display = "none"; - formVariablesPanelOut.getItems()[0].dom.labelTextContainer.style.display = "none"; - formVariablesPanelOut.getItems()[1].dom.labelTextContainer.style.display = "none"; - formVariablesPanelOut.style.addProperties({marginLeft: '45px'}); - gridVariablesOut.style.addProperties({marginLeft: '45px'}); - if (formVariablesPanelIn.visible == true) { - gridVariablesIn.setVisible(true); - gridVariablesIn.style.addProperties({marginLeft: '45px'}); - formVariablesPanelIn.setVisible(true); - formVariablesPanelIn.getItems()[2].setWidth(80); - $(formVariablesPanelIn.html).css({width: '850px', marginLeft: '45px'}); - windowPropertiesSub.getItems()[4].setVisible(true); + if (window.enterprise !== "1") { + formTimingControl.getField('tas_average').setVisible(false); + formTimingControl.getField('tas_sdv').setVisible(false); } + } - formVariablesPanelOut.style.addProperties({width: '870px'}); - $(gridVariablesIn.html).find(".pmui-gridpanel-footer").css("position", "static"); - $(gridVariablesIn.html).find(".pmui-gridpanel-footer").css("margin-top", "0px"); - $(gridVariablesOut.html).find(".pmui-gridpanel-footer").css("position", "static"); - $(gridVariablesOut.html).find(".pmui-gridpanel-footer").css("margin-top", "0px"); - windowPropertiesSub.defineEvents(); - gridVariablesOut.html.children[0].style.display = "none"; - gridVariablesIn.html.children[0].style.display = "none"; - formProperties.getField('out_doc_title').setFocus(); - formVarButtonAddOut.setWidth(80); - formVarButtonAddOut.setVisible(true); + function changeFormNotifications(value, valueTwo) { + var panel = formNotifications.getItem('formNotificationsMainPanel'); - }; -}()); -if (typeof(consolidated) == 'undefined') { - consolidated = '0'; -} -PMDesigner.activityProperties = function (activity) { - switch (activity.getActivityType()) { - case "SUB_PROCESS": - PMDesigner.propertiesSubProcess(activity); - break; - case "TASK": - if (activity.getTaskType() === "SCRIPTTASK") { - PMDesigner.scriptTaskProperties(activity); + if (panel) { + panel.setVisible(value); + if (value) { + panel.enable(); } else { - PMDesigner.taskProperties(activity); + panel.disable(); } - break; + } + + if (value) { + formNotifications.getField('tas_def_message_type').setValue(valueTwo); + visibleContentType(valueTwo); + } + formNotifications.getField('tas_send_last_email').setValue(value ? '["1"]' : '[]'); + formNotifications.getField('tas_def_subject_message').setFocus(); } -}; -PMDesigner.taskProperties = function (activity) { - var formDefinitions, - featuresForms = [], - propertiesTabs, - formCaseLabels, - dataProperties, - formTimingControl, - configurationForms, - customGrid, - formNotifications, - buttonFieldCancel, - buttonFieldAdd, - abeForm, - MobilePanel, - enableTaskMobile, - routeCaseMobile, - abeMainPanel, - abeAddOption, - abeTemplates, - abeDynaforms, - abeEmailAcount, - abeFields, - warningChanges, - windowProperties, - processDataProperties, - i, - editRow = null, - arrayTrue = '["TRUE"]', - arrayFalse = '["FALSE"]', - stringTrue = "TRUE", - stringFalse = "FALSE", - defaultServerlabel = "Mail (PHP)".translate(); + /** + * Notification receive change handler, according to user selection + * @param value + * @param valueTwo + */ + function changeFormNotificationsReceive(value, valueTwo) { + var panel = formNotifications.getItem('formNotificationsReceivePanel'); - configurationForms = [ - { - id: 'windowPropertiesTabPanelDefinitions', - icon: '', - title: 'Definitions'.translate(), - panel: formDefinitions = new PMUI.form.Form({ - id: 'formDefinitions', - visibleHeader: false, - width: DEFAULT_WINDOW_WIDTH - 250, - items: [{ - id: 'formDefinitionsUID', - pmType: 'text', - name: 'UID', - valueType: 'string', - label: 'UID'.translate(), - controlsWidth: 300 - }, { - id: 'formDefinitionsTitle', - pmType: 'text', - name: 'tas_title', - valueType: 'string', - label: 'Title'.translate(), - placeholder: 'Insert a title'.translate(), - required: true, - controlsWidth: 300 - }, { - id: 'formDefinitionsDescription', - pmType: 'textarea', - name: 'tas_description', - valueType: 'string', - label: 'Description'.translate(), - placeholder: 'Insert a description'.translate(), - rows: 100, - controlsWidth: 300, - style: {cssClasses: ['mafe-textarea-resize']} - }, new CriteriaField({ - id: 'formDefinitionsVariable', - pmType: 'text', - name: 'tas_priority_variable', - valueType: 'string', - label: 'Variable for Case priority'.translate(), - controlsWidth: 300 - }), { - id: 'formDefinitionsRouting', - pmType: 'dropdown', - name: 'tas_derivation_screen_tpl', - valueType: 'string', - label: 'Routing Screen Template'.translate(), - controlsWidth: 150, - style: { - cssProperties: { - float: "left" - } - } - } - ] - }) - }, - { - id: 'windowPropertiesTabPanelCaseLabels', - icon: '', - title: 'Case Labels'.translate(), - panel: formCaseLabels = new PMUI.form.Form({ - id: 'formCaseLabels', - visibleHeader: false, - width: DEFAULT_WINDOW_WIDTH - 250, - items: [new CriteriaField({ - id: 'formCaseLabelsTitle', - pmType: 'text', - name: 'tas_def_title', - valueType: 'string', - label: 'Title'.translate(), - placeholder: 'Insert a title'.translate(), - controlsWidth: DEFAULT_WINDOW_WIDTH - 527 - }), new CriteriaField({ - id: 'formCaseLabelsDescription', - pmType: 'textarea', - name: 'tas_def_description', - valueType: 'string', - label: 'Description'.translate(), - placeholder: 'Insert a description'.translate(), - rows: 100, - controlsWidth: DEFAULT_WINDOW_WIDTH - 527, - renderType: 'textarea' - }) - ] - }) - }, - { - id: 'windowPropertiesTabPanelTimingControl', - icon: '', - title: 'Timing Control'.translate(), - panel: formTimingControl = new PMUI.form.Form({ - id: 'formTimingControl', - visibleHeader: false, - width: DEFAULT_WINDOW_WIDTH - 250, - items: [{ - id: 'formTimingControlFly', - pmType: 'checkbox', - name: 'tas_transfer_fly', - labelVisible: false, - options: [ - { - id: 'formTimingControlOption', - label: 'Allow users to change the task duration in runtime'.translate(), - value: '1' - } - ], - onChange: function (val) { - changeTimingControl(this.controls[0].selected); - } - }, { - id: 'formTimingMainPanel', - pmType: 'panel', - items: [ - { - id: 'formTimingControlTask', - pmType: 'text', - name: 'tas_duration', - valueType: 'string', - label: 'Task duration'.translate(), - required: true, - maxLength: 3, - controlsWidth: 200, - validators: [ - { - pmType: "regexp", - criteria: /^\d*$/, - errorMessage: "Please enter a positive integer value".translate() - } - ] - }, - { - id: 'formTimingControlAverage', - pmType: 'text', - name: 'tas_average', - valueType: 'string', - label: 'Average'.translate(), - maxLength: 3, - readOnly: true, - controlsWidth: 200 - }, - { - id: 'formTimingControlSdv', - pmType: 'text', - name: 'tas_sdv', - valueType: 'string', - label: 'SDV'.translate(), - maxLength: 3, - readOnly: true, - controlsWidth: 200 - }, - { - id: 'formTimingControlTime', - pmType: 'dropdown', - name: 'tas_timeunit', - label: 'Time unit'.translate(), - controlsWidth: 100, - options: [{ - id: 'formTimingControlTime1', - label: 'Hours'.translate(), - value: 'HOURS' - }, { - id: 'formTimingControlTime2', - label: 'Days'.translate(), - value: 'DAYS' - }, { - id: 'formTimingControlTime3', - label: 'Minutes'.translate(), - value: 'MINUTES' - } - ] - }, { - id: 'formTimingControlCount', - pmType: 'dropdown', - name: 'tas_type_day', - label: 'Count days by'.translate(), - controlsWidth: 150, - options: [{ - id: 'formTimingControlCount1', - label: 'Work Days'.translate(), - value: 1 - }, { - id: 'formTimingControlCount2', - label: 'Calendar Days'.translate(), - value: 2 - } - ] - }, { - id: 'formTimingControlCalendar', - pmType: 'dropdown', - name: 'tas_calendar', - label: 'Calendar'.translate(), - options: [], - controlsWidth: 150 - } - ] - } - ] - }) - }, - { - id: 'windowPropertiesTabPanelNotifications', - icon: '', - title: 'Notifications'.translate(), - panel: formNotifications = new PMUI.form.Form({ - id: 'formNotifications', - visibleHeader: false, - width: DEFAULT_WINDOW_WIDTH - 250, - items: [ - { - id: 'formNotificationsTasSend', - pmType: 'checkbox', - name: 'tas_send_last_email', - labelVisible: false, - options: [{ - id: 'formNotificationsTasSend1', - label: 'After routing notify the next assigned user(s)'.translate(), - value: '1' - } - ], - onChange: function (val) { - changeFormNotifications(this.controls[0].selected, 'text'); - } - }, { - id: 'formNotificationsMainPanel', - pmType: 'panel', - items: [ - { - id: 'tas_email_server_uid', - name: 'tas_email_server_uid', - pmType: 'dropdown', - label: 'Email account'.translate(), - controlsWidth: 300, - labelWidth: "27%", - options: [ - { - label: 'Default email account'.translate(), - value: '' - } - ] - }, - { - id: 'tas_not_email_from_format', - name: 'tas_not_email_from_format', - pmType: 'dropdown', - label: 'Email From Format'.translate(), - controlsWidth: 300, - labelWidth: "27%", - options: [ - { - id: 'assignedUser', - label: 'Assigned User'.translate(), - value: 0 - }, { - id: 'emailAccountSettings', - label: 'Email Account Settings'.translate(), - value: 1 - } - ] - }, - new CriteriaField({ - id: 'formNotificationsSubject', - pmType: 'text', - name: 'tas_def_subject_message', - valueType: 'string', - label: 'Subject'.translate(), - placeholder: 'Insert a title'.translate(), - required: true, - controlsWidth: 300, - labelWidth: "27%" - }), { - id: 'formNotificationsContent', - pmType: 'dropdown', - name: 'tas_def_message_type', - label: 'Content Type'.translate(), - controlsWidth: 150, - labelWidth: "27%", - options: [{ - id: 'formNotificationsContent1', - value: 'text', - label: 'Plain Text'.translate() - }, { - id: 'formNotificationsContent2', - value: 'template', - label: 'Html Template'.translate() - } - ], - onChange: function (value) { - visibleContentType(value); - } - }, new CriteriaField({ - id: 'formNotificationsMessage', - pmType: 'textarea', - name: 'tas_def_message', - valueType: 'string', - label: 'Message'.translate(), - placeholder: 'Insert a message'.translate(), - rows: 100, - width: 10, - required: true, - controlsWidth: 300, - renderType: 'textarea', - labelWidth: "27%" - }), { - id: 'formNotificationsTemplate', - pmType: 'dropdown', - name: 'tas_def_message_template', - label: 'Template'.translate(), - options: [{ - value: '', - label: '' - }], - labelWidth: "27%" - } - ] - }, - { - id: 'formNotificationsTasReceive', - pmType: 'checkbox', - name: 'tas_receive_last_email', - labelVisible: false, - options: [{ - id: 'formNotificationsTasReceive', - label: 'Notify the assigned user to this task'.translate(), - value: '1' - } - ], - onChange: function (val) { - changeFormNotificationsReceive(this.controls[0].selected, 'text'); - } - }, - { - id: 'formNotificationsReceivePanel', - pmType: 'panel', - items: [ - { - id: 'tas_receive_server_uid', - name: 'tas_receive_server_uid', - pmType: 'dropdown', - label: 'Email account'.translate(), - controlsWidth: 300, - labelWidth: "27%", - options: [ - { - label: 'Default email account'.translate(), - value: '' - } - ] - }, - { - id: 'tas_receive_email_from_format', - name: 'tas_receive_email_from_format', - pmType: 'dropdown', - label: 'Email From Format'.translate(), - controlsWidth: 300, - labelWidth: "27%", - options: [ - { - id: 'assignedUser', - label: 'Assigned User'.translate(), - value: 0 - }, { - id: 'emailAccountSettings', - label: 'Email Account Settings'.translate(), - value: 1 - } - ] - }, - new CriteriaField({ - id: 'tas_receive_subject_message', - pmType: 'text', - name: 'tas_receive_subject_message', - valueType: 'string', - label: 'Subject'.translate(), - placeholder: 'Insert a title'.translate(), - required: true, - controlsWidth: 300, - labelWidth: "27%" - }), - { - id: 'tas_receive_message_type', - pmType: 'dropdown', - name: 'tas_receive_message_type', - label: 'Content Type'.translate(), - controlsWidth: 150, - labelWidth: "27%", - options: [{ - id: 'formNotificationsReceive1', - value: 'text', - label: 'Plain Text'.translate() - }, { - id: 'formNotificationsReceive2', - value: 'template', - label: 'Html Template'.translate() - } - ], - onChange: function (value) { - visibleContentTypeReceive(value); - } - }, - new CriteriaField({ - id: 'tas_receive_message', - pmType: 'textarea', - name: 'tas_receive_message', - valueType: 'string', - label: 'Message'.translate(), - placeholder: 'Insert a message'.translate(), - rows: 100, - width: 10, - required: true, - controlsWidth: 300, - renderType: 'textarea', - labelWidth: "27%" - }), - { - id: 'tas_receive_message_template', - pmType: 'dropdown', - name: 'tas_receive_message_template', - label: 'Template'.translate(), - options: [{ - value: '', - label: '' - }], - labelWidth: "27%" - } - - ] - } - ] - }) - } - ]; - if (consolidated == '1') { - configurationForms.push({ - id: 'windowPropertiesTabPanelConsolidated', - icon: '', - title: 'Consolidated Case '.translate(), - panel: formConsolidated = new PMUI.form.Form({ - id: 'formConsolidated', - visibleHeader: false, - width: DEFAULT_WINDOW_WIDTH - 250, - items: [ - { - id: 'formConsolidatedEnable', - pmType: 'checkbox', - name: 'consolidated_enable', - labelVisible: false, - options: [{ - label: 'Enable consolidate for this task.'.translate(), - value: '1' - } - ], - onChange: function (val) { - changeConsolidated(this.controls[0].selected); - } - }, { - id: 'formConsolidatedMainPanel', - pmType: 'panel', - items: [ - { - id: 'formConsolidatedReportTable', - pmType: 'text', - name: 'consolidated_report_table', - visible: false, - valueType: 'string', - controlsWidth: 300 - }, { - id: 'formConsolidatedDynaform', - pmType: 'dropdown', - name: 'consolidated_dynaform', - label: 'Dynaform Template'.translate(), - options: [], - required: true, - controlsWidth: 300 - }, { - id: 'formConsolidatedTable', - pmType: 'text', - name: 'consolidated_table', - valueType: 'string', - label: 'Table Name'.translate(), - placeholder: 'Insert a table name'.translate(), - required: true, - controlsWidth: 300, - style: { - cssProperties: { - float: "left" - } - }, - validators: [{ - pmType: "regexp", - criteria: /^[a-zA-Z0-9_]+$/, - errorMessage: "The table name can not contain spaces".translate() - }] - }, { - id: 'formConsolidatedTitle', - pmType: 'text', - name: 'consolidated_title', - valueType: 'string', - label: 'Title'.translate(), - placeholder: 'Insert a title'.translate(), - required: true, - controlsWidth: 300, - style: { - cssProperties: { - float: "left" - } - } - } - ] - } - ] - }) - }); - } - - /*----------------------------------********---------------------------------*/ - - warningChanges = new PMUI.ui.MessageWindow({ - id: 'warningChanges', - windowMessageType: 'warning', - width: 490, - bodyHeight: 'auto', - title: 'Activity Properties'.translate(), - message: 'Are you sure you want to discard your changes?'.translate(), - footerItems: [ - { - id: 'warningChangesButtonNo', - text: "No".translate(), - handler: function () { - warningChanges.close(); - }, - buttonType: "error" - }, - { - id: 'warningChangesButtonYes', - text: "Yes".translate(), - handler: function () { - windowProperties.close(); - warningChanges.close(); - }, - buttonType: "success" - } - ] - }); - windowProperties = new PMUI.ui.Window({ - id: 'windowProperties', - title: 'Activity Properties'.translate(), - height: DEFAULT_WINDOW_HEIGHT, - width: DEFAULT_WINDOW_WIDTH, - onOpen: function () { - loadServerData(); - }, - items: [ - propertiesTabs = new PMUI.panel.TabPanel({ - id: 'windowPropertiesTabPanel', - height: 435, - width: DEFAULT_WINDOW_WIDTH - 50, - style: { - cssProperties: { - 'margin-left': '10px' - } - }, - items: configurationForms.concat(featuresForms), - itemsPosition: { - position: 'left' - }, - onTabClick: function (tab) { - setFocusTab(tab); - } - }), - customGrid - ], - onBeforeClose: function () { - if (isDirty()) { - warningChanges.open(); - warningChanges.showFooter(); - } else { - windowProperties.close(); - } - }, - buttonPanelPosition: 'bottom', - buttonsPosition: 'right', - buttons: [ - { - id: 'windowPropertiesButtonCancel', - text: 'Cancel'.translate(), - handler: function () { - if (isDirty()) { - warningChanges.open(); - warningChanges.showFooter(); - } else { - windowProperties.close(); - } - }, - buttonType: "error" - }, - { - id: 'windowPropertiesButtonSave', - text: 'Save'.translate(), - handler: function () { - saveData(); - }, - buttonType: 'success' - } - ] - }); - - function changeConsolidated(value) { - var panel = formConsolidated.getItem('formConsolidatedMainPanel'); - formConsolidated.getField('consolidated_enable').setValue(value ? '["1"]' : '[]'); - - if (panel) { - panel.setVisible(value); - if (value) { - panel.enable(); - } else { - panel.disable(); - } - } - - formConsolidated.getField('consolidated_report_table').setVisible(false); - } - - function changeTimingControl(value) { - var mainPanel = formTimingControl.getItem('formTimingMainPanel'); - formTimingControl.getField('tas_transfer_fly').setValue(value ? '["1"]' : '[]'); - if (mainPanel) { - if (value) { - mainPanel.disable(); - - } else { - mainPanel.enable(); - } - mainPanel.setVisible(!value); - } - if (window.enterprise !== "1") { - formTimingControl.getField('tas_average').setVisible(false); - formTimingControl.getField('tas_sdv').setVisible(false); - } - } - - function changeFormNotifications(value, valueTwo) { - var panel = formNotifications.getItem('formNotificationsMainPanel'); - - if (panel) { - panel.setVisible(value); - if (value) { - panel.enable(); - } else { - panel.disable(); - } - } - - if (value) { - formNotifications.getField('tas_def_message_type').setValue(valueTwo); - visibleContentType(valueTwo); - } - formNotifications.getField('tas_send_last_email').setValue(value ? '["1"]' : '[]'); - formNotifications.getField('tas_def_subject_message').setFocus(); - } - - /** - * Notification receive change handler, according to user selection - * @param value - * @param valueTwo - */ - function changeFormNotificationsReceive(value, valueTwo) { - var panel = formNotifications.getItem('formNotificationsReceivePanel'); - - if (panel) { - panel.setVisible(value); - if (value) { - panel.enable(); - } else { - panel.disable(); - } - } - - if (value) { - formNotifications.getField('tas_receive_message_type').setValue(valueTwo); - visibleContentTypeReceive(valueTwo); - } - formNotifications.getField('tas_receive_last_email').setValue(value ? '["1"]' : '[]'); - formNotifications.getField('tas_receive_subject_message').setFocus(); - } - - /** - * Get value parsed - * @param valueCheckBox '["TRUE"]'/'["FALSE"]' - * @returns {string} "TRUE"/"FALSE" - */ - function getValueCheckBox(valueCheckBox) { - var optionSelected = JSON.parse(valueCheckBox), - valChecked; - valChecked = (Array.isArray(optionSelected) && optionSelected.length === 1) ? optionSelected[0] : stringFalse; - return valChecked; - } - - function loadFormData(response) { - dataProperties = response.properties; - formDefinitions.getField('UID').setReadOnly(true); - formDefinitions.getField('UID').setValue(activity.id); - formDefinitions.getField('tas_title').setValue(dataProperties.tas_title); - formDefinitions.getField('tas_title').setFocus(); - formDefinitions.getField('tas_description').setValue(dataProperties.tas_description); - formDefinitions.getField('tas_priority_variable').setValue(dataProperties.tas_priority_variable); - formDefinitions.getField('tas_derivation_screen_tpl').setValue(dataProperties.tas_derivation_screen_tpl); - - formCaseLabels.getField('tas_def_title').setValue(dataProperties.tas_def_title); - formCaseLabels.getField('tas_def_description').setValue(dataProperties.tas_def_description); - - if (dataProperties.tas_transfer_fly === 'FALSE') { - changeTimingControl(false); - } else { - changeTimingControl(true); - } - formTimingControl.getField('tas_duration').setValue(dataProperties.tas_duration); - formTimingControl.getField('tas_timeunit').setValue(dataProperties.tas_timeunit); - formTimingControl.getField('tas_type_day').setValue(dataProperties.tas_type_day); - formTimingControl.getField('tas_calendar').setValue(dataProperties.tas_calendar); - - if (window.enterprise === "1") { - formTimingControl.getField('tas_average').setValue(dataProperties.tas_average); - formTimingControl.getField('tas_sdv').setValue(dataProperties.tas_sdv); - } - - changeFormNotifications(dataProperties.tas_send_last_email === 'TRUE', dataProperties.tas_def_message_type); - changeFormNotificationsReceive(dataProperties.tas_receive_last_email === 'TRUE', dataProperties.tas_receive_message_type); - formNotifications.getField('tas_def_subject_message').setValue(dataProperties.tas_def_subject_message); - formNotifications.getField('tas_def_message_type').setValue(dataProperties.tas_def_message_type); - formNotifications.getField('tas_def_message').setValue(dataProperties.tas_def_message); - formNotifications.getField('tas_email_server_uid').setValue(dataProperties.tas_email_server_uid); - formNotifications.getField('tas_def_message_template').setValue(dataProperties.tas_def_message_template); - formNotifications.getField('tas_not_email_from_format').setValue(dataProperties.tas_not_email_from_format); - // receive - formNotifications.getField('tas_receive_subject_message').setValue(dataProperties.tas_receive_subject_message); - formNotifications.getField('tas_receive_message_type').setValue(dataProperties.tas_receive_message_type); - formNotifications.getField('tas_receive_message').setValue(dataProperties.tas_receive_message); - formNotifications.getField('tas_receive_server_uid').setValue(dataProperties.tas_receive_server_uid); - formNotifications.getField('tas_receive_message_template').setValue(dataProperties.tas_receive_message_template); - formNotifications.getField('tas_receive_email_from_format').setValue(dataProperties.tas_receive_email_from_format); - } - /*----------------------------------********---------------------------------*/ - function loadCalendar(response) { - var field = formTimingControl.getField('tas_calendar'), i; - field.clearOptions(); - field.addOption({ - value: '', - label: '- None -'.translate() - }); - for (i = 0; i < response.length; i += 1) { - field.addOption({ - value: response[i].cal_uid, - label: response[i].cal_name - }); - } - } - - /** - * Loads the template from rest service response - * @param response - * @param fieldName - */ - function loadTemplate(response, fieldName) { - var field = formNotifications.getField(fieldName), i, field2; - field.clearOptions(); - field.addOption({ - value: 'alert_message.html', - label: '-- Default --'.translate() - }); - for (i = 0; i < response.length; i += 1) { - field.addOption({ - value: response[i].prf_filename, - label: response[i].prf_filename - }); - } - field2 = formDefinitions.getField('tas_derivation_screen_tpl'); - field2.clearOptions(); - field2.addOption({ - value: '', - label: '-- Default --'.translate() - }); - for (i = 0; i < response.length; i += 1) { - if (response[i].prf_filename !== 'alert_message.html') { - field2.addOption({ - value: response[i].prf_filename, - label: response[i].prf_filename - }); - } - } - }; - /** - * Load Email account server dropdown options - * @param response - */ - function loadEmailAccount(response, fieldName) { - var field = formNotifications.getField(fieldName) || null, - i; - if (response instanceof Array && field) { - for (i = 0; i < response.length; i += 1) { - field.addOption({ - value: response[i].mess_uid, - label: response[i].mess_engine === "MAIL" ? - response[i].mess_from_name && response[i].mess_from_name !== "" ? - response[i].mess_from_name : defaultServerlabel : response[i].mess_from_name && response[i].mess_from_name !== "" ? - response[i].mess_from_name + ' <' + response[i].mess_account + '>' : ' <' + response[i].mess_account + '>' - }); - } - } - }; - - function loadABETemplateField(templates) { - var templateField = abeForm.getField('ABE_TEMPLATE'), i; - for (i in templates) { - if (templateField !== null) { - templateField.addOption({ - value: templates[i].FIELD, - label: templates[i].NAME - }); - } - abeTemplates.options.push({ - value: templates[i].FIELD, - label: templates[i].NAME - }); - } - }; - /** - * Loads the email accounts settings - * @param response - */ - function loadABEmailAccount(response) { - var accountField = abeForm.getField('ABE_EMAIL_SERVER_UID') || null, - i; - - if (response instanceof Array) { - for (i = 0; i < response.length; i += 1) { - if (accountField !== null) { - accountField.addOption({ - value: response[i].mess_uid, - label: response[i].mess_engine === "MAIL" ? - response[i].mess_from_name && response[i].mess_from_name !== "" ? - response[i].mess_from_name : defaultServerlabel : response[i].mess_from_name && response[i].mess_from_name !== "" ? - response[i].mess_from_name + ' <' + response[i].mess_account + '>' : ' <' + response[i].mess_account + '>' - }); - } - abeEmailAcount.options.push({ - value: response[i].mess_uid, - label: response[i].mess_engine === "MAIL" ? - response[i].mess_from_name && response[i].mess_from_name !== "" ? - response[i].mess_from_name : defaultServerlabel : response[i].mess_from_name && response[i].mess_from_name !== "" ? - response[i].mess_from_name + ' <' + response[i].mess_account + '>' : ' <' + response[i].mess_account + '>' - }); - } - } - - }; - - function loadABEDynaformField(dynaforms) { - var dynaformField = abeForm.getField('DYN_UID'), i; - for (i in dynaforms) { - if (dynaformField !== null) { - dynaformField.addOption({ - value: dynaforms[i].DYN_UID, - label: dynaforms[i].DYN_NAME - }); - } - abeDynaforms.options.push({ - value: dynaforms[i].DYN_UID, - label: dynaforms[i].DYN_NAME - }); - } - } - - function loadServerData() { - var restClient, i; - restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - calls: { - "formconfig": { - "url": 'project/' + PMDesigner.project.id + '/activity/' + activity.id, - "method": 'GET' - }, - "calendar": { - "url": 'calendar', - "method": 'GET' - }, - "templates": { - "url": 'project/' + PMDesigner.project.id + '/file-manager?path=templates', - "method": 'GET' - }, - "emailserver": { - "url": 'project/' + PMDesigner.project.id + '/email-event/accounts/emailServer', - "method": 'GET' - } - } - }, - functionSuccess: function (xhr, response) { - loadTemplate(response["templates"].response, 'tas_def_message_template'); - loadTemplate(response["templates"].response, 'tas_receive_message_template'); - loadCalendar(response["calendar"].response); - loadFormData(response["formconfig"].response); - loadEmailAccount(response["emailserver"].response, 'tas_email_server_uid'); - loadEmailAccount(response["emailserver"].response, 'tas_receive_server_uid'); - - /*----------------------------------********---------------------------------*/ - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } - }); - if (consolidated == '1') { - $.extend(restClient.data.calls, { - "steps": { - 'url': 'project/' + PMDesigner.project.id + '/activity/' + activity.id + '/steps', - 'method': 'GET' - }, - "consolidate": { - "url": 'consolidated/' + activity.id, - "method": 'GET' - } - }); - } - /*----------------------------------********---------------------------------*/ - restClient.setBaseEndPoint(''); - restClient.executeRestClient(); - } - - function visibleContentType(value) { - formNotifications.getField('tas_def_message_template').disable(); - formNotifications.getField('tas_def_message').disable(); - if (value === 'text') { - formNotifications.getField('tas_def_message').enable(); - formNotifications.getField('tas_def_message').setVisible(true); - formNotifications.getField('tas_def_message_template').setVisible(false); - } - if (value === 'template') { - formNotifications.getField('tas_def_message_template').enable(); - formNotifications.getField('tas_def_message').setVisible(false); - formNotifications.getField('tas_def_message_template').setVisible(true); - } - }; - /** - * content type handler, enable or disable templates or message field - * @param value - */ - function visibleContentTypeReceive(value) { - formNotifications.getField('tas_receive_message_template').disable(); - formNotifications.getField('tas_receive_message').disable(); - if (value === 'text') { - formNotifications.getField('tas_receive_message').enable(); - formNotifications.getField('tas_receive_message').setVisible(true); - formNotifications.getField('tas_receive_message_template').setVisible(false); - } - if (value === 'template') { - formNotifications.getField('tas_receive_message_template').enable(); - formNotifications.getField('tas_receive_message').setVisible(false); - formNotifications.getField('tas_receive_message_template').setVisible(true); - } - }; - function saveData() { - var tabPanel = windowProperties.getItem('windowPropertiesTabPanel'), - tabItems = tabPanel.getItems(), - valid = true, - panel, - tas_transfer_fly, - tas_send_last_email, - tas_receive_last_email, - dataCaseLabels, - dataDefinitions, - dataTimingControl, - dataNotification, - consolidated_enable, - message, - i; - - for (i = 0; i < tabItems.length; i += 1) { - panel = tabItems[i].getPanel(); - if (panel instanceof PMUI.form.Form) { - valid = valid && panel.isValid(); - } else { - if (panel.getID() === "ActionsByEmailPanel") { - if (!abeForm.isValid()) { - valid = false; - } - } - } - if (!valid) { - tabItems[i].select(); - return; - } - } - /*----------------------------------********---------------------------------*/ - - tas_transfer_fly = formTimingControl.getField('tas_transfer_fly').getValue() === '["1"]'; - tas_send_last_email = formNotifications.getField('tas_send_last_email').getValue() === '["1"]'; - tas_receive_last_email = formNotifications.getField('tas_receive_last_email').getValue() === '["1"]'; - - if (tas_transfer_fly !== false) { - var a = formTimingControl.getField('tas_transfer_fly').getValue(); - formTimingControl.reset(); - formTimingControl.getField('tas_transfer_fly').setValue(a); - formTimingControl.getField('tas_duration').setValue('1'); - formTimingControl.getField('tas_timeunit').setValue('DAYS'); - formTimingControl.getField('tas_type_day').setValue(''); - formTimingControl.getField('tas_calendar').setValue(''); - } - - if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { - dataDefinitions = getData2PMUI(formDefinitions.html); - dataCaseLabels = getData2PMUI(formCaseLabels.html); - dataTimingControl = getData2PMUI(formTimingControl.html); - dataNotification = getData2PMUI(formNotifications.html); - if (!dataCaseLabels) { - dataCaseLabels = {}; - } - if (!dataTimingControl) { - dataTimingControl = {}; - } - if (!dataNotification) { - dataNotification = {}; - } - } else { - dataDefinitions = formDefinitions.getData(); - dataCaseLabels = formCaseLabels.getData(); - dataTimingControl = formTimingControl.getData(); - dataNotification = formNotifications.getData(); - } - - if (dataDefinitions['tas_title']) { - dataProperties.tas_title = dataDefinitions['tas_title']; - } - if (dataDefinitions['tas_description']) { - dataProperties.tas_description = dataDefinitions['tas_description']; - } - if (dataDefinitions['tas_priority_variable'] || typeof dataDefinitions['tas_priority_variable'] == "string") { - dataProperties.tas_priority_variable = dataDefinitions['tas_priority_variable']; - } - if (dataDefinitions['tas_derivation_screen_tpl'] || dataDefinitions['tas_derivation_screen_tpl'] == "") { - dataProperties.tas_derivation_screen_tpl = dataDefinitions['tas_derivation_screen_tpl']; - } - dataProperties.tas_def_title = dataCaseLabels['tas_def_title']; - dataProperties.tas_def_description = dataCaseLabels['tas_def_description']; - dataProperties.tas_transfer_fly = tas_transfer_fly ? 'TRUE' : 'FALSE'; - if (dataTimingControl['tas_duration']) { - dataProperties.tas_duration = dataTimingControl['tas_duration']; - } - if (dataTimingControl['tas_timeunit']) { - dataProperties.tas_timeunit = dataTimingControl['tas_timeunit']; - } - if (dataTimingControl['tas_type_day']) { - dataProperties.tas_type_day = dataTimingControl['tas_type_day']; - } - if (dataTimingControl['tas_calendar']) { - dataProperties.tas_calendar = dataTimingControl['tas_calendar']; - } - dataProperties.tas_send_last_email = tas_send_last_email ? 'TRUE' : 'FALSE'; - if (dataNotification['tas_not_email_from_format']) { - dataProperties.tas_not_email_from_format = dataNotification['tas_not_email_from_format']; - } - if (dataNotification['tas_def_subject_message']) { - dataProperties.tas_def_subject_message = dataNotification['tas_def_subject_message']; - } - if (dataNotification['tas_def_message_type']) { - dataProperties.tas_def_message_type = dataNotification['tas_def_message_type']; - } - if (dataNotification['tas_def_message']) { - dataProperties.tas_def_message = dataNotification['tas_def_message']; - } - if (dataNotification['tas_def_message_template']) { - dataProperties.tas_def_message_template = dataNotification['tas_def_message_template']; - } - if (dataNotification['tas_email_server_uid'] !== 'undefined' && dataNotification['tas_email_server_uid'] !== null) { - dataProperties.tas_email_server_uid = dataNotification['tas_email_server_uid']; - } - - dataProperties.tas_receive_last_email = tas_receive_last_email ? 'TRUE' : 'FALSE'; - if (dataNotification['tas_receive_email_from_format']) { - dataProperties.tas_receive_email_from_format = dataNotification['tas_receive_email_from_format']; - } - if (dataNotification['tas_receive_server_uid'] !== 'undefined' && dataNotification['tas_receive_server_uid'] !== null) { - dataProperties.tas_receive_server_uid = dataNotification['tas_receive_server_uid']; - } - if (dataNotification['tas_receive_subject_message']) { - dataProperties.tas_receive_subject_message = dataNotification['tas_receive_subject_message']; - } - if (dataNotification['tas_receive_message_type']) { - dataProperties.tas_receive_message_type = dataNotification['tas_receive_message_type']; - } - if (dataNotification['tas_receive_message']) { - dataProperties.tas_receive_message = dataNotification['tas_receive_message']; - } - if (dataNotification['tas_receive_message_template']) { - dataProperties.tas_receive_message_template = dataNotification['tas_receive_message_template']; - } - /*----------------------------------********---------------------------------*/ - - if (consolidated == '1') { - consolidated_enable = false; - if (formConsolidated.getField('consolidated_enable').getValue() == '["1"]') { - consolidated_enable = true; - if (!formConsolidated.isValid()) { - return; - } - } - dataProperties.consolidate_data = { - "consolidated_enable": consolidated_enable, - "consolidated_dynaform": formConsolidated.getField('consolidated_dynaform').getValue(), - "consolidated_table": formConsolidated.getField('consolidated_table').getValue(), - "consolidated_title": formConsolidated.getField('consolidated_title').getValue(), - "consolidated_report_table": formConsolidated.getField('consolidated_report_table').getValue() - }; - } - - (new PMRestClient({ - endpoint: 'activity/' + activity.id, - typeRequest: 'update', - messageError: '', - data: { - definition: {}, - properties: dataProperties - }, - functionSuccess: function (xhr, response) { - setNameActivity(dataProperties.tas_title); - windowProperties.close(); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageSuccess: 'Task properties saved successfully'.translate(), - flashContainer: document.body - })).executeRestClient(); - } - - function setFocusTab(tab) { - var style; - $customGrid = $("#customGrid"); - $customGrid.hide().appendTo($("#windowProperties").find(".pmui-window-body:eq(0)")); - - if (tab.getTitle() === 'Definitions'.translate()) { - formDefinitions.getField('tas_title').setFocus(); - } - if (tab.getTitle() === 'Case Labels'.translate()) { - formCaseLabels.getField('tas_def_title').setFocus(); - style = $('#formCaseLabelsDescription .pmui-field-label').attr("style"); - style = style + ' float: left;'; - $('#formCaseLabelsDescription .pmui-field-label').attr("style", style); - } - if (tab.getTitle() === 'Timing Control'.translate()) { - formTimingControl.getField('tas_duration').setFocus(); - } - if (tab.getTitle() === 'Notifications'.translate()) { - formNotifications.getField('tas_def_subject_message').setFocus(); - style = $('#formNotificationsMessage .pmui-field-label').attr("style"); - style = style + ' float: left;'; - $('#formNotificationsMessage .pmui-field-label').attr("style", style); - - style = $('#tas_receive_message .pmui-field-label').attr("style"); - style = style + ' float: left;'; - $('#tas_receive_message .pmui-field-label').attr("style", style); - } - if (tab.getTitle() === 'Actions by Email'.translate()) { - abeForm.getField("ABE_TYPE").onChange(abeForm.getField("ABE_TYPE").getValue()); - } - } - - function isDirty() { - return formDefinitions.isDirty() || - formCaseLabels.isDirty() || - formTimingControl.isDirty() || - formNotifications.isDirty(); - } - - function setNameActivity(name) { - activity.setName(name); - activity.setActName(name); - PMDesigner.project.dirty = true; - } - - windowProperties.open(); - windowProperties.showFooter(); - - applyStyleWindowForm(windowProperties); - if (consolidated == '1') { - formConsolidated.getField('consolidated_report_table').setVisible(false); - } - /*----------------------------------********---------------------------------*/ - function customDOM() { - $customGrid = $("#customGrid"); - $customGrid.show().appendTo($("#customGridPanel").find("fieldset:eq(0)")); - document.getElementById("customGridPanel").style.width = "720px"; - document.getElementById("customGridPanel").style.padding = ""; - document.getElementById("customGridPanel").getElementsByTagName("fieldset")[0].style.width = "100%"; - $(".pmui-gridpanel-footer").css({"text-align": "center", "margin-top": "10px", "width": "120%"}); - $(".pmui-gridpanel-footer").removeClass("pmui-gridpanel-footer"); - } - - function clearAddOptionForm() { - abeAddOption.getField("abe_custom_value_add").setValue(""); - abeAddOption.getField("abe_custom_label_add").setValue(""); - abeAddOption.getField("abe_custom_format_add").setValue(""); - abeAddOption.getField("buttonFieldCancel").setVisible(false); - abeAddOption.getField("buttonFieldAdd").setValue("Add".translate()); - editRow = null; - }; - function addAcceptedValue() { - var abeValue = abeAddOption.getField("abe_custom_value_add").getValue(), - abeLabel = abeAddOption.getField("abe_custom_label_add").getValue(), - abeFormat = abeAddOption.getField("abe_custom_format_add").getValue(); - - if (abeAddOption && !abeAddOption.isValid()) { - return; - } - - if (!evaluateTags(abeFormat, 'validate')) { - return; - } - - if (editRow === null) { - customGrid.addItem(new PMUI.grid.GridPanelRow({ - data: { - abe_custom_value: abeValue, - abe_custom_label: abeLabel, - abe_custom_format: abeFormat - } - })); - } else { - editRow.setData({ - abe_custom_value: abeValue, - abe_custom_label: abeLabel, - abe_custom_format: abeFormat - }); - editRow = null; - abeAddOption.getField("buttonFieldCancel").setVisible(false); - abeAddOption.getField("buttonFieldAdd").setValue("Add".translate()); - } - abeAddOption.getField("abe_custom_value_add").setValue(""); - abeAddOption.getField("abe_custom_label_add").setValue(""); - abeAddOption.getField("abe_custom_format_add").setValue(""); - } - - function customGridRowEdit(row) { - editRow = row; - row = row.getData(); - if (abeAddOption) { - abeAddOption.getField("abe_custom_value_add").setValue(row.abe_custom_value); - abeAddOption.getField("abe_custom_label_add").setValue(row.abe_custom_label); - abeAddOption.getField("abe_custom_format_add").setValue(row.abe_custom_format); - abeAddOption.getField("buttonFieldCancel").setVisible(true); - abeAddOption.getField("buttonFieldAdd").setValue("Save".translate()); - } - } - - function evaluateTags(html, action) { - var oldHtml; - var tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*'; - var pattern = /^[a-zA-Z0-9\s\[\]\.\-_#%;,=:()']*$/; - var tagOrComment = new RegExp( - '<(?:' - // Comment body. - + '!--(?:(?:-*[^->])*--+|-?)' - // Special "raw text" elements whose content should be elided. - + '|script\\b' + tagBody + '>[\\s\\S]*?[\\s\\S]*?', - 'gi'); - - var action = (typeof action === 'undefined') ? 'delete' : 'validate'; - if (action == "validate") { - return pattern.test(html); - } else { - do { - oldHtml = html; - html = html.replace(tagOrComment, ''); - } while (html !== oldHtml); - return html.replace(/' : ' <' + response[i].mess_account + '>' + }); + } + } + }; -PMDesigner.ProcessFilesManager.createFirst = function (processFileManagerOptionPath, optionCreation) { - PMDesigner.ProcessFilesManager(processFileManagerOptionPath, optionCreation); -}; + function loadABETemplateField(templates) { + var templateField = abeForm.getField('ABE_TEMPLATE'), i; + for (i in templates) { + if (templateField !== null) { + templateField.addOption({ + value: templates[i].FIELD, + label: templates[i].NAME + }); + } + abeTemplates.options.push({ + value: templates[i].FIELD, + label: templates[i].NAME + }); + } + }; + /** + * Loads the email accounts settings + * @param response + */ + function loadABEmailAccount(response) { + var accountField = abeForm.getField('ABE_EMAIL_SERVER_UID') || null, + i; -(function () { - PMDesigner.assigmentRules = function (event) { - var formAssignmentRules, - i, - tabPanelAssignmentRules, - windowAssignmentRules, - dataProperties, - activity = event, - pageSizeAssignment = 9, - pageSizeAssignmentAD = 9, - quickMessageWindow = new QuickMessageWindow(), - arrayObjectUserList = [], - arrayObjectUserList2 = [], - arrayObjectUsers = [], - arrayObjectUsers2 = [], - arrayObjectAdhocUser = [], - arrayObjectAdhocUser2 = [], - arrayObjectAdhocUserList = [], - arrayObjectAdhocUserList2 = [], - warningMessageWindowDirty, - restClient, - assigmentPanelGlobal, - assigmentPanelUser, - panelTitleUser, - titleUser, - panelGridUser, - buttonsUsers, - gridUsers, - assigmentPanelUserList, - panelTitleUserList, - titleUserList, - panelGridUserList, - buttonsUserList, - gridUserList, - assigmentPanelGlobalAD, - assigmentPanelUserAD, - panelTitleUserAD, - titleUserAD, - panelSearchUserAD, - searchGridUserAD, - panelGridUserAD, - buttonsUsersAD, - gridUsersAD, - assigmentPanelUserListAD, - panelTitleUseListAD, - titleUserListAD, - panelGridUserListAD, - buttonsUserListAD, - gridUserListAD, - panelContainerRules, - panelContainerUsers, - panelContainerUsersAdHoc, - loadTrigger, - loadFormData, - loadServerData, - loadFreeUsers, - loadAssignmentUsers, - loadAdHocFreeUsers, - loadAdHocAssignmentUsers, - updateRules, - allHidden, - changeRadioButtons, - visibleService, - hiddenTab, - saveData, - saveOrUpdateUserAndAdHocUsers, - applyStyles, - applyStylesAD, - assignee, - remove, - assigneeAD, - removeAD, - groupRows, - flashMessage = new PMUI.ui.FlashMessage({ - message: '', - appendTo: document.body, - duration: 1000, - severity: "success" + if (response instanceof Array) { + for (i = 0; i < response.length; i += 1) { + if (accountField !== null) { + accountField.addOption({ + value: response[i].mess_uid, + label: response[i].mess_engine === "MAIL" ? + response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name : defaultServerlabel : response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name + ' <' + response[i].mess_account + '>' : ' <' + response[i].mess_account + '>' + }); + } + abeEmailAcount.options.push({ + value: response[i].mess_uid, + label: response[i].mess_engine === "MAIL" ? + response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name : defaultServerlabel : response[i].mess_from_name && response[i].mess_from_name !== "" ? + response[i].mess_from_name + ' <' + response[i].mess_account + '>' : ' <' + response[i].mess_account + '>' + }); + } + } + + }; + + function loadABEDynaformField(dynaforms) { + var dynaformField = abeForm.getField('DYN_UID'), i; + for (i in dynaforms) { + if (dynaformField !== null) { + dynaformField.addOption({ + value: dynaforms[i].DYN_UID, + label: dynaforms[i].DYN_NAME + }); + } + abeDynaforms.options.push({ + value: dynaforms[i].DYN_UID, + label: dynaforms[i].DYN_NAME }); + } + } - warningMessageWindowDirty = new PMUI.ui.MessageWindow({ - id: 'warningMessageWindowDirty', - windowMessageType: 'warning', - width: 490, - bodyHeight: 'auto', - title: 'Routing Rule'.translate(), - message: 'Are you sure you want to discard your changes?'.translate(), - footerItems: [{ - id: 'warningMessageWindowDirtyButtonNo', - text: 'No'.translate(), - visible: true, - handler: function () { - warningMessageWindowDirty.close(); - }, - buttonType: "error" - }, { - id: 'warningMessageWindowDirtyButtonYes', - text: 'Yes'.translate(), - visible: true, - handler: function () { - warningMessageWindowDirty.close(); - windowAssignmentRules.close(); - }, - buttonType: "success" - }] - }); - formAssignmentRules = new PMUI.form.Form({ - id: 'formAssignmentRules', - visibleHeader: false, - buttonPanelPosition: 'top', - width: 910, - items: [ - new PMUI.field.RadioButtonGroupField({ - id: 'formTasAssignType', - name: 'tas_assign_type', - label: 'Case assignment method'.translate(), - required: false, - controlPositioning: 'horizontal', - maxDirectionOptions: 3, - options: [{ - id: 'formTasAssignTypeCyclical', - label: 'Cyclical Assignment'.translate(), - value: 'BALANCED', - selected: true - }, { - id: 'formTasAssignTypeManual', - label: 'Manual Assignment'.translate(), - value: 'MANUAL' - }, { - id: 'formTasAssignTypeValue', - label: 'Value Based Assignment'.translate(), - value: 'EVALUATE' - }, { - id: 'formTasAssignTypeReports', - label: 'Reports to'.translate(), - value: 'REPORT_TO' - }, { - id: 'formTasAssignTypeSelf', - label: 'Self Service'.translate(), - value: 'SELF_SERVICE' - }, { - id: 'formTasAssignTypeSelfValue', - label: 'Self Service Value Based Assignment'.translate(), - value: 'SELF_SERVICE_EVALUATE' - }, { - id: 'formTasAssignTypeParallel', - label: 'Parallel Assignment'.translate(), - value: 'MULTIPLE_INSTANCE' - }, { - id: 'formTasAssignTypeParallel', - label: 'Value Based Assignment'.translate(), - value: 'MULTIPLE_INSTANCE_VALUE_BASED' - } - ], - onChange: function (newVal, oldVal) { - changeRadioButtons(newVal); + function loadServerData() { + var restClient, i; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: { + "formconfig": { + "url": 'project/' + PMDesigner.project.id + '/activity/' + activity.id, + "method": 'GET' }, - }), new CriteriaField({ - id: 'formAssignmentRulesVariable', - pmType: 'text', - name: 'tas_assign_variable', - valueType: 'string', - label: 'Variable for Value Based Assignment'.translate(), - controlsWidth: DEFAULT_WINDOW_WIDTH - 527 - }), new CriteriaField({ - id: 'formAssignmentRulesVariableSelf', - pmType: 'text', - name: 'tas_group_variable', - valueType: 'string', - label: 'Variable for Self Service Value Based Assignment'.translate(), - controlsWidth: DEFAULT_WINDOW_WIDTH - 527 - }), { - id: 'formAssignmentRulesSetTimeout', - pmType: 'checkbox', - name: 'tas_selfservice_timeout', - label: 'Set a timeout'.translate(), - options: [{ - id: 'formAssignmentRulesSetTimeoutOption', - label: '', - value: '1' - } - ], - onChange: function (val) { - visibleService(this.controls[0].selected); + "calendar": { + "url": 'calendar', + "method": 'GET' + }, + "templates": { + "url": 'project/' + PMDesigner.project.id + '/file-manager?path=templates', + "method": 'GET' + }, + "emailserver": { + "url": 'project/' + PMDesigner.project.id + '/email-event/accounts/emailServer', + "method": 'GET' + } + } + }, + functionSuccess: function (xhr, response) { + loadTemplate(response["templates"].response, 'tas_def_message_template'); + loadTemplate(response["templates"].response, 'tas_receive_message_template'); + loadCalendar(response["calendar"].response); + loadFormData(response["formconfig"].response); + loadEmailAccount(response["emailserver"].response, 'tas_email_server_uid'); + loadEmailAccount(response["emailserver"].response, 'tas_receive_server_uid'); + + /*----------------------------------********---------------------------------*/ + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + if (consolidated == '1') { + $.extend(restClient.data.calls, { + "steps": { + 'url': 'project/' + PMDesigner.project.id + '/activity/' + activity.id + '/steps', + 'method': 'GET' + }, + "consolidate": { + "url": 'consolidated/' + activity.id, + "method": 'GET' + } + }); + } + /*----------------------------------********---------------------------------*/ + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + } + + function visibleContentType(value) { + formNotifications.getField('tas_def_message_template').disable(); + formNotifications.getField('tas_def_message').disable(); + if (value === 'text') { + formNotifications.getField('tas_def_message').enable(); + formNotifications.getField('tas_def_message').setVisible(true); + formNotifications.getField('tas_def_message_template').setVisible(false); + } + if (value === 'template') { + formNotifications.getField('tas_def_message_template').enable(); + formNotifications.getField('tas_def_message').setVisible(false); + formNotifications.getField('tas_def_message_template').setVisible(true); + } + }; + /** + * content type handler, enable or disable templates or message field + * @param value + */ + function visibleContentTypeReceive(value) { + formNotifications.getField('tas_receive_message_template').disable(); + formNotifications.getField('tas_receive_message').disable(); + if (value === 'text') { + formNotifications.getField('tas_receive_message').enable(); + formNotifications.getField('tas_receive_message').setVisible(true); + formNotifications.getField('tas_receive_message_template').setVisible(false); + } + if (value === 'template') { + formNotifications.getField('tas_receive_message_template').enable(); + formNotifications.getField('tas_receive_message').setVisible(false); + formNotifications.getField('tas_receive_message_template').setVisible(true); + } + }; + function saveData() { + var tabPanel = windowProperties.getItem('windowPropertiesTabPanel'), + tabItems = tabPanel.getItems(), + valid = true, + panel, + tas_transfer_fly, + tas_send_last_email, + tas_receive_last_email, + dataCaseLabels, + dataDefinitions, + dataTimingControl, + dataNotification, + consolidated_enable, + message, + i; + + for (i = 0; i < tabItems.length; i += 1) { + panel = tabItems[i].getPanel(); + if (panel instanceof PMUI.form.Form) { + valid = valid && panel.isValid(); + } else { + if (panel.getID() === "ActionsByEmailPanel") { + if (!abeForm.isValid()) { + valid = false; } - }, { - id: 'formAssignmentRulesTime', - pmType: 'text', - name: 'tas_selfservice_time', - valueType: 'string', - label: 'Time'.translate(), - required: true, - validators: [{ - pmType: "regexp", - criteria: /^[0-9]*$/, - errorMessage: "Please enter a numeric value".translate() - }] - }, { - id: 'formAssignmentRulesTimeUnit', - pmType: 'dropdown', - name: 'tas_selfservice_time_unit', - label: 'Time unit'.translate(), - options: [{ - id: 'formAssignmentRulesTimeUnitOption1', - label: 'Hours'.translate(), - value: 'HOURS' - }, { - id: 'formAssignmentRulesTimeUnitOption2', - label: 'Days'.translate(), - value: 'DAYS' - }, { - id: 'formAssignmentRulesTimeUnitOption3', - label: 'Minutes'.translate(), - value: 'MINUTES' - }] - }, { - id: 'formAssignmentRulesTrigger', - pmType: 'dropdown', - name: 'tas_selfservice_trigger_uid', - label: 'Trigger to execute'.translate(), - required: true, - options: [{ - id: 'formAssignmentRulesTriggerOption1', - value: '', - label: '' - }] - }, { - id: 'formAssignmentRulesTriggerExecute', - pmType: 'dropdown', - name: 'tas_selfservice_execution', - label: 'Execute Trigger'.translate(), - options: [{ - id: 'formAssignmentRulesTriggerExecute1', - label: 'Every time scheduled by cron'.translate(), - value: 'EVERY_TIME' - }, { - id: 'formAssignmentRulesTriggerExecute2', - label: 'Once'.translate(), - value: 'ONCE' - }] } - ] - }); - restClient = new PMRestClient({ - endpoint: 'projects', - typeRequest: 'get', - messageError: "There are problems, please try again.".translate(), + } + if (!valid) { + tabItems[i].select(); + return; + } + } + /*----------------------------------********---------------------------------*/ + + tas_transfer_fly = formTimingControl.getField('tas_transfer_fly').getValue() === '["1"]'; + tas_send_last_email = formNotifications.getField('tas_send_last_email').getValue() === '["1"]'; + tas_receive_last_email = formNotifications.getField('tas_receive_last_email').getValue() === '["1"]'; + + if (tas_transfer_fly !== false) { + var a = formTimingControl.getField('tas_transfer_fly').getValue(); + formTimingControl.reset(); + formTimingControl.getField('tas_transfer_fly').setValue(a); + formTimingControl.getField('tas_duration').setValue('1'); + formTimingControl.getField('tas_timeunit').setValue('DAYS'); + formTimingControl.getField('tas_type_day').setValue(''); + formTimingControl.getField('tas_calendar').setValue(''); + } + + if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { + dataDefinitions = getData2PMUI(formDefinitions.html); + dataCaseLabels = getData2PMUI(formCaseLabels.html); + dataTimingControl = getData2PMUI(formTimingControl.html); + dataNotification = getData2PMUI(formNotifications.html); + if (!dataCaseLabels) { + dataCaseLabels = {}; + } + if (!dataTimingControl) { + dataTimingControl = {}; + } + if (!dataNotification) { + dataNotification = {}; + } + } else { + dataDefinitions = formDefinitions.getData(); + dataCaseLabels = formCaseLabels.getData(); + dataTimingControl = formTimingControl.getData(); + dataNotification = formNotifications.getData(); + } + + if (dataDefinitions['tas_title']) { + dataProperties.tas_title = dataDefinitions['tas_title']; + } + if (dataDefinitions['tas_description']) { + dataProperties.tas_description = dataDefinitions['tas_description']; + } + if (dataDefinitions['tas_priority_variable'] || typeof dataDefinitions['tas_priority_variable'] == "string") { + dataProperties.tas_priority_variable = dataDefinitions['tas_priority_variable']; + } + if (dataDefinitions['tas_derivation_screen_tpl'] || dataDefinitions['tas_derivation_screen_tpl'] == "") { + dataProperties.tas_derivation_screen_tpl = dataDefinitions['tas_derivation_screen_tpl']; + } + dataProperties.tas_def_title = dataCaseLabels['tas_def_title']; + dataProperties.tas_def_description = dataCaseLabels['tas_def_description']; + dataProperties.tas_transfer_fly = tas_transfer_fly ? 'TRUE' : 'FALSE'; + if (dataTimingControl['tas_duration']) { + dataProperties.tas_duration = dataTimingControl['tas_duration']; + } + if (dataTimingControl['tas_timeunit']) { + dataProperties.tas_timeunit = dataTimingControl['tas_timeunit']; + } + if (dataTimingControl['tas_type_day']) { + dataProperties.tas_type_day = dataTimingControl['tas_type_day']; + } + if (dataTimingControl['tas_calendar']) { + dataProperties.tas_calendar = dataTimingControl['tas_calendar']; + } + dataProperties.tas_send_last_email = tas_send_last_email ? 'TRUE' : 'FALSE'; + if (dataNotification['tas_not_email_from_format']) { + dataProperties.tas_not_email_from_format = dataNotification['tas_not_email_from_format']; + } + if (dataNotification['tas_def_subject_message']) { + dataProperties.tas_def_subject_message = dataNotification['tas_def_subject_message']; + } + if (dataNotification['tas_def_message_type']) { + dataProperties.tas_def_message_type = dataNotification['tas_def_message_type']; + } + if (dataNotification['tas_def_message']) { + dataProperties.tas_def_message = dataNotification['tas_def_message']; + } + if (dataNotification['tas_def_message_template']) { + dataProperties.tas_def_message_template = dataNotification['tas_def_message_template']; + } + if (dataNotification['tas_email_server_uid'] !== 'undefined' && dataNotification['tas_email_server_uid'] !== null) { + dataProperties.tas_email_server_uid = dataNotification['tas_email_server_uid']; + } + + dataProperties.tas_receive_last_email = tas_receive_last_email ? 'TRUE' : 'FALSE'; + if (dataNotification['tas_receive_email_from_format']) { + dataProperties.tas_receive_email_from_format = dataNotification['tas_receive_email_from_format']; + } + if (dataNotification['tas_receive_server_uid'] !== 'undefined' && dataNotification['tas_receive_server_uid'] !== null) { + dataProperties.tas_receive_server_uid = dataNotification['tas_receive_server_uid']; + } + if (dataNotification['tas_receive_subject_message']) { + dataProperties.tas_receive_subject_message = dataNotification['tas_receive_subject_message']; + } + if (dataNotification['tas_receive_message_type']) { + dataProperties.tas_receive_message_type = dataNotification['tas_receive_message_type']; + } + if (dataNotification['tas_receive_message']) { + dataProperties.tas_receive_message = dataNotification['tas_receive_message']; + } + if (dataNotification['tas_receive_message_template']) { + dataProperties.tas_receive_message_template = dataNotification['tas_receive_message_template']; + } + /*----------------------------------********---------------------------------*/ + + if (consolidated == '1') { + consolidated_enable = false; + if (formConsolidated.getField('consolidated_enable').getValue() == '["1"]') { + consolidated_enable = true; + if (!formConsolidated.isValid()) { + return; + } + } + dataProperties.consolidate_data = { + "consolidated_enable": consolidated_enable, + "consolidated_dynaform": formConsolidated.getField('consolidated_dynaform').getValue(), + "consolidated_table": formConsolidated.getField('consolidated_table').getValue(), + "consolidated_title": formConsolidated.getField('consolidated_title').getValue(), + "consolidated_report_table": formConsolidated.getField('consolidated_report_table').getValue() + }; + } + + (new PMRestClient({ + endpoint: 'activity/' + activity.id, + typeRequest: 'update', + messageError: '', + data: { + definition: {}, + properties: dataProperties + }, + functionSuccess: function (xhr, response) { + setNameActivity(dataProperties.tas_title); + windowProperties.close(); + }, functionFailure: function (xhr, response) { PMDesigner.msgWinError(response.error.message); - } - }); + }, + messageSuccess: 'Task properties saved successfully'.translate(), + flashContainer: document.body + })).executeRestClient(); + } + + function setFocusTab(tab) { + var style; + $customGrid = $("#customGrid"); + $customGrid.hide().appendTo($("#windowProperties").find(".pmui-window-body:eq(0)")); + + if (tab.getTitle() === 'Definitions'.translate()) { + formDefinitions.getField('tas_title').setFocus(); + } + if (tab.getTitle() === 'Case Labels'.translate()) { + formCaseLabels.getField('tas_def_title').setFocus(); + style = $('#formCaseLabelsDescription .pmui-field-label').attr("style"); + style = style + ' float: left;'; + $('#formCaseLabelsDescription .pmui-field-label').attr("style", style); + } + if (tab.getTitle() === 'Timing Control'.translate()) { + formTimingControl.getField('tas_duration').setFocus(); + } + if (tab.getTitle() === 'Notifications'.translate()) { + formNotifications.getField('tas_def_subject_message').setFocus(); + style = $('#formNotificationsMessage .pmui-field-label').attr("style"); + style = style + ' float: left;'; + $('#formNotificationsMessage .pmui-field-label').attr("style", style); + + style = $('#tas_receive_message .pmui-field-label').attr("style"); + style = style + ' float: left;'; + $('#tas_receive_message .pmui-field-label').attr("style", style); + } + if (tab.getTitle() === 'Actions by Email'.translate()) { + abeForm.getField("ABE_TYPE").onChange(abeForm.getField("ABE_TYPE").getValue()); + } + } + + function isDirty() { + return formDefinitions.isDirty() || + formCaseLabels.isDirty() || + formTimingControl.isDirty() || + formNotifications.isDirty(); + } + + function setNameActivity(name) { + activity.setName(name); + activity.setActName(name); + PMDesigner.project.dirty = true; + } + + windowProperties.open(); + windowProperties.showFooter(); + + applyStyleWindowForm(windowProperties); + if (consolidated == '1') { + formConsolidated.getField('consolidated_report_table').setVisible(false); + } + /*----------------------------------********---------------------------------*/ + function customDOM() { + $customGrid = $("#customGrid"); + $customGrid.show().appendTo($("#customGridPanel").find("fieldset:eq(0)")); + document.getElementById("customGridPanel").style.width = "720px"; + document.getElementById("customGridPanel").style.padding = ""; + document.getElementById("customGridPanel").getElementsByTagName("fieldset")[0].style.width = "100%"; + $(".pmui-gridpanel-footer").css({"text-align": "center", "margin-top": "10px", "width": "120%"}); + $(".pmui-gridpanel-footer").removeClass("pmui-gridpanel-footer"); + } - assigmentPanelGlobal = new PMUI.core.Panel({ - id: "assigmentPanelGlobal", - layout: "hbox", - width: DEFAULT_WINDOW_WIDTH - }); - assigmentPanelUser = new PMUI.core.Panel({ - id: "assigmentPanelUser", - layout: "vbox", - width: "60%", - style: { - cssClasses: [ - 'mafe-panel-assignment-white' - ] - } - }); - panelTitleUser = new PMUI.core.Panel({ - id: "panelTitleUser", - layout: "hbox" - }); - titleUser = new PMUI.ui.TextLabel({ - id: "titleUser", - label: " ", - textMode: 'plain', - text: 'Available users list'.translate(), - style: { - cssClasses: [ - 'mafe-designer-assigment-title' - ] - } - }); - panelGridUser = new PMUI.core.Panel({ - id: "panelGridUser", - layout: "hbox", - style: { - cssClasses: ["mafe-panel"] - } - }); - buttonsUsers = new PMUI.field.RadioButtonGroupField({ - id: "buttonsUsers", - controlPositioning: 'horizontal', - maxDirectionOptions: 3, - options: [{ - id: 'buttonAllAv', - label: 'View all'.translate(), - value: 'all', - selected: true - }, { - id: 'buttonUsersAv', - label: 'View users'.translate(), - value: 'user' - }, { - id: 'buttonGroupsAv', - label: 'View groups'.translate(), - value: 'group' - }], - onChange: function (newVal, oldVal) { - switch (newVal) { - case "user" : - gridUsers.typeList = "user"; - break; - case "group": - gridUsers.typeList = "group"; - break; - default: - gridUsers.typeList = ""; - break; + function clearAddOptionForm() { + abeAddOption.getField("abe_custom_value_add").setValue(""); + abeAddOption.getField("abe_custom_label_add").setValue(""); + abeAddOption.getField("abe_custom_format_add").setValue(""); + abeAddOption.getField("buttonFieldCancel").setVisible(false); + abeAddOption.getField("buttonFieldAdd").setValue("Add".translate()); + editRow = null; + }; + function addAcceptedValue() { + var abeValue = abeAddOption.getField("abe_custom_value_add").getValue(), + abeLabel = abeAddOption.getField("abe_custom_label_add").getValue(), + abeFormat = abeAddOption.getField("abe_custom_format_add").getValue(); + + if (abeAddOption && !abeAddOption.isValid()) { + return; + } + + if (!evaluateTags(abeFormat, 'validate')) { + return; + } + + if (editRow === null) { + customGrid.addItem(new PMUI.grid.GridPanelRow({ + data: { + abe_custom_value: abeValue, + abe_custom_label: abeLabel, + abe_custom_format: abeFormat } - gridUsers.goToPage(0); - } - }); - gridUsers = new PMUI.grid.GridPanel({ - id: "gridUsers", - pageSize: pageSizeAssignment - 1, - edges: 2, - behavior: 'dragdropsort', - displayedPages: 2, - filterable: true, - filterPlaceholder: 'Search ...'.translate(), - emptyMessage: 'No records found'.translate(), - nextLabel: 'Next'.translate(), - previousLabel: 'Previous'.translate(), - tableContainerHeight: 242, - customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { - return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + })); + } else { + editRow.setData({ + abe_custom_value: abeValue, + abe_custom_label: abeLabel, + abe_custom_format: abeFormat + }); + editRow = null; + abeAddOption.getField("buttonFieldCancel").setVisible(false); + abeAddOption.getField("buttonFieldAdd").setValue("Add".translate()); + } + abeAddOption.getField("abe_custom_value_add").setValue(""); + abeAddOption.getField("abe_custom_label_add").setValue(""); + abeAddOption.getField("abe_custom_format_add").setValue(""); + } + + function customGridRowEdit(row) { + editRow = row; + row = row.getData(); + if (abeAddOption) { + abeAddOption.getField("abe_custom_value_add").setValue(row.abe_custom_value); + abeAddOption.getField("abe_custom_label_add").setValue(row.abe_custom_label); + abeAddOption.getField("abe_custom_format_add").setValue(row.abe_custom_format); + abeAddOption.getField("buttonFieldCancel").setVisible(true); + abeAddOption.getField("buttonFieldAdd").setValue("Save".translate()); + } + } + + function evaluateTags(html, action) { + var oldHtml; + var tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*'; + var pattern = /^[a-zA-Z0-9\s\[\]\.\-_#%;,=:()']*$/; + var tagOrComment = new RegExp( + '<(?:' + // Comment body. + + '!--(?:(?:-*[^->])*--+|-?)' + // Special "raw text" elements whose content should be elided. + + '|script\\b' + tagBody + '>[\\s\\S]*?[\\s\\S]*?', + 'gi'); + + var action = (typeof action === 'undefined') ? 'delete' : 'validate'; + if (action == "validate") { + return pattern.test(html); + } else { + do { + oldHtml = html; + html = html.replace(tagOrComment, ''); + } while (html !== oldHtml); + return html.replace(/ -1) { - arrayObjectAdhocUser.splice(index, 1); - } - }, - onDrop: function (a, row) { - grid = this; - removeAD(row); - gridUserListAD.goToPage(gridUserListAD.currentPage); - grid.goToPage(grid.currentPage); - flashMessage.setMessage("The user/group was successfully removed".translate()); - flashMessage.setAppendTo(windowAssignmentRules.getHTML()); - flashMessage.show(); - return false; - }, - style: { - cssClasses: [ - 'mafe-designer-assigment-grid' - ] - } - }); - assigmentPanelUserListAD = new PMUI.core.Panel({ - id: "assigmentPanelUserListAD", - layout: "vbox", - style: { - cssClasses: [ - 'mafe-panel-assignment-white' - ] + })).executeRestClient(); + } + } + /** + * Save Content of the Html Editor + */ + function saveHtmlEditor() { + var index = 0, + codeMirror = windowCode.getItems()[index], + contentCodeMirror = codeMirror.getValue(), + rowRelatedUID = codeMirror.related_row, + request; + + + request = new PMRestClient({ + endpoint: 'file-manager/' + rowRelatedUID, + typeRequest: 'update', + messageError: 'Error Update File'.translate(), + data: { + prf_content: contentCodeMirror }, - width: "60%" - }); - panelTitleUseListAD = new PMUI.core.Panel({ - id: "panelTitleUseListAD", - layout: "hbox" - }); - titleUserListAD = new PMUI.ui.TextLabel({ - id: "titleUserListAD", - textMode: 'plain', - text: 'Assigned users list'.translate(), - style: { - cssClasses: [ - 'mafe-designer-assigment-title' - ] - } - }); - panelGridUserListAD = new PMUI.core.Panel({ - id: "panelGridUserListAD", - layout: "hbox", - style: { - cssClasses: ["mafe-panel"] - } - }); - buttonsUserListAD = new PMUI.field.RadioButtonGroupField({ - id: "buttonsUserListAD", - controlPositioning: 'horizontal', - maxDirectionOptions: 3, - options: [{ - id: 'buttonAllAs', - label: 'View all'.translate(), - value: 'all', - selected: true - }, { - id: 'buttonUsersAs', - label: 'View users'.translate(), - value: 'user' - }, { - id: 'buttonGroupsAs', - label: 'View groups'.translate(), - value: 'group' - }], - onChange: function (newVal, oldVal) { - switch (newVal) { - case "user" : - gridUserListAD.typeList = "user"; - break; - case "group": - gridUserListAD.typeList = "group"; - break; - default: - gridUserListAD.typeList = ""; - break; + functionSuccess: function (xhr, response) { + windowCode.close(); + if (processFileManagerOptionPath == "templates") { + PMDesigner.msgFlash('File updated successfully'.translate(), gridTemplate); + windowFilesManager.open(); + loadTemplate(); } - gridUserListAD.goToPage(0); + if (processFileManagerOptionPath == "public") { + PMDesigner.msgFlash('File updated successfully'.translate(), gridPublic); + windowFilesManager.open(); + loadPublic(); + } + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); } }); - gridUserListAD = new PMUI.grid.GridPanel({ - id: "gridUserListAD", - pageSize: pageSizeAssignmentAD - 1, - behavior: 'dragdropsort', - filterable: true, - filterPlaceholder: 'Search ...'.translate(), - nextLabel: 'Next'.translate(), - previousLabel: 'Previous'.translate(), - tableContainerHeight: 242, - customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { - return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); - }, - emptyMessage: function () { - var div = document.createElement('div'), - span = document.createElement('span'); - div.appendChild(span); - div.className = "mafe-grid-panel-empty"; - div.style.height = gridUserListAD.dom.tableContainer.style.height; - div.style.width = gridUserListAD.dom.tableContainer.style.width; - span.innerHTML = 'Drag & Drop a User or a Group here'.translate(); - return div; + request.executeRestClient(); + } + + function loadFileManager() { + (new PMRestClient({ + endpoint: 'file-manager', + typeRequest: 'get', + messageError: '', + functionSuccess: function (xhr, response) { + gridFilesManager.clearItems(); + for (var i = 0; i < response.length; i++) { + gridFilesManager.addDataItem({prf_path: response[i].name}); + } + if (openCreateTemplates) { + gridFilesManager.onRowClick(gridFilesManager.getItems()[0]); + newfile(); + } }, - onEmpty: function (grid, cell) { - gridUserListAD.dom.tableContainer.style.overflow = "hidden"; + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + })).executeRestClient(); + } + + function loadTemplate() { + (new PMRestClient({ + endpoint: 'file-manager', + typeRequest: 'get', + messageError: '', + data: { + path: processFileManagerOptionPath, + get_content: true }, - dynamicLoad: { - keys: { - server: HTTP_SERVER_HOSTNAME, - projectID: PMDesigner.project.projectId, - workspace: WORKSPACE, - accessToken: PMDesigner.project.tokens.access_token, - endPoint: 'project/' + PMDesigner.project.id + '/activity/' + activity.id + '/adhoc-assignee/paged' + functionSuccess: function (xhr, response) { + gridTemplate.clearItems(); + gridTemplate.clearItemsColumns(); + for (var i = 0; i < response.length; i++) { + gridTemplate.addDataItem({ + prf_filename: response[i].prf_filename, + prf_content: response[i].prf_content, + prf_uid: response[i].prf_uid, + prf_assigned_routing_screen: response[i].prf_derivation_screen + }); } + gridTemplate.sort('prf_filename', 'asc'); }, - customDataRest: function (data) { - var i; - for (i = 0; i < data.length; i += 1) { - if (data[i].ada_type == "group") { - data[i]["assignee"] = data[i].ada_name; - } else { - data[i]["assignee"] = data[i].ada_name + " " + data[i].ada_lastname + " (" + data[i].ada_username + ")"; - } + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + })).executeRestClient(); + checkDerivationScreen(); + } + + function loadPublic() { + (new PMRestClient({ + endpoint: 'file-manager', + typeRequest: 'get', + messageError: '', + data: { + path: processFileManagerOptionPath, + get_content: false + }, + functionSuccess: function (xhr, response) { + gridPublic.clearItems(); + for (var i = 0; i < response.length; i++) { + gridPublic.addDataItem({ + prf_filename: response[i].prf_filename, + prf_uid: response[i].prf_uid + }); } - return data; + gridPublic.sort('prf_filename', 'asc'); }, - columns: [ - { - id: 'gridUserListADButtonLabel', - title: "", - width: "13%", - dataType: 'button', - buttonLabel: function (row, data) { - return data.lastName; - }, - buttonStyle: { - cssClasses: [ - 'mafe-grid-button' - ] - }, - onButtonClick: function (row, grid) { - var option, select; - select = document.createElement("span"); - select.id = "list-usersIngroup"; - option = document.createElement("span"); - option.id = "list-usersIngroup-iem"; - if (row.getData()["ada_type"] === "group") { - var i, - restClient = new PMRestClient({ - typeRequest: 'get', - functionSuccess: function (xhr, response) { - var optionClone, i; - for (i = 0; i < response.length; i += 1) { - if (i == 10) { - optionClone = option.cloneNode(false); - optionClone.innerHTML = ". . ."; - select.appendChild(optionClone); - } else { - optionClone = option.cloneNode(false); - optionClone.textContent = "- " + response[i].usr_firstname + ' ' + response[i].usr_lastname; - optionClone.title = response[i].usr_firstname + ' ' + response[i].usr_lastname; - select.appendChild(optionClone); - } - } - if (!optionClone) { - optionClone = option.cloneNode(false); - optionClone.textContent = "No users".translate(); - select.appendChild(optionClone); - } + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + })).executeRestClient(); + } - quickMessageWindow.show($(row.html).find('a')[0], select); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: 'There are problems saving the assigned user, please try again.'.translate() - }); - restClient.setBaseEndPoint("group/" + row.getData()["ada_uid"] + "/users?start=0&limit=11"); - restClient.executeRestClient(); - } - } - }, - { - title: '', - dataType: 'string', - columnData: "assignee", - alignmentCell: "left", - width: "330px" - }, - { - id: 'gridUserListADButtonDelete', - title: '', - dataType: 'button', - width: "10%", - buttonStyle: { - cssClasses: [ - 'mafe-button-delete-assign' - ] - }, - buttonLabel: function (row, data) { - var sw = row.getData()["ada_type"] === 'user'; - row.getCells()[0].content.style.addClasses([sw ? 'button-icon-user' : 'button-icon-group']); - return ''; - }, - onButtonClick: function (row, grid) { - var dataRow = {}; - grid = (grid != null) ? grid : gridUserListAD; - removeAD(row); - grid.goToPage(grid.currentPage); - gridUsersAD.goToPage(gridUsersAD.currentPage); - flashMessage.setMessage("The user/group was successfully removed".translate()); - flashMessage.setAppendTo(windowAssignmentRules.getHTML()); - flashMessage.show(); - } + function download() { + var xhr, + win = window, + value = 'blob', + url = HTTP_SERVER_HOSTNAME + '/api/1.0/' + WORKSPACE + '/project/' + PMDesigner.project.id + '/file-manager/' + rowselectedFile.getData().prf_uid + '/download'; + + if (win.XMLHttpRequest) { + xhr = new XMLHttpRequest(); + } else if (win.ActiveXObject) { + xhr = new ActiveXObject('Microsoft.XMLHTTP'); + } + win.URL = win.URL || win.webkitURL; + + xhr.open('GET', url, true); + xhr.responseType = value; + xhr.setRequestHeader('Authorization', 'Bearer ' + PMDesigner.project.keys.access_token); + xhr.setRequestHeader ('Cache-Control', 'no-cache'); + xhr.onload = function () { + if (this.status === 200) { + if (processFileManagerOptionPath == "templates") { + PMDesigner.msgFlash('Start file download successfully'.translate(), gridTemplate); } - ], - onDropOut: function (item, origin, destiny) { + if (processFileManagerOptionPath == "public") { + PMDesigner.msgFlash('Start file download successfully'.translate(), gridPublic); + } + var doc = win.document, a = doc.createElementNS('http://www.w3.org/1999/xhtml', 'a'), event = doc.createEvent('MouseEvents'); + event.initMouseEvent('click', true, false, win, 0, 0, 0, 0, 0, false, false, false, false, 0, null); + var blob = xhr.response; + if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1) || (navigator.userAgent.indexOf("Edge") != -1)) { + window.navigator.msSaveBlob(blob, rowselectedFile.getData().prf_filename); + } + else { + a.href = win.URL.createObjectURL(blob); + a.download = rowselectedFile.getData().prf_filename; + a.dispatchEvent(event); + } + } + }; + xhr.send() + + + } + + function uploadFile() { + var fileSelector = formUploadField.getHTML().getElementsByTagName('input')[0]; + if (fileSelector.files.length === 0) { + PMDesigner.msgFlash('Please select a file to upload'.translate(), windowUpload.footer, "info"); + return; + } + (new PMRestClient({ + endpoint: 'file-manager', + typeRequest: 'post', + messageError: '', + data: { + prf_filename: fileSelector.files[0].name, + prf_path: processFileManagerOptionPath, + prf_content: null }, - onDrop: function (a, row) { - grid = this; - assigneeAD(row); - gridUsersAD.goToPage(gridUsersAD.currentPage); - grid.goToPage(grid.currentPage); - flashMessage.setMessage("Assignee saved successfully".translate()); - flashMessage.setAppendTo(windowAssignmentRules.getHTML()); - flashMessage.show(); - return false; + functionSuccess: function (xhr, response) { + var win = window, fd = new FormData(), xhr, val = 'prf_file'; + fd.append(val, fileSelector.files[0]); + if (win.XMLHttpRequest) + xhr = new XMLHttpRequest(); + else if (win.ActiveXObject) + xhr = new ActiveXObject('Microsoft.XMLHTTP'); + xhr.open('POST', '/api/1.0/' + WORKSPACE + '/project/' + PMDesigner.project.id + '/file-manager/' + response.prf_uid + '/upload', true); + xhr.setRequestHeader('Authorization', 'Bearer ' + PMDesigner.project.keys.access_token); + xhr.onload = function () { + if (this.status === 200) { + formUploadField.reset(); + windowUpload.close(); + if (processFileManagerOptionPath == "templates") { + PMDesigner.msgFlash('File uploaded successfully'.translate(), gridTemplate); + loadTemplate(); + } + if (processFileManagerOptionPath == "public") { + PMDesigner.msgFlash('File uploaded successfully'.translate(), gridPublic); + loadPublic(); + } + } + }; + xhr.send(fd); }, - style: { - cssClasses: [ - 'mafe-designer-assigment-grid' - ] + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); } - }); + })).executeRestClient(); + } - panelContainerRules = new PMUI.core.Panel({ - width: DEFAULT_WINDOW_WIDTH - 55, - height: "auto", - fieldset: true, - items: [ - formAssignmentRules - ] - }); - panelContainerUsers = new PMUI.core.Panel({ - width: DEFAULT_WINDOW_WIDTH, - height: "auto", - fieldset: true, - items: [ - assigmentPanelGlobal - ] - }); - panelContainerUsersAdHoc = new PMUI.core.Panel({ - width: DEFAULT_WINDOW_WIDTH, - height: "auto", - fieldset: true, - items: [ - assigmentPanelGlobalAD - ] + function styleApp() { + try { + gridFilesManager.dom.toolbar.style.display = 'none'; + gridTemplate.dom.toolbar.getElementsByTagName('input')[0].style.visibility = 'hidden'; + gridPublic.dom.toolbar.getElementsByTagName('input')[0].style.visibility = 'hidden'; + + } catch (e) { + } + } + + function disableAllFields() { + windowFilesManager.getItems()[0].setVisible(false); + + } + + function openFolder() { + disableAllFields(); + styleApp(); + + if (processFileManagerOptionPath == "templates") { + windowFilesManager.setTitle("Templates".translate()); + loadTemplate(); + if (flagGridTemplate) { + windowFilesManager.addItem(gridTemplate); + flagGridTemplate = false; + } + + var buttonsTemplate = document.createElement("div"); + buttonsTemplate.id = "buttonsTemplate"; + buttonsTemplate.style.display = "inlineBlock"; + buttonsTemplate.style.float = "right"; + + buttonsTemplate.appendChild(buttonUpload.getHTML()); + buttonsTemplate.appendChild(buttonNew.getHTML()); + //buttonsTemplate.appendChild(buttonBack.getHTML()); + + buttonUpload.defineEvents(); + buttonNew.defineEvents(); + //buttonBack.defineEvents(); + + gridTemplate.dom.toolbar.appendChild(buttonsTemplate); + gridTemplate.setVisible(true); + gridTemplate.dom.toolbar.getElementsByTagName('input')[0].style.visibility = 'visible'; + buttonNew.getHTML().style.top = '-3px'; + } + if (processFileManagerOptionPath == "public") { + windowFilesManager.setTitle("Public Files".translate()); + loadPublic(); + if (flagGridPublic) { + windowFilesManager.addItem(gridPublic); + flagGridPublic = false; + } + var buttonsPublic = document.createElement("div"); + buttonsPublic.id = "buttonsPublic"; + buttonsPublic.style.display = "inlineBlock"; + buttonsPublic.style.float = "right"; + + buttonsPublic.appendChild(buttonUpload.getHTML()); + buttonsPublic.appendChild(buttonPublicCreate.getHTML()); + //buttonsPublic.appendChild(buttonBack.getHTML()); + + buttonUpload.defineEvents(); + buttonPublicCreate.defineEvents(); + //buttonBack.defineEvents(); + + gridPublic.dom.toolbar.appendChild(buttonsPublic); + gridPublic.dom.toolbar.getElementsByTagName('input')[0].style.visibility = 'visible'; + gridPublic.setVisible(true); + buttonPublicCreate.getHTML().style.top = '-3px'; + } + } + /** + * Check Templates Assigned Derivation Screen + * @returns {checkDerivationScreen} + */ + function checkDerivationScreen () { + var gridTemplateAux = gridTemplate, + idRichText = "gridTemplateButtonRichTextEditor", + rowsGrid, + columnsGrid, + dataRowGrid, + columnRichText, + index = 0, + cell = {}, + message = "Editor unavailable", + tooltipMafeClass = "mafe-action-tooltip-black", + i, + max; + + rowsGrid = gridTemplateAux.getItems(); + columnsGrid = gridTemplateAux.getColumns(); + columnRichText = $.grep(columnsGrid, function (item, index) { + return item.id === idRichText; }); + for (i = 0, max = rowsGrid.length; i < max; i += 1) { + dataRowGrid = rowsGrid[i].data.customKeys; + if (dataRowGrid.prf_assigned_routing_screen && columnRichText.length) { + columnRichText[index].disableCell(i); + cell = columnRichText[index].getCells().length ? columnRichText[index].getCells()[i] : cell; + if (!$.isEmptyObject(cell)) { + $(cell.getHTML()).attr('title', message).tooltip({ + tooltipClass: tooltipMafeClass, + position: { + my: 'center top', + at: 'center bottom+4' + } + }); + } + } + } + return this; + } + + if (optionCreation == "CREATION_NORMAL") { + windowFilesManager.open(); + openFolder(); + } else { + windowFilesManager.open(); + openFolder(); + newfile(); + } + checkDerivationScreen(); +}; + +PMDesigner.ProcessFilesManager.createFirst = function (processFileManagerOptionPath, optionCreation) { + PMDesigner.ProcessFilesManager(processFileManagerOptionPath, optionCreation); +}; + +(function () { + PMDesigner.assigmentRules = function (event) { + var formAssignmentRules, + i, + tabPanelAssignmentRules, + windowAssignmentRules, + dataProperties, + activity = event, + pageSizeAssignment = 9, + pageSizeAssignmentAD = 9, + quickMessageWindow = new QuickMessageWindow(), + arrayObjectUserList = [], + arrayObjectUserList2 = [], + arrayObjectUsers = [], + arrayObjectUsers2 = [], + arrayObjectAdhocUser = [], + arrayObjectAdhocUser2 = [], + arrayObjectAdhocUserList = [], + arrayObjectAdhocUserList2 = [], + warningMessageWindowDirty, + restClient, + assigmentPanelGlobal, + assigmentPanelUser, + panelTitleUser, + titleUser, + panelGridUser, + buttonsUsers, + gridUsers, + assigmentPanelUserList, + panelTitleUserList, + titleUserList, + panelGridUserList, + buttonsUserList, + gridUserList, + assigmentPanelGlobalAD, + assigmentPanelUserAD, + panelTitleUserAD, + titleUserAD, + panelSearchUserAD, + searchGridUserAD, + panelGridUserAD, + buttonsUsersAD, + gridUsersAD, + assigmentPanelUserListAD, + panelTitleUseListAD, + titleUserListAD, + panelGridUserListAD, + buttonsUserListAD, + gridUserListAD, + panelContainerRules, + panelContainerUsers, + panelContainerUsersAdHoc, + loadTrigger, + loadFormData, + loadServerData, + loadFreeUsers, + loadAssignmentUsers, + loadAdHocFreeUsers, + loadAdHocAssignmentUsers, + updateRules, + allHidden, + changeRadioButtons, + visibleService, + hiddenTab, + saveData, + saveOrUpdateUserAndAdHocUsers, + applyStyles, + applyStylesAD, + assignee, + remove, + assigneeAD, + removeAD, + groupRows, + flashMessage = new PMUI.ui.FlashMessage({ + message: '', + appendTo: document.body, + duration: 1000, + severity: "success" + }); - tabPanelAssignmentRules = new PMUI.panel.TabPanel({ - id: 'tabPanelAssignmentRules', - width: "100%", - height: "auto", - items: [ - { - id: 'tabUsers', - title: 'Users'.translate(), - panel: panelContainerUsers + warningMessageWindowDirty = new PMUI.ui.MessageWindow({ + id: 'warningMessageWindowDirty', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: 'Routing Rule'.translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [{ + id: 'warningMessageWindowDirtyButtonNo', + text: 'No'.translate(), + visible: true, + handler: function () { + warningMessageWindowDirty.close(); }, - { - id: 'tabUsersAdHoc', - title: 'Ad Hoc Users'.translate(), - panel: panelContainerUsersAdHoc - } - ], - onTabClick: function (item) { - quickMessageWindow.close(); - switch (item.id) { - case 'tabRules': - break; - case 'tabUsers': - applyStyles(); - gridUsers.goToPage(0); - gridUserList.goToPage(0); - break; - case 'tabUsersAdHoc': - applyStylesAD(); - gridUsersAD.goToPage(0); - gridUserListAD.goToPage(0); - break; - } - } + buttonType: "error" + }, { + id: 'warningMessageWindowDirtyButtonYes', + text: 'Yes'.translate(), + visible: true, + handler: function () { + warningMessageWindowDirty.close(); + windowAssignmentRules.close(); + }, + buttonType: "success" + }] }); - windowAssignmentRules = new PMUI.ui.Window({ - id: 'windowAssignmentRules', - title: 'Assignment Rules'.translate() + ': ' + activity.act_name, - height: DEFAULT_WINDOW_HEIGHT, - width: DEFAULT_WINDOW_WIDTH, - footerItems: [ - { - id: 'windowConnectionsButtonCancel', - text: 'Close'.translate(), - handler: function () { - if (formAssignmentRules.isDirty()) { - warningMessageWindowDirty.open(); - warningMessageWindowDirty.showFooter(); - } else { - windowAssignmentRules.close(); - } + formAssignmentRules = new PMUI.form.Form({ + id: 'formAssignmentRules', + visibleHeader: false, + buttonPanelPosition: 'top', + width: 910, + items: [ + new PMUI.field.RadioButtonGroupField({ + id: 'formTasAssignType', + name: 'tas_assign_type', + label: 'Case assignment method'.translate(), + required: false, + controlPositioning: 'horizontal', + maxDirectionOptions: 3, + options: [{ + id: 'formTasAssignTypeCyclical', + label: 'Cyclical Assignment'.translate(), + value: 'BALANCED', + selected: true + }, { + id: 'formTasAssignTypeManual', + label: 'Manual Assignment'.translate(), + value: 'MANUAL' + }, { + id: 'formTasAssignTypeValue', + label: 'Value Based Assignment'.translate(), + value: 'EVALUATE' + }, { + id: 'formTasAssignTypeReports', + label: 'Reports to'.translate(), + value: 'REPORT_TO' + }, { + id: 'formTasAssignTypeSelf', + label: 'Self Service'.translate(), + value: 'SELF_SERVICE' + }, { + id: 'formTasAssignTypeSelfValue', + label: 'Self Service Value Based Assignment'.translate(), + value: 'SELF_SERVICE_EVALUATE' + }, { + id: 'formTasAssignTypeParallel', + label: 'Parallel Assignment'.translate(), + value: 'MULTIPLE_INSTANCE' + }, { + id: 'formTasAssignTypeParallel', + label: 'Value Based Assignment'.translate(), + value: 'MULTIPLE_INSTANCE_VALUE_BASED' + } + ], + onChange: function (newVal, oldVal) { + changeRadioButtons(newVal); }, - buttonType: 'error' - }, - { - buttonType: 'success', - id: 'windowPropertiesButtonSave', - text: "Save".translate(), - handler: function () { - saveData(); + }), new CriteriaField({ + id: 'formAssignmentRulesVariable', + pmType: 'text', + name: 'tas_assign_variable', + valueType: 'string', + label: 'Variable for Value Based Assignment'.translate(), + controlsWidth: DEFAULT_WINDOW_WIDTH - 527 + }), new CriteriaField({ + id: 'formAssignmentRulesVariableSelf', + pmType: 'text', + name: 'tas_group_variable', + valueType: 'string', + label: 'Variable for Self Service Value Based Assignment'.translate(), + controlsWidth: DEFAULT_WINDOW_WIDTH - 527 + }), { + id: 'formAssignmentRulesSetTimeout', + pmType: 'checkbox', + name: 'tas_selfservice_timeout', + label: 'Set a timeout'.translate(), + options: [{ + id: 'formAssignmentRulesSetTimeoutOption', + label: '', + value: '1' } + ], + onChange: function (val) { + visibleService(this.controls[0].selected); + } + }, { + id: 'formAssignmentRulesTime', + pmType: 'text', + name: 'tas_selfservice_time', + valueType: 'string', + label: 'Time'.translate(), + required: true, + validators: [{ + pmType: "regexp", + criteria: /^[0-9]*$/, + errorMessage: "Please enter a numeric value".translate() + }] + }, { + id: 'formAssignmentRulesTimeUnit', + pmType: 'dropdown', + name: 'tas_selfservice_time_unit', + label: 'Time unit'.translate(), + options: [{ + id: 'formAssignmentRulesTimeUnitOption1', + label: 'Hours'.translate(), + value: 'HOURS' + }, { + id: 'formAssignmentRulesTimeUnitOption2', + label: 'Days'.translate(), + value: 'DAYS' + }, { + id: 'formAssignmentRulesTimeUnitOption3', + label: 'Minutes'.translate(), + value: 'MINUTES' + }] + }, { + id: 'formAssignmentRulesTrigger', + pmType: 'dropdown', + name: 'tas_selfservice_trigger_uid', + label: 'Trigger to execute'.translate(), + required: true, + options: [{ + id: 'formAssignmentRulesTriggerOption1', + value: '', + label: '' + }] + }, { + id: 'formAssignmentRulesTriggerExecute', + pmType: 'dropdown', + name: 'tas_selfservice_execution', + label: 'Execute Trigger'.translate(), + options: [{ + id: 'formAssignmentRulesTriggerExecute1', + label: 'Every time scheduled by cron'.translate(), + value: 'EVERY_TIME' + }, { + id: 'formAssignmentRulesTriggerExecute2', + label: 'Once'.translate(), + value: 'ONCE' + }] } - ], - visibleFooter: true, - buttonPanelPosition: 'bottom', - footerAlign: "right", - onBeforeClose: function () { - if (formAssignmentRules.isDirty()) { - warningMessageWindowDirty.open(); - warningMessageWindowDirty.showFooter(); - } else { - windowAssignmentRules.close(); - } + ] + }); + restClient = new PMRestClient({ + endpoint: 'projects', + typeRequest: 'get', + messageError: "There are problems, please try again.".translate(), + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); } }); - loadTrigger = function (response) { - var field = formAssignmentRules.getField('tas_selfservice_trigger_uid'), i; - field.clearOptions(); - field.addOption({ - value: '', - label: '- Select Trigger -'.translate() - }); - for (i = 0; i < response.length; i += 1) { - field.addOption({ - value: response[i].tri_uid, - label: response[i].tri_title - }); - } - }; - loadFormData = function (response) { - dataProperties = response.properties; - formAssignmentRules.getField('tas_assign_type').setValue(dataProperties.tas_assign_type); - formAssignmentRules.getField('tas_assign_variable').setValue(dataProperties.tas_assign_variable); - formAssignmentRules.getField('tas_group_variable').setValue(dataProperties.tas_group_variable); - changeRadioButtons(formAssignmentRules.getField('tas_assign_type').getValue()); - formAssignmentRules.getField('tas_selfservice_timeout').controls[0].deselect(); - if (dataProperties.tas_selfservice_timeout === 1) { - formAssignmentRules.getField('tas_selfservice_timeout').controls[0].select(); - } - formAssignmentRules.getField('tas_selfservice_time').setValue(dataProperties.tas_selfservice_time); - formAssignmentRules.getField('tas_selfservice_time_unit').setValue(dataProperties.tas_selfservice_time_unit); - formAssignmentRules.getField('tas_selfservice_trigger_uid').setValue(dataProperties.tas_selfservice_trigger_uid); - formAssignmentRules.getField('tas_selfservice_execution').setValue(dataProperties.tas_selfservice_execution); - visibleService(dataProperties.tas_selfservice_timeout === 1); - }; - loadServerData = function () { - var restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - calls: [ - { - url: 'project/' + PMDesigner.project.id + '/activity/' + activity.id, - method: 'GET' - }, { - url: 'project/' + PMDesigner.project.id + '/triggers', - method: 'GET' - } - ] - }, - functionSuccess: function (xhr, response) { - loadTrigger(response[1].response); - loadFormData(response[0].response); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } - }); - restClient.setBaseEndPoint(''); - restClient.executeRestClient(); - }; - loadFreeUsers = function (response) { - var i; - gridUsers.clearItems(); - for (i = 0; i < response.length; i += 1) { - gridUsers.addDataItem({ - fullName: response[i].aas_name + " " + response[i].aas_lastname, - ass_uid: response[i].aas_uid, - ass_type: response[i].aas_type - }); - } - }; - loadAssignmentUsers = function (response) { - var i; - gridUserList.clearItems(); - for (i = 0; i < response.length; i += 1) { - gridUserList.addDataItem({ - fullName: response[i].aas_name + " " + response[i].aas_lastname, - ass_uid: response[i].aas_uid, - ass_type: response[i].aas_type - }); - } - }; - loadAdHocFreeUsers = function (response) { - var i; - gridUsersAD.clearItems(); - for (i = 0; i < response.length; i += 1) { - gridUsersAD.addDataItem({ - fullName: response[i].ada_name + " " + response[i].ada_lastname, - ada_uid: response[i].ada_uid, - ass_type: response[i].ada_type - }); - } - }; - loadAdHocAssignmentUsers = function (response) { - var i; - gridUserListAD.clearItems(); - for (i = 0; i < response.length; i += 1) { - gridUserListAD.addDataItem({ - fullName: response[i].ada_name + " " + response[i].ada_lastname, - ada_uid: response[i].ada_uid, - ass_type: response[i].ada_type - }); + assigmentPanelGlobal = new PMUI.core.Panel({ + id: "assigmentPanelGlobal", + layout: "hbox", + width: DEFAULT_WINDOW_WIDTH + }); + assigmentPanelUser = new PMUI.core.Panel({ + id: "assigmentPanelUser", + layout: "vbox", + width: "60%", + style: { + cssClasses: [ + 'mafe-panel-assignment-white' + ] } - }; - updateRules = function () { - (new PMRestClient({ - endpoint: 'activity/' + activity.id, - typeRequest: 'update', - messageError: ' ', - data: { - definition: {}, - properties: dataProperties - }, - messageSuccess: 'Assignment Rules saved successfully'.translate(), - flashContainer: document.body, - functionSuccess: function () { - formAssignmentRules.dirty = false; - windowAssignmentRules.close(); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } - })).executeRestClient(); - }; - allHidden = function () { - formAssignmentRules.getField('tas_assign_variable').setVisible(false); - formAssignmentRules.getField('tas_group_variable').setVisible(false); - formAssignmentRules.getField('tas_selfservice_timeout').setVisible(false); - formAssignmentRules.getField('tas_selfservice_timeout').controls[0].deselect(); - formAssignmentRules.getField('tas_selfservice_time').setVisible(false); - formAssignmentRules.getField('tas_selfservice_time_unit').setVisible(false); - formAssignmentRules.getField('tas_selfservice_trigger_uid').setVisible(false); - formAssignmentRules.getField('tas_selfservice_execution').setVisible(false); - }; - changeRadioButtons = function (newVal) { - allHidden(); - tabPanelAssignmentRules.setVisible(true); - switch (newVal) { - case 'EVALUATE': - formAssignmentRules.getField('tas_assign_variable').setVisible(true); - if (dataProperties.tas_assign_variable === "" || dataProperties.tas_assign_variable === null) { - formAssignmentRules.getField('tas_assign_variable').setValue('@@SYS_NEXT_USER_TO_BE_ASSIGNED'); - } else { - formAssignmentRules.getField('tas_assign_variable').setValue(dataProperties.tas_assign_variable); - } - break; - case 'SELF_SERVICE': - formAssignmentRules.getField('tas_selfservice_timeout').setVisible(true); - break; - case 'SELF_SERVICE_EVALUATE': - formAssignmentRules.getField('tas_group_variable').setVisible(true); - if (dataProperties.tas_group_variable === "@@SYS_GROUP_TO_BE_ASSIGNED" || dataProperties.tas_group_variable === "" || dataProperties.tas_group_variable === null) { - formAssignmentRules.getField('tas_group_variable').setPlaceholder('@@ARRAY_OF_USERS or @@GROUP_UID'); - } else { - formAssignmentRules.getField('tas_group_variable').setValue(dataProperties.tas_group_variable); - } - formAssignmentRules.getField('tas_selfservice_timeout').setVisible(true); - break; - case 'REPORT_TO': - break; - case 'MULTIPLE_INSTANCE_VALUE_BASED': - formAssignmentRules.getField('tas_assign_variable').setLabel("Array of users".translate()); - if (formAssignmentRules.getField('tas_assign_variable').getValue() == "@@SYS_NEXT_USER_TO_BE_ASSIGNED" || formAssignmentRules.getField('tas_assign_variable').getValue() == "") { - formAssignmentRules.getField('tas_assign_variable').setValue(''); - formAssignmentRules.getField('tas_assign_variable').setPlaceholder('@@ARRAY_OF_USERS'); - } - formAssignmentRules.getField('tas_assign_variable').setVisible(true); - if (activity.act_loop_type == "PARALLEL") { - tabPanelAssignmentRules.setVisible(false); - } - break; - default: - break; + }); + panelTitleUser = new PMUI.core.Panel({ + id: "panelTitleUser", + layout: "hbox" + }); + titleUser = new PMUI.ui.TextLabel({ + id: "titleUser", + label: " ", + textMode: 'plain', + text: 'Available users list'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ] } - }; - visibleService = function (value) { - var a = formAssignmentRules.getField('tas_assign_type').getValue(); - if (a === 'SELF_SERVICE' || a === 'SELF_SERVICE_EVALUATE') { - formAssignmentRules.getField('tas_selfservice_time').setVisible(value); - formAssignmentRules.getField('tas_selfservice_time_unit').setVisible(value); - formAssignmentRules.getField('tas_selfservice_trigger_uid').setVisible(value); - formAssignmentRules.getField('tas_selfservice_execution').setVisible(value); + }); + panelGridUser = new PMUI.core.Panel({ + id: "panelGridUser", + layout: "hbox", + style: { + cssClasses: ["mafe-panel"] } - }; - hiddenTab = function (value) { - tabPanelAssignmentRules.showTab(2); - }; - saveData = function () { - var a, b, c, d, tas_selfservice_timeout, data; - tas_selfservice_timeout = formAssignmentRules.getField('tas_selfservice_timeout').getValue() === '["1"]'; - if (!tas_selfservice_timeout) { - //validation because getData method do not work in IE - if (navigator.userAgent.indexOf("MSIE") !== -1 || navigator.userAgent.indexOf("Trident") !== -1) { - data = getData2PMUI(formAssignmentRules.html); - b = data["tas_assign_variable"]; - } else { - b = formAssignmentRules.getField('tas_assign_variable').getValue(); - } - a = formAssignmentRules.getField('tas_assign_type').getValue(); - c = formAssignmentRules.getField('tas_group_variable').getValue(); - d = formAssignmentRules.getField('tas_group_variable').getValue(); - formAssignmentRules.getField('tas_assign_type').setValue(a); - formAssignmentRules.getField('tas_assign_variable').setValue(b); - formAssignmentRules.getField('tas_group_variable').setValue(c); - formAssignmentRules.getField('tas_selfservice_timeout').setValue(d); - formAssignmentRules.getField('tas_selfservice_time').setValue(''); - formAssignmentRules.getField('tas_selfservice_time_unit').setValue(''); - formAssignmentRules.getField('tas_selfservice_trigger_uid').setValue(''); - formAssignmentRules.getField('tas_selfservice_execution').setValue(''); - } else { - if (!formAssignmentRules.isValid()) { - return; + }); + buttonsUsers = new PMUI.field.RadioButtonGroupField({ + id: "buttonsUsers", + controlPositioning: 'horizontal', + maxDirectionOptions: 3, + options: [{ + id: 'buttonAllAv', + label: 'View all'.translate(), + value: 'all', + selected: true + }, { + id: 'buttonUsersAv', + label: 'View users'.translate(), + value: 'user' + }, { + id: 'buttonGroupsAv', + label: 'View groups'.translate(), + value: 'group' + }], + onChange: function (newVal, oldVal) { + switch (newVal) { + case "user" : + gridUsers.typeList = "user"; + break; + case "group": + gridUsers.typeList = "group"; + break; + default: + gridUsers.typeList = ""; + break; } + gridUsers.goToPage(0); } - dataProperties.tas_assign_type = formAssignmentRules.getField('tas_assign_type').getValue(); - dataProperties.tas_assign_variable = formAssignmentRules.getField('tas_assign_variable').getValue() === '' ? '@@SYS_NEXT_USER_TO_BE_ASSIGNED' : formAssignmentRules.getField('tas_assign_variable').getValue(); - dataProperties.tas_group_variable = formAssignmentRules.getField('tas_group_variable').getValue() === '' ? '@@SYS_GROUP_TO_BE_ASSIGNED' : formAssignmentRules.getField('tas_group_variable').getValue(); - dataProperties.tas_selfservice_timeout = tas_selfservice_timeout ? 1 : 0; - dataProperties.tas_selfservice_time = formAssignmentRules.getField('tas_selfservice_time').getValue() !== "" ? parseInt(formAssignmentRules.getField('tas_selfservice_time').getValue(), 10) : 0; - dataProperties.tas_selfservice_time_unit = formAssignmentRules.getField('tas_selfservice_time_unit').getValue(); - dataProperties.tas_selfservice_trigger_uid = formAssignmentRules.getField('tas_selfservice_trigger_uid').getValue(); - dataProperties.tas_selfservice_execution = formAssignmentRules.getField('tas_selfservice_execution').getValue(); - updateRules(); - }; - saveOrUpdateUserAndAdHocUsers = function () { - //Assigne and Remove (users) - var i, b; - if (gridUserList.getItems().length > 0) { - grid = gridUserList; - for (i = 0; i < arrayObjectUserList.length; i += 1) { - b = arrayObjectUserList[i]; - if (arrayObjectUserList2.indexOf(b) == -1) { - assignee(b); + }); + gridUsers = new PMUI.grid.GridPanel({ + id: "gridUsers", + pageSize: pageSizeAssignment - 1, + edges: 2, + behavior: 'dragdropsort', + displayedPages: 2, + filterable: true, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + tableContainerHeight: 242, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + customDataRest: function (data) { + var i; + for (i = 0; i < data.length; i += 1) { + if (data[i].aas_type == "group") { + data[i]["available"] = data[i].aas_name; + } else { + data[i]["available"] = data[i].aas_name + " " + data[i].aas_lastname + " (" + data[i].aas_username + ")"; } } - } - if (gridUsers.getItems().length > 0) { - for (i = 0; i < arrayObjectUsers.length; i += 1) { - b = arrayObjectUsers[i]; - if (arrayObjectUsers2.indexOf(b) == -1) { - remove(arrayObjectUsers[i]); - } + return data; + }, + dynamicLoad: { + keys: { + server: HTTP_SERVER_HOSTNAME, + projectID: PMDesigner.project.projectId, + workspace: WORKSPACE, + accessToken: PMDesigner.project.tokens.access_token, + endPoint: 'project/' + PMDesigner.project.id + '/activity/' + activity.id + '/available-assignee/paged' } - } - //Assigne and Remove (AdHocUsers) - if (gridUserListAD.getItems().length > 0) { - grid = gridUserListAD; - for (i = 0; i < arrayObjectAdhocUserList.length; i += 1) { - b = arrayObjectAdhocUserList[i]; - if (arrayObjectAdhocUserList2.indexOf(b) == -1) { - assigneeAD(b); + }, + columns: [{ + id: 'gridUsersButtonLabel', + title: '', + dataType: 'button', + width: "10%", + buttonLabel: function (row, data) { + return data.fullName; + }, + buttonStyle: { + cssClasses: [ + 'mafe-grid-button' + ] + }, + onButtonClick: function (row, grid) { + var option, select; + select = document.createElement("span"); + select.id = "list-usersIngroup"; + option = document.createElement("span"); + option.id = "list-usersIngroup-iem" + + if (row.getData()["aas_type"] === 'group') { + var restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var optionClone, i; + for (i = 0; i < response.length; i += 1) { + if (i == 10) { + optionClone = option.cloneNode(false); + optionClone.innerHTML = ". . ."; + select.appendChild(optionClone); + } else { + optionClone = option.cloneNode(false); + optionClone.textContent = "- " + response[i].usr_firstname + ' ' + response[i].usr_lastname; + optionClone.title = response[i].usr_firstname + ' ' + response[i].usr_lastname; + select.appendChild(optionClone); + } + } + if (!optionClone) { + optionClone = option.cloneNode(false); + optionClone.textContent = "No users".translate(); + select.appendChild(optionClone); + } + + quickMessageWindow.show($(row.html).find('a')[0], select); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() + }); + restClient.setBaseEndPoint('group/' + row.getData()["aas_uid"] + '/users?start=0&limit=11'); + restClient.executeRestClient(); } } - } - if (gridUsersAD.getItems().length > 0) { - for (i = 0; i < arrayObjectAdhocUser.length; i += 1) { - b = arrayObjectAdhocUser[i]; - if (arrayObjectAdhocUser2.indexOf(b) == -1) { - removeAD(arrayObjectAdhocUser[i]); + }, + { + title: "", + dataType: 'string', + columnData: "available", + alignmentCell: "left", + width: "330px" + }, + { + id: 'gridUsersButtonAssign', + title: '', + dataType: 'button', + width: "10%", + buttonStyle: { + cssClasses: [ + 'mafe-button-edit-assign' + ] + }, + buttonLabel: function (row, data) { + var sw = row.getData()["aas_type"] === 'user'; + row.getCells()[0].content.style.addClasses([sw ? 'button-icon-user' : 'button-icon-group']); + return ''; + }, + onButtonClick: function (row, grid) { + var dataRow = {}; + grid = (grid != null) ? grid : gridUsers; + assignee(row); + gridUserList.goToPage(gridUserList.currentPage); + grid.goToPage(0); + gridUserList.goToPage(0); + flashMessage.setMessage("Assignee saved successfully".translate()); + flashMessage.setAppendTo(windowAssignmentRules.getHTML()); + flashMessage.show(); } - } + }], + onDropOut: function (item, origin, destiny) { + }, + onDrop: function (a, row) { + grid = this; + remove(row); + gridUserList.goToPage(gridUserList.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("The user/group was successfully removed".translate()); + flashMessage.setAppendTo(windowAssignmentRules.getHTML()); + flashMessage.show(); + return false; + }, + style: { + cssClasses: [ + 'mafe-designer-assigment-grid' + ] } - }; - applyStyles = function () { - gridUsers.dom.toolbar.appendChild(buttonsUsers.getHTML()); - buttonsUsers.defineEvents(); - gridUsers.dom.toolbar.style.height = "76px"; - gridUserList.dom.toolbar.appendChild(buttonsUserList.getHTML()); - buttonsUserList.defineEvents(); - gridUserList.dom.toolbar.style.height = "76px"; - buttonsUsers.dom.labelTextContainer.style.display = "none"; - buttonsUserList.dom.labelTextContainer.style.display = "none"; - gridUsers.hideHeaders(); - gridUserList.hideHeaders(); - assigmentPanelUserList.setHeight('100%'); - gridUsers.filterControl.html.style.width = "300px"; - gridUserList.filterControl.html.style.width = "300px"; - }; - applyStylesAD = function () { - gridUsersAD.dom.toolbar.appendChild(buttonsUsersAD.getHTML()); - buttonsUsersAD.defineEvents(); - gridUsersAD.dom.toolbar.style.height = "76px"; - - gridUserListAD.dom.toolbar.appendChild(buttonsUserListAD.getHTML()); - buttonsUserListAD.defineEvents(); - gridUserListAD.dom.toolbar.style.height = "76px"; - buttonsUsersAD.dom.labelTextContainer.style.display = "none"; - buttonsUserListAD.dom.labelTextContainer.style.display = "none"; - gridUsersAD.hideHeaders(); - gridUserListAD.hideHeaders(); - assigmentPanelUserListAD.setHeight('100%'); - gridUsersAD.filterControl.html.style.width = "300px"; - gridUserListAD.filterControl.html.style.width = "300px"; - }; - assignee = function (row) { - restClient.setTypeRequest("post"); - restClient.setEndpoint("activity/" + activity.id + "/assignee"); - restClient.setData({aas_uid: row.getData()["aas_uid"], aas_type: row.getData()["aas_type"]}); - restClient.functionSuccess = function (xhr, response) { - }; - restClient.executeRestClient(); - }; - remove = function (row) { - restClient.setTypeRequest("remove"); - restClient.setEndpoint("activity/" + activity.id + "/assignee/" + row.getData().aas_uid); - restClient.functionSuccess = function (xhr, response) { - }; - restClient.executeRestClient(); - }; - assigneeAD = function (row) { - restClient.setTypeRequest("post"); - restClient.setEndpoint("activity/" + activity.id + "/adhoc-assignee"); - restClient.setData({ada_uid: row.getData()["ada_uid"], ada_type: row.getData()["ada_type"]}); - restClient.functionSuccess = function (xhr, response) { - }; - restClient.executeRestClient(); - }; - removeAD = function (row) { - restClient.setTypeRequest("remove"); - restClient.setEndpoint("activity/" + activity.id + "/adhoc-assignee/" + row.getData()["ada_uid"]); - restClient.functionSuccess = function (xhr, response) { - }; - restClient.executeRestClient(); - }; - groupRows = function (grid, value) { - var i, items; - if (grid.memorystack === undefined) { - grid.memorystack = []; + }); + assigmentPanelUserList = new PMUI.core.Panel({ + id: "assigmentPanelUserList", + layout: "vbox", + width: "60%", + style: { + cssClasses: [ + 'mafe-panel-assignment-white' + ] } - items = grid.getItems(); - while (grid.memorystack.length > 0) { - grid.addItem(grid.memorystack.pop()); + }); + panelTitleUserList = new PMUI.core.Panel({ + id: "panelTitleUserList", + layout: "hbox" + }); + titleUserList = new PMUI.ui.TextLabel({ + id: "titleUserList", + textMode: 'plain', + text: 'Assigned users list'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ] } - if (value !== 'all') { - for (i = 0; i < items.length; i += 1) { - if (items[i].getData().ass_type !== value) { - grid.memorystack.push(items[i]); - grid.removeItem(items[i]); - } - } + }); + panelGridUserList = new PMUI.core.Panel({ + id: "panelGridUserList", + layout: "hbox", + style: { + cssClasses: ["mafe-panel"] } - grid.sort('fullName', 'asc'); - }; - - function onchangeRadio(grid, fieldName) { - var radioButTrat = document.getElementsByName(fieldName), i; - for (i = 0; i < radioButTrat.length; i += 1) { - if (radioButTrat[i].checked == true) { - quickMessageWindow.close(); - groupRows(grid, radioButTrat[i].value); + }); + buttonsUserList = new PMUI.field.RadioButtonGroupField({ + id: "buttonsUserList", + controlPositioning: 'horizontal', + maxDirectionOptions: 3, + options: [{ + id: 'buttonAllAs', + label: 'View all'.translate(), + value: 'all', + selected: true + }, { + id: 'buttonUsersAs', + label: 'View users'.translate(), + value: 'user' + }, { + id: 'buttonGroupsAs', + label: 'View groups'.translate(), + value: 'group' + }], + onChange: function (newVal, oldVal) { + switch (newVal) { + case "user" : + gridUserList.typeList = "user"; + break; + case "group": + gridUserList.typeList = "group"; + break; + default: + gridUserList.typeList = ""; + break; } + gridUserList.goToPage(0); } - } - - function domSettings() { - if (activity.act_loop_type == "PARALLEL") { - $(formAssignmentRules.getField("tas_assign_type").controls[0].html).parent().hide(); - $(formAssignmentRules.getField("tas_assign_type").controls[1].html).parent().hide(); - $(formAssignmentRules.getField("tas_assign_type").controls[2].html).parent().hide(); - $(formAssignmentRules.getField("tas_assign_type").controls[3].html).parent().hide(); - $(formAssignmentRules.getField("tas_assign_type").controls[4].html).parent().hide(); - $(formAssignmentRules.getField("tas_assign_type").controls[5].html).parent().hide(); - $(formAssignmentRules.getField("tas_assign_type").controls[6].html).parent().show(); - $(formAssignmentRules.getField("tas_assign_type").controls[7].html).parent().show(); - if (formAssignmentRules.getField('tas_assign_type').getValue() == "MULTIPLE_INSTANCE_VALUE_BASED") { - formAssignmentRules.getField('tas_assign_type').setValue("MULTIPLE_INSTANCE_VALUE_BASED"); - } else { - formAssignmentRules.getField('tas_assign_type').setValue("MULTIPLE_INSTANCE"); + }); + gridUserList = new PMUI.grid.GridPanel({ + id: "gridUserList", + pageSize: pageSizeAssignment - 1, + edges: 2, + displayedPages: 2, + behavior: 'dragdropsort', + filterable: true, + nextLabel: 'Next'.translate(), + filterPlaceholder: 'Search ...'.translate(), + previousLabel: 'Previous'.translate(), + tableContainerHeight: 242, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + emptyMessage: function () { + var div = document.createElement('div'), + span = document.createElement('span'); + div.appendChild(span); + div.className = "mafe-grid-panel-empty"; + div.style.height = gridUserList.dom.tableContainer.style.height; + div.style.width = gridUserList.dom.tableContainer.style.width; + span.innerHTML = 'Drag & Drop a User or a Group here'.translate(); + return div; + }, + onEmpty: function () { + gridUserList.dom.tableContainer.style.overflow = "hidden"; + }, + dynamicLoad: { + keys: { + server: HTTP_SERVER_HOSTNAME, + projectID: PMDesigner.project.projectId, + workspace: WORKSPACE, + accessToken: PMDesigner.project.tokens.access_token, + endPoint: 'project/' + PMDesigner.project.id + '/activity/' + activity.id + '/assignee/paged' } - } else { - $(formAssignmentRules.getField("tas_assign_type").controls[0].html).parent().show(); - $(formAssignmentRules.getField("tas_assign_type").controls[1].html).parent().show(); - $(formAssignmentRules.getField("tas_assign_type").controls[2].html).parent().show(); - $(formAssignmentRules.getField("tas_assign_type").controls[3].html).parent().show(); - $(formAssignmentRules.getField("tas_assign_type").controls[4].html).parent().show(); - $(formAssignmentRules.getField("tas_assign_type").controls[5].html).parent().show(); - $(formAssignmentRules.getField("tas_assign_type").controls[6].html).parent().hide(); - $(formAssignmentRules.getField("tas_assign_type").controls[7].html).parent().hide(); - if (formAssignmentRules.getField('tas_assign_type').getValue() == "MULTIPLE_INSTANCE_VALUE_BASED") { - formAssignmentRules.getField('tas_assign_type').setValue("BALANCED"); - formAssignmentRules.getField('tas_assign_variable').setVisible(false); + }, + customDataRest: function (data) { + var i; + for (i = 0; i < data.length; i += 1) { + if (data[i].aas_type == "group") { + data[i]["assignment"] = data[i].aas_name; + } else { + data[i]["assignment"] = data[i].aas_name + " " + data[i].aas_lastname + " (" + data[i].aas_username + ")"; + } + } + return data; + }, + columns: [ + { + id: 'gridUserListButtonLabel', + title: "", + width: "10%", + dataType: 'button', + buttonLabel: function (row, data) { + return data.lastName; + }, + buttonStyle: { + cssClasses: [ + 'mafe-grid-button' + ] + }, + onButtonClick: function (row, grid) { + var option, select; + select = document.createElement("span"); + select.id = "list-usersIngroup"; + option = document.createElement("span"); + option.id = "list-usersIngroup-iem"; + + if (row.getData()["aas_type"] === "group") { + var restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var optionClone, i; + for (i = 0; i < response.length; i += 1) { + if (i == 10) { + optionClone = option.cloneNode(false); + optionClone.innerHTML = ". . ."; + select.appendChild(optionClone); + } else { + optionClone = option.cloneNode(false); + optionClone.textContent = "- " + response[i].usr_firstname + ' ' + response[i].usr_lastname; + optionClone.title = response[i].usr_firstname + ' ' + response[i].usr_lastname; + select.appendChild(optionClone); + } + } + if (!optionClone) { + optionClone = option.cloneNode(false); + optionClone.textContent = "No users".translate(); + select.appendChild(optionClone); + } + + quickMessageWindow.show($(row.html).find('a')[0], select); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() + }); + restClient.setBaseEndPoint("group/" + row.getData()["aas_uid"] + "/users?start=0&limit=11"); + restClient.executeRestClient(); + } + } + }, + { + title: '', + dataType: 'string', + columnData: "assignment", + alignmentCell: "left", + width: "330px" + }, + { + id: 'gridUserListButtonDelete', + title: '', + dataType: 'button', + width: "10%", + buttonStyle: { + cssClasses: [ + 'mafe-button-delete-assign' + ] + }, + buttonLabel: function (row, data) { + var sw = row.getData()["aas_type"] === 'user'; + row.getCells()[0].content.style.addClasses([sw ? 'button-icon-user' : 'button-icon-group']); + return ''; + }, + onButtonClick: function (row, grid) { + var dataRow = {}; + grid = (grid != null) ? grid : gridUserList; + remove(row); + gridUserList.goToPage(gridUserList.currentPage); + grid.goToPage(0); + gridUsers.goToPage(0); + flashMessage.setMessage("The user/group was successfully removed".translate()); + flashMessage.setAppendTo(windowAssignmentRules.getHTML()); + flashMessage.show(); + } } + ], + onDropOut: function (item, origin, destiny) { + }, + onDrop: function (grid, row) { + var dataRow = {}; + grid = this; + assignee(row); + gridUsers.goToPage(gridUsers.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("Assignee saved successfully".translate()); + flashMessage.setAppendTo(windowAssignmentRules.getHTML()); + flashMessage.show(); + return false; + }, + style: { + cssClasses: [ + 'mafe-designer-assigment-grid' + ] } - }; - - panelTitleUser.addItem(titleUser); - panelGridUser.addItem(gridUsers); - assigmentPanelUser.addItem(panelTitleUser); - assigmentPanelUser.addItem(panelGridUser); - assigmentPanelGlobal.addItem(assigmentPanelUser); - panelTitleUserList.addItem(titleUserList); - panelGridUserList.addItem(gridUserList); - assigmentPanelUserList.addItem(panelTitleUserList); - assigmentPanelUserList.addItem(panelGridUserList); - assigmentPanelGlobal.addItem(assigmentPanelUserList); - - panelTitleUserAD.addItem(titleUserAD); - panelSearchUserAD.addItem(searchGridUserAD); - panelGridUserAD.addItem(gridUsersAD); - assigmentPanelUserAD.addItem(panelTitleUserAD); - assigmentPanelUserAD.addItem(panelGridUserAD); - assigmentPanelGlobalAD.addItem(assigmentPanelUserAD); - panelTitleUseListAD.addItem(titleUserListAD); - panelGridUserListAD.addItem(gridUserListAD); - assigmentPanelUserListAD.addItem(panelTitleUseListAD); - assigmentPanelUserListAD.addItem(panelGridUserListAD); - assigmentPanelGlobalAD.addItem(assigmentPanelUserListAD); + }); - if (formAssignmentRules.dirty == null) { - formAssignmentRules.dirty = false; - } - windowAssignmentRules.addItem(formAssignmentRules); - windowAssignmentRules.addItem(tabPanelAssignmentRules); - windowAssignmentRules.open(); - applyStyleWindowForm(windowAssignmentRules); - windowAssignmentRules.body.style.overflowY = 'auto'; - windowAssignmentRules.body.style.overflowX = 'hidden'; - windowAssignmentRules.defineEvents(); - buttonsUsers.defineEvents(); - tabPanelAssignmentRules.itemClick(0); - loadServerData(); - domSettings(); - //array for Users - usersgrid = gridUsers; - for (i = 0; i < usersgrid.getItems().length; i += 1) { - arrayObjectUsers2[i] = usersgrid.getItems()[i]; - } - userslist = gridUserList; - for (i = 0; i < userslist.getItems().length; i += 1) { - arrayObjectUserList2[i] = userslist.getItems()[i]; - } - //array for AdHocUsers - usersgrid = gridUsersAD; - for (i = 0; i < usersgrid.getItems().length; i += 1) { - arrayObjectAdhocUser2[i] = usersgrid.getItems()[i]; - } - userslist = gridUserListAD; - for (i = 0; i < userslist.getItems().length; i += 1) { - arrayObjectAdhocUserList2[i] = userslist.getItems()[i]; - } - formAssignmentRules.html.style.marginLeft = '30px'; - formAssignmentRulesSetTimeoutOption; - document.getElementById("formAssignmentRulesSetTimeoutOption").childNodes[0].onchange = function () { - visibleService(this.checked); - }; - $(".pmui-field-control-table").css("border", "0px"); - $(".pmui-field-label").css("padding", "0px"); - $(".mafe-designer-assigment-title").css("margin-top", "25px"); - $("#formTasAssignType").append("
"); - $(".pmui-gridpanel-footer").addClass("pmui-gridpanel-footer-dinamic"); - }; -}()); -(function () { - PMDesigner.assigmentSupervisors = function (event) { - var assigmentWindow = null, - pageSizeAssignment = 8, - restClient, - assigmentPanelUser, - assigmentPanelUserList, - assigmentPanelGlobal, - panelTitleUser, - titleUser, - panelSearchUser, - searchGridUser, - panelGridUser, - buttonsUsers, - gridUsers, - panelTitleUserList, - titleUserList, - panelSearchUserList, - searchGridUserList, - panelGridUserList, - buttonsUserList, - gridUserList, - applyStyles, - loadServerData, - loadUsers, - loadUsersList, - groupRows, - assignee, - remove, - quickMessageWindow = new QuickMessageWindow(); + assigmentPanelGlobalAD = new PMUI.core.Panel({ + id: "assigmentPanelGlobalAD", + layout: "hbox", + width: DEFAULT_WINDOW_WIDTH - assigmentWindow = new PMUI.ui.Window({ - id: 'assigmentUserWindow', - title: 'Assign Users and Groups as Supervisors'.translate(), - width: DEFAULT_WINDOW_WIDTH + 1, - height: DEFAULT_WINDOW_HEIGHT, - footerHeight: 'auto', - bodyHeight: 'auto', - modal: true }); - restClient = new PMRestClient({ - endpoint: 'projects', - typeRequest: 'get', - messageError: 'There are problems, please try again.'.translate(), - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); + assigmentPanelUserAD = new PMUI.core.Panel({ + id: "assigmentPanelUserAD", + layout: "vbox", + width: "60%", + style: { + cssClasses: [ + 'mafe-panel-assignment-white' + ] } }); + panelTitleUserAD = new PMUI.core.Panel({ + id: "panelTitleUserAD", + layout: "hbox" + }); + titleUserAD = new PMUI.ui.TextLabel({ + id: "titleUserAD", + label: " ", + textMode: 'plain', + text: 'Available users list'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ] + } + }); + panelSearchUserAD = new PMUI.core.Panel({ + id: "panelSearchUserAD", + layout: "hbox" + }); + searchGridUserAD = new PMUI.field.TextField({ + id: "searchGridUserAD", + label: " ", + placeholder: 'Search ...'.translate(), + style: { + cssClasses: [ + 'mafe-assigment-search' + ] + } + }); + panelGridUserAD = new PMUI.core.Panel({ + id: "panelGridUserAD", + layout: "hbox", + style: { + cssClasses: ["mafe-panel"] + } + }); + buttonsUsersAD = new PMUI.field.RadioButtonGroupField({ + id: "buttonsUsersAD", + controlPositioning: 'horizontal', + maxDirectionOptions: 3, + options: [{ + id: 'buttonAllAv', + label: 'View all'.translate(), + selected: true, + value: 'all' + }, { + id: 'buttonUsersAv', + label: 'View users'.translate(), + value: 'user' + }, { + id: 'buttonGroupsAv', + label: 'View groups'.translate(), + value: 'group' + }], + onChange: function (newVal, oldVal) { + switch (newVal) { + case "user" : + gridUsersAD.typeList = "user"; + break; + case "group": + gridUsersAD.typeList = "group"; + break; + default: + gridUsersAD.typeList = ""; + break; + } + gridUsersAD.goToPage(0); + } + }); + gridUsersAD = new PMUI.grid.GridPanel({ + id: "gridUsersAD", + pageSize: pageSizeAssignmentAD - 1, + filterable: true, + behavior: 'dragdropsort', + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + tableContainerHeight: 242, + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + dynamicLoad: { + keys: { + server: HTTP_SERVER_HOSTNAME, + projectID: PMDesigner.project.projectId, + workspace: WORKSPACE, + accessToken: PMDesigner.project.tokens.access_token, + endPoint: 'project/' + PMDesigner.project.id + '/activity/' + activity.id + '/adhoc-available-assignee/paged' + } + }, + customDataRest: function (data) { + var i; + for (i = 0; i < data.length; i += 1) { + if (data[i].ada_type == "group") { + data[i]["available"] = data[i].ada_name; + } else { + data[i]["available"] = data[i].ada_name + " " + data[i].ada_lastname + " (" + data[i].ada_username + ")"; + } + } + return data; + }, + columns: [ + { + id: 'gridUsersADButtonLabel', + title: '', + dataType: 'button', + width: "10%", + buttonLabel: function (row, data) { + return data.lastName; + }, + buttonStyle: { + cssClasses: [ + 'mafe-grid-button' + ] + }, + onButtonClick: function (row, grid) { + var option, select; + select = document.createElement("span"); + select.id = "list-usersIngroup"; + option = document.createElement("span"); + option.id = "list-usersIngroup-iem"; + if (row.getData()["ada_type"] === "group") { + var restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var optionClone, i; + for (i = 0; i < response.length; i += 1) { + if (i == 10) { + optionClone = option.cloneNode(false); + optionClone.innerHTML = ". . ."; + select.appendChild(optionClone); + } else { + optionClone = option.cloneNode(false); + optionClone.textContent = "- " + response[i].usr_firstname + ' ' + response[i].usr_lastname; + optionClone.title = response[i].usr_firstname + ' ' + response[i].usr_lastname; + select.appendChild(optionClone); + } + } + if (!optionClone) { + optionClone = option.cloneNode(false); + optionClone.textContent = "No users".translate(); + select.appendChild(optionClone); + } - assigmentPanelUser = new PMUI.core.Panel({ - layout: "vbox", - width: "49%", + quickMessageWindow.show($(row.html).find('a')[0], select); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() + }); + restClient.setBaseEndPoint("group/" + row.getData()["ada_uid"] + "/users?start=0&limit=11"); + restClient.executeRestClient(); + } + } + }, + { + title: "", + dataType: 'string', + columnData: "available", + alignmentCell: "left", + width: "330px" + }, + { + id: 'gridUsersADButtonAssign', + title: '', + dataType: 'button', + width: "10%", + buttonStyle: { + cssClasses: [ + 'mafe-button-edit-assign' + ] + }, + buttonLabel: function (row, data) { + var sw = row.getData()["ada_type"] === 'user'; + row.getCells()[0].content.style.addClasses([sw ? 'button-icon-user' : 'button-icon-group']); + return ''; + }, + onButtonClick: function (row, grid) { + var dataRow = {}; + grid = (grid != null) ? grid : gridUsersAD; + assigneeAD(row); + grid.goToPage(gridUsersAD.currentPage); + gridUserListAD.goToPage(0); + flashMessage.setMessage("Assignee saved successfully".translate()); + flashMessage.setAppendTo(windowAssignmentRules.getHTML()); + flashMessage.show(); + } + } + ], + onDropOut: function (item, origin, destiny) { + formAssignmentRules.dirty = true; + grid = gridUsersAD; + grid.sort('fullName', 'asc'); + buttonsUserListAD.setValue(buttonsUsersAD.getValue()); + groupRows(gridUsersAD, 'all'); + groupRows(gridUserListAD, 'all'); + arrayObjectAdhocUserList.push(item); + index = arrayObjectAdhocUser.indexOf(item); + if (index > -1) { + arrayObjectAdhocUser.splice(index, 1); + } + }, + onDrop: function (a, row) { + grid = this; + removeAD(row); + gridUserListAD.goToPage(gridUserListAD.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("The user/group was successfully removed".translate()); + flashMessage.setAppendTo(windowAssignmentRules.getHTML()); + flashMessage.show(); + return false; + }, style: { cssClasses: [ - 'mafe-panel-assignment-white' + 'mafe-designer-assigment-grid' ] } }); - assigmentPanelUserList = new PMUI.core.Panel({ + assigmentPanelUserListAD = new PMUI.core.Panel({ + id: "assigmentPanelUserListAD", layout: "vbox", - width: "50%", - style: { - cssClasses: [ - 'mafe-panel-assignment-smooth' - ] - } - }); - assigmentPanelGlobal = new PMUI.core.Panel({ - layout: 'hbox', - width: DEFAULT_WINDOW_WIDTH, style: { cssClasses: [ - 'mafe-assigment-panel-global' + 'mafe-panel-assignment-white' ] - } + }, + width: "60%" }); - - panelTitleUser = new PMUI.core.Panel({ - layout: 'hbox' + panelTitleUseListAD = new PMUI.core.Panel({ + id: "panelTitleUseListAD", + layout: "hbox" }); - titleUser = new PMUI.ui.TextLabel({ - id: 'titleUser', - label: ' ', + titleUserListAD = new PMUI.ui.TextLabel({ + id: "titleUserListAD", textMode: 'plain', - text: 'Available Users List'.translate(), + text: 'Assigned users list'.translate(), style: { cssClasses: [ 'mafe-designer-assigment-title' ] } }); - panelSearchUser = new PMUI.core.Panel({ - layout: 'hbox' - }); - searchGridUser = new PMUI.field.TextField({ - id: 'searchGridUser', - label: ' ', - placeholder: 'Search ...'.translate() + panelGridUserListAD = new PMUI.core.Panel({ + id: "panelGridUserListAD", + layout: "hbox", + style: { + cssClasses: ["mafe-panel"] + } }); - panelGridUser = new PMUI.core.Panel({layout: 'hbox'}); - buttonsUsers = new PMUI.field.OptionsSelectorField({ - id: 'buttonsUsers', - orientation: 'horizontal', - items: [{ - text: 'All'.translate(), - selected: true, + buttonsUserListAD = new PMUI.field.RadioButtonGroupField({ + id: "buttonsUserListAD", + controlPositioning: 'horizontal', + maxDirectionOptions: 3, + options: [{ + id: 'buttonAllAs', + label: 'View all'.translate(), value: 'all', - style: { - cssClasses: [ - 'pmui-switch-icon-all' - ] - } + selected: true }, { - text: 'Users'.translate(), - value: 'user', - style: { - cssClasses: [ - 'pmui-switch-icon-user' - ] - } + id: 'buttonUsersAs', + label: 'View users'.translate(), + value: 'user' }, { - text: 'Groups'.translate(), - value: 'group', - style: { - cssClasses: [ - 'pmui-switch-icon-group' - ] - } - } - ], - listeners: { - select: function (item, event) { - groupRows(gridUsers, item.value); + id: 'buttonGroupsAs', + label: 'View groups'.translate(), + value: 'group' + }], + onChange: function (newVal, oldVal) { + switch (newVal) { + case "user" : + gridUserListAD.typeList = "user"; + break; + case "group": + gridUserListAD.typeList = "group"; + break; + default: + gridUserListAD.typeList = ""; + break; } - }, - style: { - cssClasses: [ - 'mafe-assigment-buttons' - ] + gridUserListAD.goToPage(0); } }); - gridUsers = new PMUI.grid.GridPanel({ - id: 'gridUsers', - pageSize: pageSizeAssignment, + gridUserListAD = new PMUI.grid.GridPanel({ + id: "gridUserListAD", + pageSize: pageSizeAssignmentAD - 1, behavior: 'dragdropsort', filterable: true, filterPlaceholder: 'Search ...'.translate(), - emptyMessage: 'No records found'.translate(), nextLabel: 'Next'.translate(), previousLabel: 'Previous'.translate(), + tableContainerHeight: 242, customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); }, - columns: [{ - id: 'gridUsersButtonLabel', - title: '', - dataType: 'button', - width: '10%', - buttonLabel: function (row, data) { - return data.lastName; - }, - buttonStyle: { - cssClasses: [ - 'mafe-grid-button' - ] - }, - onButtonClick: function (row, grid) { - if (row.data.customKeys.obj_type === 'group') { - restClient.setTypeRequest('get'); - restClient.functionSuccess = function (xhr, response) { - var stringUsers = '', i; - for (i = 0; i < response.length; i += 1) { - stringUsers = stringUsers + response[i].usr_firstname + ' ' + response[i].usr_lastname + ', '; - } - stringUsers = stringUsers.substring(0, stringUsers.length - 2); - if (stringUsers === '') { - stringUsers = 'No users'; - } - quickMessageWindow.show($(row.html).find('a')[0], stringUsers); - }; - restClient.setBaseEndPoint('group/' + row.data.customKeys.sup_uid + '/users'); - restClient.executeRestClient(); + emptyMessage: function () { + var div = document.createElement('div'), + span = document.createElement('span'); + div.appendChild(span); + div.className = "mafe-grid-panel-empty"; + div.style.height = gridUserListAD.dom.tableContainer.style.height; + div.style.width = gridUserListAD.dom.tableContainer.style.width; + span.innerHTML = 'Drag & Drop a User or a Group here'.translate(); + return div; + }, + onEmpty: function (grid, cell) { + gridUserListAD.dom.tableContainer.style.overflow = "hidden"; + }, + dynamicLoad: { + keys: { + server: HTTP_SERVER_HOSTNAME, + projectID: PMDesigner.project.projectId, + workspace: WORKSPACE, + accessToken: PMDesigner.project.tokens.access_token, + endPoint: 'project/' + PMDesigner.project.id + '/activity/' + activity.id + '/adhoc-assignee/paged' + } + }, + customDataRest: function (data) { + var i; + for (i = 0; i < data.length; i += 1) { + if (data[i].ada_type == "group") { + data[i]["assignee"] = data[i].ada_name; + } else { + data[i]["assignee"] = data[i].ada_name + " " + data[i].ada_lastname + " (" + data[i].ada_username + ")"; } } - }, { - title: '', - dataType: 'string', - columnData: 'sup_name', - alignmentCell: 'left', - width: '80%' - }, { - id: 'gridUsersButtonAssign', - title: '', - dataType: 'button', - width: '19%', - buttonStyle: { - cssClasses: [ - 'mafe-button-edit' - ] + return data; + }, + columns: [ + { + id: 'gridUserListADButtonLabel', + title: "", + width: "13%", + dataType: 'button', + buttonLabel: function (row, data) { + return data.lastName; + }, + buttonStyle: { + cssClasses: [ + 'mafe-grid-button' + ] + }, + onButtonClick: function (row, grid) { + var option, select; + select = document.createElement("span"); + select.id = "list-usersIngroup"; + option = document.createElement("span"); + option.id = "list-usersIngroup-iem"; + if (row.getData()["ada_type"] === "group") { + var i, + restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var optionClone, i; + for (i = 0; i < response.length; i += 1) { + if (i == 10) { + optionClone = option.cloneNode(false); + optionClone.innerHTML = ". . ."; + select.appendChild(optionClone); + } else { + optionClone = option.cloneNode(false); + optionClone.textContent = "- " + response[i].usr_firstname + ' ' + response[i].usr_lastname; + optionClone.title = response[i].usr_firstname + ' ' + response[i].usr_lastname; + select.appendChild(optionClone); + } + } + if (!optionClone) { + optionClone = option.cloneNode(false); + optionClone.textContent = "No users".translate(); + select.appendChild(optionClone); + } + + quickMessageWindow.show($(row.html).find('a')[0], select); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() + }); + restClient.setBaseEndPoint("group/" + row.getData()["ada_uid"] + "/users?start=0&limit=11"); + restClient.executeRestClient(); + } + } }, - buttonLabel: function (row, data) { - row.getCells()[0].content.style.addClasses([row.data.customKeys.obj_type === 'user' ? 'button-icon-user' : 'button-icon-group']); - return 'Assign'.translate(); + { + title: '', + dataType: 'string', + columnData: "assignee", + alignmentCell: "left", + width: "330px" }, - onButtonClick: function (row, grid) { - grid.removeItem(row); - grid.sort('sup_name', 'asc'); - gridUserList.addItem(row); - buttonsUserList.setValue(buttonsUsers.getValue()); - groupRows(gridUserList, buttonsUsers.getValue()); - assignee(row); + { + id: 'gridUserListADButtonDelete', + title: '', + dataType: 'button', + width: "10%", + buttonStyle: { + cssClasses: [ + 'mafe-button-delete-assign' + ] + }, + buttonLabel: function (row, data) { + var sw = row.getData()["ada_type"] === 'user'; + row.getCells()[0].content.style.addClasses([sw ? 'button-icon-user' : 'button-icon-group']); + return ''; + }, + onButtonClick: function (row, grid) { + var dataRow = {}; + grid = (grid != null) ? grid : gridUserListAD; + removeAD(row); + grid.goToPage(grid.currentPage); + gridUsersAD.goToPage(gridUsersAD.currentPage); + flashMessage.setMessage("The user/group was successfully removed".translate()); + flashMessage.setAppendTo(windowAssignmentRules.getHTML()); + flashMessage.show(); + } } - } ], onDropOut: function (item, origin, destiny) { - assignee(item); }, onDrop: function (a, row) { - buttonsUsers.setValue(buttonsUserList.getValue()); - groupRows(gridUsers, buttonsUserList.getValue()); + grid = this; + assigneeAD(row); + gridUsersAD.goToPage(gridUsersAD.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("Assignee saved successfully".translate()); + flashMessage.setAppendTo(windowAssignmentRules.getHTML()); + flashMessage.show(); + return false; }, style: { cssClasses: [ @@ -21102,174 +20326,371 @@ PMDesigner.ProcessFilesManager.createFirst = function (processFileManagerOptionP } }); - panelTitleUserList = new PMUI.core.Panel({ - layout: 'hbox' - }); - titleUserList = new PMUI.ui.TextLabel({ - id: 'titleUserList', - textMode: 'plain', - text: 'Assigned Users List'.translate(), - style: { - cssClasses: [ - 'mafe-designer-assigment-title' - ] - } - }); - panelSearchUserList = new PMUI.core.Panel({ - layout: 'hbox' + panelContainerRules = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH - 55, + height: "auto", + fieldset: true, + items: [ + formAssignmentRules + ] }); - searchGridUserList = new PMUI.field.TextField({ - id: 'searchGridUserList', - label: ' ', - placeholder: 'Search ...'.translate() + panelContainerUsers = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH, + height: "auto", + fieldset: true, + items: [ + assigmentPanelGlobal + ] }); - panelGridUserList = new PMUI.core.Panel({ - layout: 'hbox' + panelContainerUsersAdHoc = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH, + height: "auto", + fieldset: true, + items: [ + assigmentPanelGlobalAD + ] }); - buttonsUserList = new PMUI.field.OptionsSelectorField({ - id: 'buttonsUserList', - orientation: 'horizontal', - items: [{ - text: 'All'.translate(), - value: 'all', - selected: true, - style: { - cssClasses: [ - 'pmui-switch-icon-all' - ] + + tabPanelAssignmentRules = new PMUI.panel.TabPanel({ + id: 'tabPanelAssignmentRules', + width: "100%", + height: "auto", + items: [ + { + id: 'tabUsers', + title: 'Users'.translate(), + panel: panelContainerUsers + }, + { + id: 'tabUsersAdHoc', + title: 'Ad Hoc Users'.translate(), + panel: panelContainerUsersAdHoc } - }, { - text: 'Users'.translate(), - value: 'user', - style: { - cssClasses: [ - 'pmui-switch-icon-user' - ] + ], + onTabClick: function (item) { + quickMessageWindow.close(); + switch (item.id) { + case 'tabRules': + break; + case 'tabUsers': + applyStyles(); + gridUsers.goToPage(0); + gridUserList.goToPage(0); + break; + case 'tabUsersAdHoc': + applyStylesAD(); + gridUsersAD.goToPage(0); + gridUserListAD.goToPage(0); + break; } - }, { - text: 'Groups'.translate(), - value: 'group', - style: { - cssClasses: [ - 'pmui-switch-icon-group' - ] + } + }); + windowAssignmentRules = new PMUI.ui.Window({ + id: 'windowAssignmentRules', + title: 'Assignment Rules'.translate() + ': ' + activity.act_name, + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + footerItems: [ + { + id: 'windowConnectionsButtonCancel', + text: 'Close'.translate(), + handler: function () { + if (formAssignmentRules.isDirty()) { + warningMessageWindowDirty.open(); + warningMessageWindowDirty.showFooter(); + } else { + windowAssignmentRules.close(); + } + }, + buttonType: 'error' + }, + { + buttonType: 'success', + id: 'windowPropertiesButtonSave', + text: "Save".translate(), + handler: function () { + saveData(); + } } - } - ], - listeners: { - select: function (item, event) { - groupRows(gridUserList, item.value); + visibleFooter: true, + buttonPanelPosition: 'bottom', + footerAlign: "right", + onBeforeClose: function () { + if (formAssignmentRules.isDirty()) { + warningMessageWindowDirty.open(); + warningMessageWindowDirty.showFooter(); + } else { + windowAssignmentRules.close(); } - }, - style: { - cssClasses: [ - 'mafe-assigment-buttons' - ] } }); - gridUserList = new PMUI.grid.GridPanel({ - id: 'gridUserList', - pageSize: pageSizeAssignment, - behavior: 'dragdropsort', - filterPlaceholder: 'Search ...'.translate(), - filterable: true, - nextLabel: 'Next'.translate(), - previousLabel: 'Previous'.translate(), - customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { - return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); - }, - emptyMessage: function () { - var div = document.createElement('div'), - span = document.createElement('span'); - div.appendChild(span); - div.className = 'mafe-grid-panel-empty'; - span.innerHTML = 'Drag & Drop a User or a Group here'.translate(); - return div; - }, - onEmpty: function (grid, cell) { - gridUserList.dom.tableContainer.style.overflow = 'hidden'; - }, - columns: [{ - id: 'gridUserListButtonLabel', - title: '', - width: '10%', - dataType: 'button', - buttonLabel: function (row, data) { - return data.lastName; - }, - buttonStyle: { - cssClasses: [ - 'mafe-grid-button' + + loadTrigger = function (response) { + var field = formAssignmentRules.getField('tas_selfservice_trigger_uid'), i; + field.clearOptions(); + field.addOption({ + value: '', + label: '- Select Trigger -'.translate() + }); + for (i = 0; i < response.length; i += 1) { + field.addOption({ + value: response[i].tri_uid, + label: response[i].tri_title + }); + } + }; + loadFormData = function (response) { + dataProperties = response.properties; + formAssignmentRules.getField('tas_assign_type').setValue(dataProperties.tas_assign_type); + formAssignmentRules.getField('tas_assign_variable').setValue(dataProperties.tas_assign_variable); + formAssignmentRules.getField('tas_group_variable').setValue(dataProperties.tas_group_variable); + changeRadioButtons(formAssignmentRules.getField('tas_assign_type').getValue()); + formAssignmentRules.getField('tas_selfservice_timeout').controls[0].deselect(); + if (dataProperties.tas_selfservice_timeout === 1) { + formAssignmentRules.getField('tas_selfservice_timeout').controls[0].select(); + } + formAssignmentRules.getField('tas_selfservice_time').setValue(dataProperties.tas_selfservice_time); + formAssignmentRules.getField('tas_selfservice_time_unit').setValue(dataProperties.tas_selfservice_time_unit); + formAssignmentRules.getField('tas_selfservice_trigger_uid').setValue(dataProperties.tas_selfservice_trigger_uid); + formAssignmentRules.getField('tas_selfservice_execution').setValue(dataProperties.tas_selfservice_execution); + visibleService(dataProperties.tas_selfservice_timeout === 1); + }; + loadServerData = function () { + var restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'project/' + PMDesigner.project.id + '/activity/' + activity.id, + method: 'GET' + }, { + url: 'project/' + PMDesigner.project.id + '/triggers', + method: 'GET' + } ] }, - onButtonClick: function (row, grid) { - var stringUsers, i; - if (row.data.customKeys.obj_type === 'group') { - restClient.setTypeRequest('get'); - restClient.functionSuccess = function (xhr, response) { - stringUsers = ''; - for (i = 0; i < response.length; i += 1) { - stringUsers = stringUsers + response[i].usr_firstname + ' ' + response[i].usr_lastname + ', '; - } - stringUsers = stringUsers.substring(0, stringUsers.length - 2); - if (stringUsers === '') { - stringUsers = 'No users'; - } - quickMessageWindow.show($(row.html).find('a')[0], stringUsers); - }; - restClient.setBaseEndPoint('group/' + row.data.customKeys.sup_uid + '/users'); - restClient.executeRestClient(); + functionSuccess: function (xhr, response) { + loadTrigger(response[1].response); + loadFormData(response[0].response); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + }; + loadFreeUsers = function (response) { + var i; + gridUsers.clearItems(); + for (i = 0; i < response.length; i += 1) { + gridUsers.addDataItem({ + fullName: response[i].aas_name + " " + response[i].aas_lastname, + ass_uid: response[i].aas_uid, + ass_type: response[i].aas_type + }); + } + }; + loadAssignmentUsers = function (response) { + var i; + gridUserList.clearItems(); + for (i = 0; i < response.length; i += 1) { + gridUserList.addDataItem({ + fullName: response[i].aas_name + " " + response[i].aas_lastname, + ass_uid: response[i].aas_uid, + ass_type: response[i].aas_type + }); + } + }; + loadAdHocFreeUsers = function (response) { + var i; + gridUsersAD.clearItems(); + for (i = 0; i < response.length; i += 1) { + gridUsersAD.addDataItem({ + fullName: response[i].ada_name + " " + response[i].ada_lastname, + ada_uid: response[i].ada_uid, + ass_type: response[i].ada_type + }); + } + }; + loadAdHocAssignmentUsers = function (response) { + var i; + gridUserListAD.clearItems(); + for (i = 0; i < response.length; i += 1) { + gridUserListAD.addDataItem({ + fullName: response[i].ada_name + " " + response[i].ada_lastname, + ada_uid: response[i].ada_uid, + ass_type: response[i].ada_type + }); + } + }; + updateRules = function () { + (new PMRestClient({ + endpoint: 'activity/' + activity.id, + typeRequest: 'update', + messageError: ' ', + data: { + definition: {}, + properties: dataProperties + }, + messageSuccess: 'Assignment Rules saved successfully'.translate(), + flashContainer: document.body, + functionSuccess: function () { + formAssignmentRules.dirty = false; + windowAssignmentRules.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + })).executeRestClient(); + }; + allHidden = function () { + formAssignmentRules.getField('tas_assign_variable').setVisible(false); + formAssignmentRules.getField('tas_group_variable').setVisible(false); + formAssignmentRules.getField('tas_selfservice_timeout').setVisible(false); + formAssignmentRules.getField('tas_selfservice_timeout').controls[0].deselect(); + formAssignmentRules.getField('tas_selfservice_time').setVisible(false); + formAssignmentRules.getField('tas_selfservice_time_unit').setVisible(false); + formAssignmentRules.getField('tas_selfservice_trigger_uid').setVisible(false); + formAssignmentRules.getField('tas_selfservice_execution').setVisible(false); + }; + changeRadioButtons = function (newVal) { + allHidden(); + tabPanelAssignmentRules.setVisible(true); + switch (newVal) { + case 'EVALUATE': + formAssignmentRules.getField('tas_assign_variable').setVisible(true); + if (dataProperties.tas_assign_variable === "" || dataProperties.tas_assign_variable === null) { + formAssignmentRules.getField('tas_assign_variable').setValue('@@SYS_NEXT_USER_TO_BE_ASSIGNED'); + } else { + formAssignmentRules.getField('tas_assign_variable').setValue(dataProperties.tas_assign_variable); + } + break; + case 'SELF_SERVICE': + formAssignmentRules.getField('tas_selfservice_timeout').setVisible(true); + break; + case 'SELF_SERVICE_EVALUATE': + formAssignmentRules.getField('tas_group_variable').setVisible(true); + if (dataProperties.tas_group_variable === "@@SYS_GROUP_TO_BE_ASSIGNED" || dataProperties.tas_group_variable === "" || dataProperties.tas_group_variable === null) { + formAssignmentRules.getField('tas_group_variable').setPlaceholder('@@ARRAY_OF_USERS or @@GROUP_UID'); + } else { + formAssignmentRules.getField('tas_group_variable').setValue(dataProperties.tas_group_variable); + } + formAssignmentRules.getField('tas_selfservice_timeout').setVisible(true); + break; + case 'REPORT_TO': + break; + case 'MULTIPLE_INSTANCE_VALUE_BASED': + formAssignmentRules.getField('tas_assign_variable').setLabel("Array of users".translate()); + if (formAssignmentRules.getField('tas_assign_variable').getValue() == "@@SYS_NEXT_USER_TO_BE_ASSIGNED" || formAssignmentRules.getField('tas_assign_variable').getValue() == "") { + formAssignmentRules.getField('tas_assign_variable').setValue(''); + formAssignmentRules.getField('tas_assign_variable').setPlaceholder('@@ARRAY_OF_USERS'); + } + formAssignmentRules.getField('tas_assign_variable').setVisible(true); + if (activity.act_loop_type == "PARALLEL") { + tabPanelAssignmentRules.setVisible(false); + } + break; + default: + break; + } + }; + visibleService = function (value) { + var a = formAssignmentRules.getField('tas_assign_type').getValue(); + if (a === 'SELF_SERVICE' || a === 'SELF_SERVICE_EVALUATE') { + formAssignmentRules.getField('tas_selfservice_time').setVisible(value); + formAssignmentRules.getField('tas_selfservice_time_unit').setVisible(value); + formAssignmentRules.getField('tas_selfservice_trigger_uid').setVisible(value); + formAssignmentRules.getField('tas_selfservice_execution').setVisible(value); + } + }; + hiddenTab = function (value) { + tabPanelAssignmentRules.showTab(2); + }; + saveData = function () { + var a, b, c, d, tas_selfservice_timeout, data; + tas_selfservice_timeout = formAssignmentRules.getField('tas_selfservice_timeout').getValue() === '["1"]'; + if (!tas_selfservice_timeout) { + //validation because getData method do not work in IE + if (navigator.userAgent.indexOf("MSIE") !== -1 || navigator.userAgent.indexOf("Trident") !== -1) { + data = getData2PMUI(formAssignmentRules.html); + b = data["tas_assign_variable"]; + } else { + b = formAssignmentRules.getField('tas_assign_variable').getValue(); + } + a = formAssignmentRules.getField('tas_assign_type').getValue(); + c = formAssignmentRules.getField('tas_group_variable').getValue(); + d = formAssignmentRules.getField('tas_group_variable').getValue(); + formAssignmentRules.getField('tas_assign_type').setValue(a); + formAssignmentRules.getField('tas_assign_variable').setValue(b); + formAssignmentRules.getField('tas_group_variable').setValue(c); + formAssignmentRules.getField('tas_selfservice_timeout').setValue(d); + formAssignmentRules.getField('tas_selfservice_time').setValue(''); + formAssignmentRules.getField('tas_selfservice_time_unit').setValue(''); + formAssignmentRules.getField('tas_selfservice_trigger_uid').setValue(''); + formAssignmentRules.getField('tas_selfservice_execution').setValue(''); + } else { + if (!formAssignmentRules.isValid()) { + return; + } + } + dataProperties.tas_assign_type = formAssignmentRules.getField('tas_assign_type').getValue(); + dataProperties.tas_assign_variable = formAssignmentRules.getField('tas_assign_variable').getValue() === '' ? '@@SYS_NEXT_USER_TO_BE_ASSIGNED' : formAssignmentRules.getField('tas_assign_variable').getValue(); + dataProperties.tas_group_variable = formAssignmentRules.getField('tas_group_variable').getValue() === '' ? '@@SYS_GROUP_TO_BE_ASSIGNED' : formAssignmentRules.getField('tas_group_variable').getValue(); + dataProperties.tas_selfservice_timeout = tas_selfservice_timeout ? 1 : 0; + dataProperties.tas_selfservice_time = formAssignmentRules.getField('tas_selfservice_time').getValue() !== "" ? parseInt(formAssignmentRules.getField('tas_selfservice_time').getValue(), 10) : 0; + dataProperties.tas_selfservice_time_unit = formAssignmentRules.getField('tas_selfservice_time_unit').getValue(); + dataProperties.tas_selfservice_trigger_uid = formAssignmentRules.getField('tas_selfservice_trigger_uid').getValue(); + dataProperties.tas_selfservice_execution = formAssignmentRules.getField('tas_selfservice_execution').getValue(); + updateRules(); + }; + saveOrUpdateUserAndAdHocUsers = function () { + //Assigne and Remove (users) + var i, b; + if (gridUserList.getItems().length > 0) { + grid = gridUserList; + for (i = 0; i < arrayObjectUserList.length; i += 1) { + b = arrayObjectUserList[i]; + if (arrayObjectUserList2.indexOf(b) == -1) { + assignee(b); } } - }, { - title: '', - dataType: 'string', - columnData: 'sup_name', - width: '80%', - alignmentCell: 'left' - }, { - id: 'gridUserListButtonDelete', - title: '', - dataType: 'button', - width: '10%', - buttonStyle: { - cssClasses: [ - 'mafe-button-delete' - ] - }, - buttonLabel: function (row, data) { - row.getCells()[0].content.style.addClasses([row.data.customKeys.obj_type === 'user' ? 'button-icon-user' : 'button-icon-group']); - return 'Remove'.translate(); - }, - onButtonClick: function (row, grid) { - grid.removeItem(row); - grid.sort('sup_name', 'asc'); - gridUsers.addItem(row); - buttonsUsers.setValue(buttonsUserList.getValue()); - groupRows(gridUsers, buttonsUserList.getValue()); - remove(row); + } + if (gridUsers.getItems().length > 0) { + for (i = 0; i < arrayObjectUsers.length; i += 1) { + b = arrayObjectUsers[i]; + if (arrayObjectUsers2.indexOf(b) == -1) { + remove(arrayObjectUsers[i]); + } } } - ], - onDropOut: function (item, origin, destiny) { - remove(item); - }, - onDrop: function (a, row) { - buttonsUserList.setValue(buttonsUsers.getValue()); - groupRows(gridUserList, buttonsUsers.getValue()); - }, - style: { - cssClasses: [ - 'mafe-designer-assigment-grid' - ] + //Assigne and Remove (AdHocUsers) + if (gridUserListAD.getItems().length > 0) { + grid = gridUserListAD; + for (i = 0; i < arrayObjectAdhocUserList.length; i += 1) { + b = arrayObjectAdhocUserList[i]; + if (arrayObjectAdhocUserList2.indexOf(b) == -1) { + assigneeAD(b); + } + } } - }); - + if (gridUsersAD.getItems().length > 0) { + for (i = 0; i < arrayObjectAdhocUser.length; i += 1) { + b = arrayObjectAdhocUser[i]; + if (arrayObjectAdhocUser2.indexOf(b) == -1) { + removeAD(arrayObjectAdhocUser[i]); + } + } + } + }; applyStyles = function () { gridUsers.dom.toolbar.appendChild(buttonsUsers.getHTML()); + buttonsUsers.defineEvents(); gridUsers.dom.toolbar.style.height = "76px"; gridUserList.dom.toolbar.appendChild(buttonsUserList.getHTML()); + buttonsUserList.defineEvents(); gridUserList.dom.toolbar.style.height = "76px"; buttonsUsers.dom.labelTextContainer.style.display = "none"; buttonsUserList.dom.labelTextContainer.style.display = "none"; @@ -21279,75 +20700,51 @@ PMDesigner.ProcessFilesManager.createFirst = function (processFileManagerOptionP gridUsers.filterControl.html.style.width = "300px"; gridUserList.filterControl.html.style.width = "300px"; }; - loadServerData = function () { - var restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - calls: [ - { - url: 'project/' + PMDesigner.project.id + '/available-process-supervisors', - method: 'GET' - }, { - url: 'project/' + PMDesigner.project.id + '/process-supervisors', - method: 'GET' - } - ] - }, - functionSuccess: function (xhr, response) { - loadUsers(response[0].response); - loadUsersList(response[1].response); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } - }); - restClient.setBaseEndPoint(''); + applyStylesAD = function () { + gridUsersAD.dom.toolbar.appendChild(buttonsUsersAD.getHTML()); + buttonsUsersAD.defineEvents(); + gridUsersAD.dom.toolbar.style.height = "76px"; + + gridUserListAD.dom.toolbar.appendChild(buttonsUserListAD.getHTML()); + buttonsUserListAD.defineEvents(); + gridUserListAD.dom.toolbar.style.height = "76px"; + buttonsUsersAD.dom.labelTextContainer.style.display = "none"; + buttonsUserListAD.dom.labelTextContainer.style.display = "none"; + gridUsersAD.hideHeaders(); + gridUserListAD.hideHeaders(); + assigmentPanelUserListAD.setHeight('100%'); + gridUsersAD.filterControl.html.style.width = "300px"; + gridUserListAD.filterControl.html.style.width = "300px"; + }; + assignee = function (row) { + restClient.setTypeRequest("post"); + restClient.setEndpoint("activity/" + activity.id + "/assignee"); + restClient.setData({aas_uid: row.getData()["aas_uid"], aas_type: row.getData()["aas_type"]}); + restClient.functionSuccess = function (xhr, response) { + }; restClient.executeRestClient(); }; - loadUsers = function (response) { - var i; - for (i = 0; i < response.length; i += 1) { - if (response[i].obj_type === 'user') { - gridUsers.addDataItem({ - sup_uid: response[i].usr_uid, - sup_name: response[i].usr_firstname + ' ' + response[i].usr_lastname, - obj_type: response[i].obj_type - }); - } - if (response[i].obj_type === 'group') { - gridUsers.addDataItem({ - sup_uid: response[i].grp_uid, - sup_name: response[i].grp_name, - obj_type: response[i].obj_type - }); - } - } - gridUsers.sort('sup_name', 'asc'); + remove = function (row) { + restClient.setTypeRequest("remove"); + restClient.setEndpoint("activity/" + activity.id + "/assignee/" + row.getData().aas_uid); + restClient.functionSuccess = function (xhr, response) { + }; + restClient.executeRestClient(); }; - loadUsersList = function (response) { - var i; - for (i = 0; i < response.length; i += 1) { - if (response[i].pu_type === 'SUPERVISOR') { - gridUserList.addDataItem({ - sup_uid: response[i].usr_uid, - sup_name: response[i].usr_firstname + ' ' + response[i].usr_lastname, - obj_type: 'user', - pu_type: response[i].pu_type, - pu_uid: response[i].pu_uid - }); - } - if (response[i].pu_type === 'GROUP_SUPERVISOR') { - gridUserList.addDataItem({ - sup_uid: response[i].grp_uid, - sup_name: response[i].grp_name, - obj_type: 'group', - pu_type: response[i].pu_type, - pu_uid: response[i].pu_uid - }); - } - } - gridUserList.sort('sup_name', 'asc'); + assigneeAD = function (row) { + restClient.setTypeRequest("post"); + restClient.setEndpoint("activity/" + activity.id + "/adhoc-assignee"); + restClient.setData({ada_uid: row.getData()["ada_uid"], ada_type: row.getData()["ada_type"]}); + restClient.functionSuccess = function (xhr, response) { + }; + restClient.executeRestClient(); + }; + removeAD = function (row) { + restClient.setTypeRequest("remove"); + restClient.setEndpoint("activity/" + activity.id + "/adhoc-assignee/" + row.getData()["ada_uid"]); + restClient.functionSuccess = function (xhr, response) { + }; + restClient.executeRestClient(); }; groupRows = function (grid, value) { var i, items; @@ -21360,277 +20757,163 @@ PMDesigner.ProcessFilesManager.createFirst = function (processFileManagerOptionP } if (value !== 'all') { for (i = 0; i < items.length; i += 1) { - if (items[i].getData().obj_type !== value) { + if (items[i].getData().ass_type !== value) { grid.memorystack.push(items[i]); grid.removeItem(items[i]); } } } - grid.sort('sup_name', 'asc'); - }; - assignee = function (row) { - var restClient = new PMRestClient({ - endpoint: 'process-supervisor', - typeRequest: 'post', - data: { - usr_uid: row.data.customKeys.sup_uid, - pu_type: row.data.customKeys.obj_type === 'group' ? 'GROUP_SUPERVISOR' : 'SUPERVISOR' - }, - functionSuccess: function (xhr, response) { - row.data.customKeys.pu_type = response.pu_type; - row.data.customKeys.pu_uid = response.pu_uid; - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: 'There are problems saving the assigned user, please try again.'.translate() - }); - restClient.executeRestClient(); - }; - remove = function (row) { - var restClient = new PMRestClient({ - endpoint: 'process-supervisor/' + row.data.customKeys.pu_uid, - typeRequest: 'remove', - functionSuccess: function () { - }, - functionComplete: function () { - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } - }); - restClient.executeRestClient(); + grid.sort('fullName', 'asc'); + }; + + function onchangeRadio(grid, fieldName) { + var radioButTrat = document.getElementsByName(fieldName), i; + for (i = 0; i < radioButTrat.length; i += 1) { + if (radioButTrat[i].checked == true) { + quickMessageWindow.close(); + groupRows(grid, radioButTrat[i].value); + } + } + } + + function domSettings() { + if (activity.act_loop_type == "PARALLEL") { + $(formAssignmentRules.getField("tas_assign_type").controls[0].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[1].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[2].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[3].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[4].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[5].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[6].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[7].html).parent().show(); + if (formAssignmentRules.getField('tas_assign_type').getValue() == "MULTIPLE_INSTANCE_VALUE_BASED") { + formAssignmentRules.getField('tas_assign_type').setValue("MULTIPLE_INSTANCE_VALUE_BASED"); + } else { + formAssignmentRules.getField('tas_assign_type').setValue("MULTIPLE_INSTANCE"); + } + } else { + $(formAssignmentRules.getField("tas_assign_type").controls[0].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[1].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[2].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[3].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[4].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[5].html).parent().show(); + $(formAssignmentRules.getField("tas_assign_type").controls[6].html).parent().hide(); + $(formAssignmentRules.getField("tas_assign_type").controls[7].html).parent().hide(); + if (formAssignmentRules.getField('tas_assign_type').getValue() == "MULTIPLE_INSTANCE_VALUE_BASED") { + formAssignmentRules.getField('tas_assign_type').setValue("BALANCED"); + formAssignmentRules.getField('tas_assign_variable').setVisible(false); + } + } }; - assigmentWindow.open(); panelTitleUser.addItem(titleUser); - panelTitleUserList.addItem(titleUserList); - assigmentWindow.body.style.overflow = "hidden"; panelGridUser.addItem(gridUsers); - panelGridUserList.addItem(gridUserList); - - assigmentPanelGlobal.addItem(assigmentPanelUser); - assigmentPanelGlobal.addItem(assigmentPanelUserList); - assigmentWindow.addItem(assigmentPanelGlobal); - assigmentPanelUser.addItem(panelTitleUser); - assigmentPanelUser.addItem(panelSearchUser); - assigmentPanelUser.addItem(buttonsUsers); assigmentPanelUser.addItem(panelGridUser); - + assigmentPanelGlobal.addItem(assigmentPanelUser); + panelTitleUserList.addItem(titleUserList); + panelGridUserList.addItem(gridUserList); assigmentPanelUserList.addItem(panelTitleUserList); - assigmentPanelUserList.addItem(panelSearchUserList); - assigmentPanelUserList.addItem(buttonsUserList); assigmentPanelUserList.addItem(panelGridUserList); + assigmentPanelGlobal.addItem(assigmentPanelUserList); - assigmentWindow.defineEvents(); - applyStyles(); - - loadServerData(); - }; -}()); -(function () { - PMDesigner.assigmentSupervisors = function (event) { - var assigmentWindow = null, - pageSizeAssignment = 8, - flagEdit = 0, - i, - index = 0, - quickMessageWindow = new QuickMessageWindow(), - arrayObjectUserList = new Array(), - arrayObjectUsers = new Array(), - arrayObjectUserList2 = new Array(), - arrayObjectUsers2 = new Array(), - arrayDynaformInputDocumentID = new Array(), - arrayDynaformInputDocumentObject = new Array(), - arrayObjectRemovedSteps = new Array(), - message_window, - restClient, - assigmentPanelUser, - assigmentPanelUserList, - assigmentPanelGlobal, - panelTitleUser, - titleUser, - panelSearchUser, - searchGridUser, - panelGridUser, - buttonsUsers, - gridUsers, - panelTitleUserList, - titleUserList, - panelSearchUserList, - searchGridUserList, - panelGridUserList, - radioUsersList, - buttonsUserList, - gridUserList, - radioUsers, - applyStylesRadioButtonGroupField, - applyStylesForToolbar, - applyStyles, - loadUsers, - loadUsersList, - groupRows, - assignee, - remove, - loadGridCaseTacker, - orderDataTree, - titleTreeObjects, - titleGridObjects, - panelLabelObjects, - panelObjects, - treePanelObjects, - updateItem, - usersgrid, - saveItemDyanformInputDocuments, - getValuesAssignmentSteps, - gridPanelObjects, - panelContainerObjects, - userslist, - gridpanelobj, - flashMessage = new PMUI.ui.FlashMessage({ - message: '', - appendTo: document.body, - duration: 1000, - severity: "success" - }); - assigmentWindow = new PMUI.ui.Window({ - id: 'assigmentUserWindow', - title: 'Supervisors'.translate(), - width: DEFAULT_WINDOW_WIDTH + 1, - height: DEFAULT_WINDOW_HEIGHT, - footerHeight: 'auto', - bodyHeight: 'auto', - modal: true, - onBeforeClose: function () { - if (flagEdit != 0) { - message_window.open(); - message_window.showFooter(); - } else { - assigmentWindow.close(); - } - }, - footerItems: [ - { - text: "Cancel", - handler: function () { - if (flagEdit != 0) { - message_window.open(); - message_window.showFooter(); - } else { - assigmentWindow.close(); - } - }, - buttonType: 'error' - }, - { - text: 'Save', - handler: function () { - var i, j, idObject, objType, baseEndPointID; - if (flagEdit != 0) { - //save Configuration Supervisors and Steps(Dyanform - Inputs Documents) - if (gridUserList.getItems().length > 0) { - grid = gridUserList; - for (i = 0; i < arrayObjectUserList.length; i += 1) { - b = arrayObjectUserList[i]; - grid.removeItem(b); - grid.sort('sup_name', 'asc'); - gridUserList.addItem(b); - radioUsersList.setValue(radioUsers.getValue()); - groupRows(gridUserList, radioUsers.getValue()); - if (arrayObjectUserList2.indexOf(b) == -1) { - assignee(b); - } - } - } - if (gridUsers.getItems().length > 0) { - for (i = 0; i < arrayObjectUsers.length; i += 1) { - b = arrayObjectUsers[i]; - if (arrayObjectUsers2.indexOf(b) == -1) { - remove(arrayObjectUsers[i]); - } - } - } - - index = 0; - for (i = 0; i < gridPanelObjects.getItems().length; i += 1) { - idObject = gridPanelObjects.getItems()[i].getData().obj_uid; - index = arrayDynaformInputDocumentID.indexOf(idObject); - if (index <= -1) { - saveItemDyanformInputDocuments(gridPanelObjects.getItems()[i]); - } else { - updateItem(gridPanelObjects.getItems()[i], i); - } - } + panelTitleUserAD.addItem(titleUserAD); + panelSearchUserAD.addItem(searchGridUserAD); + panelGridUserAD.addItem(gridUsersAD); + assigmentPanelUserAD.addItem(panelTitleUserAD); + assigmentPanelUserAD.addItem(panelGridUserAD); + assigmentPanelGlobalAD.addItem(assigmentPanelUserAD); + panelTitleUseListAD.addItem(titleUserListAD); + panelGridUserListAD.addItem(gridUserListAD); + assigmentPanelUserListAD.addItem(panelTitleUseListAD); + assigmentPanelUserListAD.addItem(panelGridUserListAD); + assigmentPanelGlobalAD.addItem(assigmentPanelUserListAD); - for (i = 0; i < arrayObjectRemovedSteps.length; i += 1) { - for (j = 0; j < arrayDynaformInputDocumentObject.length; j += 1) { - index = (arrayObjectRemovedSteps[i] == arrayDynaformInputDocumentObject[j].obj_uid) ? 0 : 1; - if (index == 0) { - objType = arrayDynaformInputDocumentObject[j].obj_type.toLowerCase(); - baseEndPointID = (objType === "dynaform") ? arrayDynaformInputDocumentObject[j].pud_uid : arrayDynaformInputDocumentObject[j].pui_uid; - restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - "calls": [ - { - "url": 'process-supervisor/' + objType + '/' + baseEndPointID, - "method": 'DELETE' - } - ] - }, - functionSuccess: function (xhr, response) { - }, - functionFailure: function (xhr, response) { - } - }); - restClient.executeRestClient(); - break; - } - } - } - assigmentWindow.close(); - } - else { - assigmentWindow.close(); - } - }, - buttonType: "success" - } - ], - visibleFooter: true, - buttonPanelPosition: "bottom", - footerAlign: "right" - }); + if (formAssignmentRules.dirty == null) { + formAssignmentRules.dirty = false; + } + windowAssignmentRules.addItem(formAssignmentRules); + windowAssignmentRules.addItem(tabPanelAssignmentRules); + windowAssignmentRules.open(); + applyStyleWindowForm(windowAssignmentRules); + windowAssignmentRules.body.style.overflowY = 'auto'; + windowAssignmentRules.body.style.overflowX = 'hidden'; + windowAssignmentRules.defineEvents(); + buttonsUsers.defineEvents(); + tabPanelAssignmentRules.itemClick(0); + loadServerData(); + domSettings(); + //array for Users + usersgrid = gridUsers; + for (i = 0; i < usersgrid.getItems().length; i += 1) { + arrayObjectUsers2[i] = usersgrid.getItems()[i]; + } + userslist = gridUserList; + for (i = 0; i < userslist.getItems().length; i += 1) { + arrayObjectUserList2[i] = userslist.getItems()[i]; + } + //array for AdHocUsers + usersgrid = gridUsersAD; + for (i = 0; i < usersgrid.getItems().length; i += 1) { + arrayObjectAdhocUser2[i] = usersgrid.getItems()[i]; + } + userslist = gridUserListAD; + for (i = 0; i < userslist.getItems().length; i += 1) { + arrayObjectAdhocUserList2[i] = userslist.getItems()[i]; + } + formAssignmentRules.html.style.marginLeft = '30px'; + formAssignmentRulesSetTimeoutOption; + document.getElementById("formAssignmentRulesSetTimeoutOption").childNodes[0].onchange = function () { + visibleService(this.checked); + }; + $(".pmui-field-control-table").css("border", "0px"); + $(".pmui-field-label").css("padding", "0px"); + $(".mafe-designer-assigment-title").css("margin-top", "25px"); + $("#formTasAssignType").append("
"); + $(".pmui-gridpanel-footer").addClass("pmui-gridpanel-footer-dinamic"); + }; +}()); +(function () { + PMDesigner.assigmentSupervisors = function (event) { + var assigmentWindow = null, + pageSizeAssignment = 8, + restClient, + assigmentPanelUser, + assigmentPanelUserList, + assigmentPanelGlobal, + panelTitleUser, + titleUser, + panelSearchUser, + searchGridUser, + panelGridUser, + buttonsUsers, + gridUsers, + panelTitleUserList, + titleUserList, + panelSearchUserList, + searchGridUserList, + panelGridUserList, + buttonsUserList, + gridUserList, + applyStyles, + loadServerData, + loadUsers, + loadUsersList, + groupRows, + assignee, + remove, + quickMessageWindow = new QuickMessageWindow(); - message_window = new PMUI.ui.MessageWindow({ - id: "messageWindowCancel", - width: 490, - title: "Supervisors".translate(), - windowMessageType: "warning", - bodyHeight: "auto", - message: 'Are you sure you want to discard your changes?'.translate(), - footerItems: [{ - id: "messageWindowNo", - text: "No".translate(), - handler: function () { - message_window.close(); - }, - buttonType: "error" - }, - { - id: "messageWindowYes", - text: "Yes".translate(), - handler: function () { - message_window.close(); - assigmentWindow.close(); - }, - buttonType: "success" - } - ] + assigmentWindow = new PMUI.ui.Window({ + id: 'assigmentUserWindow', + title: 'Assign Users and Groups as Supervisors'.translate(), + width: DEFAULT_WINDOW_WIDTH + 1, + height: DEFAULT_WINDOW_HEIGHT, + footerHeight: 'auto', + bodyHeight: 'auto', + modal: true }); - restClient = new PMRestClient({ endpoint: 'projects', typeRequest: 'get', @@ -21744,26 +21027,6 @@ PMDesigner.ProcessFilesManager.createFirst = function (processFileManagerOptionP customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); }, - dynamicLoad: { - keys: { - server: HTTP_SERVER_HOSTNAME, - projectID: PMDesigner.project.projectId, - workspace: WORKSPACE, - accessToken: PMDesigner.project.tokens.access_token, - endPoint: 'project/' + PMDesigner.project.id + '/available-process-supervisors/paged' - } - }, - customDataRest: function (data) { - var i; - for (i = 0; i < data.length; i += 1) { - if (data[i].obj_type == "group") { - data[i].available = data[i].grp_name; - } else { - data[i].available = data[i]["usr_firstname"] + " " + data[i]["usr_lastname"] + " (" + data[i]["usr_username"] + ")"; - } - } - return data; - }, columns: [{ id: 'gridUsersButtonLabel', title: '', @@ -21778,51 +21041,29 @@ PMDesigner.ProcessFilesManager.createFirst = function (processFileManagerOptionP ] }, onButtonClick: function (row, grid) { - var option, select; - select = document.createElement("span"); - select.id = "list-usersIngroup"; - option = document.createElement("span"); - option.id = "list-usersIngroup-iem" - if (row.getData()["obj_type"] === 'group') { - var restClient = new PMRestClient({ - typeRequest: 'get', - functionSuccess: function (xhr, response) { - var optionClone, i; - for (i = 0; i < response.length; i += 1) { - if (i == 10) { - optionClone = option.cloneNode(false); - optionClone.innerHTML = ". . ."; - select.appendChild(optionClone); - } else { - optionClone = option.cloneNode(false); - optionClone.textContent = "- " + response[i].usr_firstname + ' ' + response[i].usr_lastname; - optionClone.title = response[i].usr_firstname + ' ' + response[i].usr_lastname; - select.appendChild(optionClone); - } - } - if (!optionClone) { - optionClone = option.cloneNode(false); - optionClone.textContent = "No users".translate(); - select.appendChild(optionClone); - } - - quickMessageWindow.show($(row.html).find('a')[0], select); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: 'There are problems saving the assigned user, please try again.'.translate() - }); - restClient.setBaseEndPoint('group/' + row.getData()["grp_uid"] + '/supervisor-users?start=0&limit=11'); + if (row.data.customKeys.obj_type === 'group') { + restClient.setTypeRequest('get'); + restClient.functionSuccess = function (xhr, response) { + var stringUsers = '', i; + for (i = 0; i < response.length; i += 1) { + stringUsers = stringUsers + response[i].usr_firstname + ' ' + response[i].usr_lastname + ', '; + } + stringUsers = stringUsers.substring(0, stringUsers.length - 2); + if (stringUsers === '') { + stringUsers = 'No users'; + } + quickMessageWindow.show($(row.html).find('a')[0], stringUsers); + }; + restClient.setBaseEndPoint('group/' + row.data.customKeys.sup_uid + '/users'); restClient.executeRestClient(); } } }, { title: '', dataType: 'string', - columnData: 'available', + columnData: 'sup_name', alignmentCell: 'left', - width: '330px' + width: '80%' }, { id: 'gridUsersButtonAssign', title: '', @@ -21830,35 +21071,29 @@ PMDesigner.ProcessFilesManager.createFirst = function (processFileManagerOptionP width: '19%', buttonStyle: { cssClasses: [ - 'mafe-button-edit-assign' + 'mafe-button-edit' ] }, buttonLabel: function (row, data) { - row.getCells()[0].content.style.addClasses([row.getData()["obj_type"] === 'user' ? 'button-icon-user' : 'button-icon-group']); - return ''; + row.getCells()[0].content.style.addClasses([row.data.customKeys.obj_type === 'user' ? 'button-icon-user' : 'button-icon-group']); + return 'Assign'.translate(); }, onButtonClick: function (row, grid) { - grid = (grid != null) ? grid : gridUsers; + grid.removeItem(row); + grid.sort('sup_name', 'asc'); + gridUserList.addItem(row); + buttonsUserList.setValue(buttonsUsers.getValue()); + groupRows(gridUserList, buttonsUsers.getValue()); assignee(row); - gridUserList.goToPage(gridUserList.currentPage); - grid.goToPage(grid.currentPage); - flashMessage.setMessage("The user/group was successfully removed".translate()); - flashMessage.setAppendTo(assigmentWindow.getHTML()); - flashMessage.show(); } } ], onDropOut: function (item, origin, destiny) { + assignee(item); }, onDrop: function (a, row) { - grid = this; - remove(row); - gridUserList.goToPage(gridUserList.currentPage); - grid.goToPage(grid.currentPage); - flashMessage.setMessage("The user/group was successfully removed".translate()); - flashMessage.setAppendTo(assigmentWindow.getHTML()); - flashMessage.show(); - return false; + buttonsUsers.setValue(buttonsUserList.getValue()); + groupRows(gridUsers, buttonsUserList.getValue()); }, style: { cssClasses: [ @@ -21873,58 +21108,23 @@ PMDesigner.ProcessFilesManager.createFirst = function (processFileManagerOptionP titleUserList = new PMUI.ui.TextLabel({ id: 'titleUserList', textMode: 'plain', - text: 'Assigned supervisors list'.translate(), - style: { - cssClasses: [ - 'mafe-designer-assigment-title' - ] - } - }); - panelSearchUserList = new PMUI.core.Panel({ - layout: 'hbox' - }); - searchGridUserList = new PMUI.field.TextField({ - id: 'searchGridUserList', - label: ' ', - placeholder: 'Search ...'.translate() - }); - panelGridUserList = new PMUI.core.Panel({ - layout: 'hbox' - }); - radioUsersList = new PMUI.field.RadioButtonGroupField({ - id: 'idRadioUsersList', - controlPositioning: 'horizontal', - maxDirectionOptions: 3, - options: [ - { - label: "View all".translate(), - value: "all" - }, - { - label: "View users".translate(), - value: "user" - }, - { - label: "View groups".translate(), - value: "group" - } - ], - onChange: function (newVal, oldVal) { - switch (newVal) { - case "user" : - gridUserList.typeList = "user".translate(); - break; - case "group": - gridUserList.typeList = "group".translate(); - break; - default: - gridUserList.typeList = ""; - break; - } - gridUserList.goToPage(0); - }, - required: true, - value: "all" + text: 'Assigned Users List'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ] + } + }); + panelSearchUserList = new PMUI.core.Panel({ + layout: 'hbox' + }); + searchGridUserList = new PMUI.field.TextField({ + id: 'searchGridUserList', + label: ' ', + placeholder: 'Search ...'.translate() + }); + panelGridUserList = new PMUI.core.Panel({ + layout: 'hbox' }); buttonsUserList = new PMUI.field.OptionsSelectorField({ id: 'buttonsUserList', @@ -21990,3048 +21190,3848 @@ PMDesigner.ProcessFilesManager.createFirst = function (processFileManagerOptionP onEmpty: function (grid, cell) { gridUserList.dom.tableContainer.style.overflow = 'hidden'; }, - dynamicLoad: { - keys: { - server: HTTP_SERVER_HOSTNAME, - projectID: PMDesigner.project.projectId, - workspace: WORKSPACE, - accessToken: PMDesigner.project.tokens.access_token, - endPoint: 'project/' + PMDesigner.project.id + '/process-supervisors/paged' + columns: [{ + id: 'gridUserListButtonLabel', + title: '', + width: '10%', + dataType: 'button', + buttonLabel: function (row, data) { + return data.lastName; + }, + buttonStyle: { + cssClasses: [ + 'mafe-grid-button' + ] + }, + onButtonClick: function (row, grid) { + var stringUsers, i; + if (row.data.customKeys.obj_type === 'group') { + restClient.setTypeRequest('get'); + restClient.functionSuccess = function (xhr, response) { + stringUsers = ''; + for (i = 0; i < response.length; i += 1) { + stringUsers = stringUsers + response[i].usr_firstname + ' ' + response[i].usr_lastname + ', '; + } + stringUsers = stringUsers.substring(0, stringUsers.length - 2); + if (stringUsers === '') { + stringUsers = 'No users'; + } + quickMessageWindow.show($(row.html).find('a')[0], stringUsers); + }; + restClient.setBaseEndPoint('group/' + row.data.customKeys.sup_uid + '/users'); + restClient.executeRestClient(); + } + } + }, { + title: '', + dataType: 'string', + columnData: 'sup_name', + width: '80%', + alignmentCell: 'left' + }, { + id: 'gridUserListButtonDelete', + title: '', + dataType: 'button', + width: '10%', + buttonStyle: { + cssClasses: [ + 'mafe-button-delete' + ] + }, + buttonLabel: function (row, data) { + row.getCells()[0].content.style.addClasses([row.data.customKeys.obj_type === 'user' ? 'button-icon-user' : 'button-icon-group']); + return 'Remove'.translate(); + }, + onButtonClick: function (row, grid) { + grid.removeItem(row); + grid.sort('sup_name', 'asc'); + gridUsers.addItem(row); + buttonsUsers.setValue(buttonsUserList.getValue()); + groupRows(gridUsers, buttonsUserList.getValue()); + remove(row); } + } + ], + onDropOut: function (item, origin, destiny) { + remove(item); }, - customDataRest: function (data) { - var i; - for (i = 0; i < data.length; i += 1) { - if (data[i].pu_type == "GROUP_SUPERVISOR") { - data[i].assignee = data[i].grp_name; - } else { - data[i].assignee = data[i]["usr_firstname"] + " " + data[i]["usr_lastname"] + " (" + data[i]["usr_username"] + ")"; + onDrop: function (a, row) { + buttonsUserList.setValue(buttonsUsers.getValue()); + groupRows(gridUserList, buttonsUsers.getValue()); + }, + style: { + cssClasses: [ + 'mafe-designer-assigment-grid' + ] + } + }); + + applyStyles = function () { + gridUsers.dom.toolbar.appendChild(buttonsUsers.getHTML()); + gridUsers.dom.toolbar.style.height = "76px"; + gridUserList.dom.toolbar.appendChild(buttonsUserList.getHTML()); + gridUserList.dom.toolbar.style.height = "76px"; + buttonsUsers.dom.labelTextContainer.style.display = "none"; + buttonsUserList.dom.labelTextContainer.style.display = "none"; + gridUsers.hideHeaders(); + gridUserList.hideHeaders(); + assigmentPanelUserList.setHeight('100%'); + gridUsers.filterControl.html.style.width = "300px"; + gridUserList.filterControl.html.style.width = "300px"; + }; + loadServerData = function () { + var restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + calls: [ + { + url: 'project/' + PMDesigner.project.id + '/available-process-supervisors', + method: 'GET' + }, { + url: 'project/' + PMDesigner.project.id + '/process-supervisors', + method: 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + loadUsers(response[0].response); + loadUsersList(response[1].response); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + }; + loadUsers = function (response) { + var i; + for (i = 0; i < response.length; i += 1) { + if (response[i].obj_type === 'user') { + gridUsers.addDataItem({ + sup_uid: response[i].usr_uid, + sup_name: response[i].usr_firstname + ' ' + response[i].usr_lastname, + obj_type: response[i].obj_type + }); + } + if (response[i].obj_type === 'group') { + gridUsers.addDataItem({ + sup_uid: response[i].grp_uid, + sup_name: response[i].grp_name, + obj_type: response[i].obj_type + }); + } + } + gridUsers.sort('sup_name', 'asc'); + }; + loadUsersList = function (response) { + var i; + for (i = 0; i < response.length; i += 1) { + if (response[i].pu_type === 'SUPERVISOR') { + gridUserList.addDataItem({ + sup_uid: response[i].usr_uid, + sup_name: response[i].usr_firstname + ' ' + response[i].usr_lastname, + obj_type: 'user', + pu_type: response[i].pu_type, + pu_uid: response[i].pu_uid + }); + } + if (response[i].pu_type === 'GROUP_SUPERVISOR') { + gridUserList.addDataItem({ + sup_uid: response[i].grp_uid, + sup_name: response[i].grp_name, + obj_type: 'group', + pu_type: response[i].pu_type, + pu_uid: response[i].pu_uid + }); + } + } + gridUserList.sort('sup_name', 'asc'); + }; + groupRows = function (grid, value) { + var i, items; + if (grid.memorystack === undefined) { + grid.memorystack = []; + } + items = grid.getItems(); + while (grid.memorystack.length > 0) { + grid.addItem(grid.memorystack.pop()); + } + if (value !== 'all') { + for (i = 0; i < items.length; i += 1) { + if (items[i].getData().obj_type !== value) { + grid.memorystack.push(items[i]); + grid.removeItem(items[i]); } } - return data; + } + grid.sort('sup_name', 'asc'); + }; + assignee = function (row) { + var restClient = new PMRestClient({ + endpoint: 'process-supervisor', + typeRequest: 'post', + data: { + usr_uid: row.data.customKeys.sup_uid, + pu_type: row.data.customKeys.obj_type === 'group' ? 'GROUP_SUPERVISOR' : 'SUPERVISOR' + }, + functionSuccess: function (xhr, response) { + row.data.customKeys.pu_type = response.pu_type; + row.data.customKeys.pu_uid = response.pu_uid; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() + }); + restClient.executeRestClient(); + }; + remove = function (row) { + var restClient = new PMRestClient({ + endpoint: 'process-supervisor/' + row.data.customKeys.pu_uid, + typeRequest: 'remove', + functionSuccess: function () { + }, + functionComplete: function () { + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }; + + assigmentWindow.open(); + panelTitleUser.addItem(titleUser); + panelTitleUserList.addItem(titleUserList); + assigmentWindow.body.style.overflow = "hidden"; + panelGridUser.addItem(gridUsers); + panelGridUserList.addItem(gridUserList); + + assigmentPanelGlobal.addItem(assigmentPanelUser); + assigmentPanelGlobal.addItem(assigmentPanelUserList); + assigmentWindow.addItem(assigmentPanelGlobal); + + assigmentPanelUser.addItem(panelTitleUser); + assigmentPanelUser.addItem(panelSearchUser); + assigmentPanelUser.addItem(buttonsUsers); + assigmentPanelUser.addItem(panelGridUser); + + assigmentPanelUserList.addItem(panelTitleUserList); + assigmentPanelUserList.addItem(panelSearchUserList); + assigmentPanelUserList.addItem(buttonsUserList); + assigmentPanelUserList.addItem(panelGridUserList); + + assigmentWindow.defineEvents(); + applyStyles(); + + loadServerData(); + }; +}()); +(function () { + PMDesigner.assigmentSupervisors = function (event) { + var assigmentWindow = null, + pageSizeAssignment = 8, + flagEdit = 0, + i, + index = 0, + quickMessageWindow = new QuickMessageWindow(), + arrayObjectUserList = new Array(), + arrayObjectUsers = new Array(), + arrayObjectUserList2 = new Array(), + arrayObjectUsers2 = new Array(), + arrayDynaformInputDocumentID = new Array(), + arrayDynaformInputDocumentObject = new Array(), + arrayObjectRemovedSteps = new Array(), + message_window, + restClient, + assigmentPanelUser, + assigmentPanelUserList, + assigmentPanelGlobal, + panelTitleUser, + titleUser, + panelSearchUser, + searchGridUser, + panelGridUser, + buttonsUsers, + gridUsers, + panelTitleUserList, + titleUserList, + panelSearchUserList, + searchGridUserList, + panelGridUserList, + radioUsersList, + buttonsUserList, + gridUserList, + radioUsers, + applyStylesRadioButtonGroupField, + applyStylesForToolbar, + applyStyles, + loadUsers, + loadUsersList, + groupRows, + assignee, + remove, + loadGridCaseTacker, + orderDataTree, + titleTreeObjects, + titleGridObjects, + panelLabelObjects, + panelObjects, + treePanelObjects, + updateItem, + usersgrid, + saveItemDyanformInputDocuments, + getValuesAssignmentSteps, + gridPanelObjects, + panelContainerObjects, + userslist, + gridpanelobj, + flashMessage = new PMUI.ui.FlashMessage({ + message: '', + appendTo: document.body, + duration: 1000, + severity: "success" + }); + assigmentWindow = new PMUI.ui.Window({ + id: 'assigmentUserWindow', + title: 'Supervisors'.translate(), + width: DEFAULT_WINDOW_WIDTH + 1, + height: DEFAULT_WINDOW_HEIGHT, + footerHeight: 'auto', + bodyHeight: 'auto', + modal: true, + onBeforeClose: function () { + if (flagEdit != 0) { + message_window.open(); + message_window.showFooter(); + } else { + assigmentWindow.close(); + } }, - columns: [{ - id: 'gridUserListButtonLabel', - title: '', - width: '10%', - dataType: 'button', - buttonLabel: function (row, data) { - return data.lastName; - }, - buttonStyle: { - cssClasses: [ - 'mafe-grid-button' - ] + footerItems: [ + { + text: "Cancel", + handler: function () { + if (flagEdit != 0) { + message_window.open(); + message_window.showFooter(); + } else { + assigmentWindow.close(); + } + }, + buttonType: 'error' }, - onButtonClick: function (row, grid) { - var option, select; - select = document.createElement("span"); - select.id = "list-usersIngroup"; - option = document.createElement("span"); - option.id = "list-usersIngroup-iem" - if (row.getData()["pu_type"] === "GROUP_SUPERVISOR") { - var restClient = new PMRestClient({ - typeRequest: 'get', - functionSuccess: function (xhr, response) { - var optionClone, i; - for (i = 0; i < response.length; i += 1) { - if (i == 10) { - optionClone = option.cloneNode(false); - optionClone.innerHTML = ". . ."; - select.appendChild(optionClone); - } else { - optionClone = option.cloneNode(false); - optionClone.textContent = "- " + response[i].usr_firstname + ' ' + response[i].usr_lastname; - optionClone.title = response[i].usr_firstname + ' ' + response[i].usr_lastname; - select.appendChild(optionClone); + { + text: 'Save', + handler: function () { + var i, j, idObject, objType, baseEndPointID; + if (flagEdit != 0) { + //save Configuration Supervisors and Steps(Dyanform - Inputs Documents) + if (gridUserList.getItems().length > 0) { + grid = gridUserList; + for (i = 0; i < arrayObjectUserList.length; i += 1) { + b = arrayObjectUserList[i]; + grid.removeItem(b); + grid.sort('sup_name', 'asc'); + gridUserList.addItem(b); + radioUsersList.setValue(radioUsers.getValue()); + groupRows(gridUserList, radioUsers.getValue()); + if (arrayObjectUserList2.indexOf(b) == -1) { + assignee(b); } } - if (!optionClone) { - optionClone = option.cloneNode(false); - optionClone.textContent = "No users".translate(); - select.appendChild(optionClone); + } + if (gridUsers.getItems().length > 0) { + for (i = 0; i < arrayObjectUsers.length; i += 1) { + b = arrayObjectUsers[i]; + if (arrayObjectUsers2.indexOf(b) == -1) { + remove(arrayObjectUsers[i]); + } } + } - quickMessageWindow.show($(row.html).find('a')[0], select); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: 'There are problems saving the assigned user, please try again.'.translate() - }); - restClient.setBaseEndPoint('group/' + row.getData()["grp_uid"] + '/supervisor-users?start=0&limit=11'); - restClient.executeRestClient(); - } + index = 0; + for (i = 0; i < gridPanelObjects.getItems().length; i += 1) { + idObject = gridPanelObjects.getItems()[i].getData().obj_uid; + index = arrayDynaformInputDocumentID.indexOf(idObject); + if (index <= -1) { + saveItemDyanformInputDocuments(gridPanelObjects.getItems()[i]); + } else { + updateItem(gridPanelObjects.getItems()[i], i); + } + } + + for (i = 0; i < arrayObjectRemovedSteps.length; i += 1) { + for (j = 0; j < arrayDynaformInputDocumentObject.length; j += 1) { + index = (arrayObjectRemovedSteps[i] == arrayDynaformInputDocumentObject[j].obj_uid) ? 0 : 1; + if (index == 0) { + objType = arrayDynaformInputDocumentObject[j].obj_type.toLowerCase(); + baseEndPointID = (objType === "dynaform") ? arrayDynaformInputDocumentObject[j].pud_uid : arrayDynaformInputDocumentObject[j].pui_uid; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": 'process-supervisor/' + objType + '/' + baseEndPointID, + "method": 'DELETE' + } + ] + }, + functionSuccess: function (xhr, response) { + }, + functionFailure: function (xhr, response) { + } + }); + restClient.executeRestClient(); + break; + } + } + } + assigmentWindow.close(); + } + else { + assigmentWindow.close(); + } + }, + buttonType: "success" } - }, { - title: '', - dataType: 'string', - columnData: 'assignee', - width: '330px', - alignmentCell: 'left' - }, { - id: 'gridUserListButtonDelete', - title: '', - dataType: 'button', - width: '10%', - buttonStyle: { - cssClasses: [ - 'mafe-button-delete-assign' - ] - }, - buttonLabel: function (row, data) { - row.getCells()[0].content.style.addClasses([row.getData()["pu_type"] === "SUPERVISOR" ? 'button-icon-user' : 'button-icon-group']); - return ''; + ], + visibleFooter: true, + buttonPanelPosition: "bottom", + footerAlign: "right" + }); + + message_window = new PMUI.ui.MessageWindow({ + id: "messageWindowCancel", + width: 490, + title: "Supervisors".translate(), + windowMessageType: "warning", + bodyHeight: "auto", + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [{ + id: "messageWindowNo", + text: "No".translate(), + handler: function () { + message_window.close(); }, - onButtonClick: function (row, grid) { - grid = (grid != null) ? grid : gridUsers; - remove(row); - gridUsers.goToPage(gridUsers.currentPage); - grid.goToPage(grid.currentPage); - flashMessage.setMessage("Assignee saved successfully".translate()); - flashMessage.setAppendTo(assigmentWindow.getHTML()); - flashMessage.show(); + buttonType: "error" + }, + { + id: "messageWindowYes", + text: "Yes".translate(), + handler: function () { + message_window.close(); + assigmentWindow.close(); + }, + buttonType: "success" } + ] + }); + + restClient = new PMRestClient({ + endpoint: 'projects', + typeRequest: 'get', + messageError: 'There are problems, please try again.'.translate(), + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); } - ], - onDropOut: function (item, origin, destiny) { - }, - onDrop: function (grid, row) { - var dataRow = {}; - grid = this; - assignee(row); - gridUsers.goToPage(gridUsers.currentPage); - grid.goToPage(grid.currentPage); - flashMessage.setMessage("Assignee saved successfully".translate()); - flashMessage.setAppendTo(assigmentWindow.getHTML()); - flashMessage.show(); - return false; - }, + }); + + assigmentPanelUser = new PMUI.core.Panel({ + layout: "vbox", + width: "49%", style: { cssClasses: [ - 'mafe-designer-assigment-grid' + 'mafe-panel-assignment-white' ] } }); - radioUsers = new PMUI.field.RadioButtonGroupField({ - id: 'idRadioUsers', - controlPositioning: 'horizontal', - maxDirectionOptions: 3, - options: [ - { - label: "View all".translate(), - value: "all" - }, - { - label: "View users".translate(), - value: "user" - }, - { - label: "View groups".translate(), - value: "group" - } - ], - onChange: function (newVal, oldVal) { - switch (newVal) { - case "user" : - gridUsers.typeList = "user"; - break; - case "group": - gridUsers.typeList = "group"; - break; - default: - gridUsers.typeList = ""; - break; - } - gridUsers.goToPage(0); - }, - required: true, - value: "all", + assigmentPanelUserList = new PMUI.core.Panel({ + layout: "vbox", + width: "50%", style: { - cssProperties: { - 'margin-top': '15px' - } + cssClasses: [ + 'mafe-panel-assignment-smooth' + ] } }); - applyStylesRadioButtonGroupField = function () { - $('#idRadioUsers .pmui-field-control-table').css("border", "none"); - $('#idRadioUsers').css("margin-top", "12px"); - radioUsers.defineEvents(); - - $('#idRadioUsersList .pmui-field-control-table').css("border", "none"); - $('#idRadioUsersList').css("margin-top", "12px"); - radioUsersList.defineEvents(); - }; - - applyStylesForToolbar = function () { - $('.pmui-gridpanel-toolbar')[0].childNodes[0].style.width = "300px"; - $('.pmui-gridpanel-toolbar')[1].childNodes[0].style.width = "300px"; - $('.pmui-gridpanel-toolbar')[0].childNodes[0].style.backgroundColor = "#f5f5f5"; - $('.pmui-gridpanel-toolbar')[1].childNodes[0].style.backgroundColor = "#f5f5f5"; - $('#assigmentUserWindow')[0].childNodes[1].childNodes[0].childNodes[1].style.backgroundColor = "white"; - $('#gridUserList')[0].style.backgroundColor = "white"; - $('#gridUserList').css("width", "452px"); - $('#gridUsers').css({"width": "452px", "height": "175px"}); - $('.pmui-window-body .pmui-panel:eq(9)').css({ - 'width': '1000px', - 'border-top': '1px solid #cdd2d5', - 'margin-top': '36px', - 'height': '80px' - }); - }; - - applyStyles = function () { - applyStylesRadioButtonGroupField(); - gridUsers.dom.toolbar.appendChild(radioUsers.getHTML()); - gridUsers.dom.toolbar.style.height = "76px"; - gridUserList.dom.toolbar.appendChild(radioUsersList.getHTML()); - gridUserList.dom.toolbar.style.height = "76px"; - radioUsers.dom.labelTextContainer.style.display = "none"; - radioUsersList.dom.labelTextContainer.style.display = "none"; - gridUsers.hideHeaders(); - gridUserList.hideHeaders(); - assigmentPanelUserList.setHeight('100%'); - gridUsers.filterControl.html.style.width = "300px"; - gridUserList.filterControl.html.style.width = "300px"; - assigmentWindow.getItems()[0].getItems()[0].html.style.borderRight = "1px solid #cdd2d5"; - assigmentWindow.getItems()[0].getItems()[0].html.style.borderBottom = "1px solid #cdd2d5"; - assigmentWindow.getItems()[0].getItems()[1].html.style.borderBottom = "1px solid #cdd2d5"; - assigmentWindow.getItems()[0].getItems()[0].html.style.height = "415px"; - assigmentWindow.getItems()[0].getItems()[1].html.style.height = "415px"; - assigmentWindow.getItems()[0].getItems()[1].html.style.paddingLeft = "10px"; - $('#gridPanelObjects .pmui-gridpanel-tableContainer').css({'height': '245px'}); - $(".pmui-gridpanel-footer").addClass("pmui-gridpanel-footer-dinamic"); - }; - loadUsers = function (response) { - var i; - for (i = 0; i < response.length; i += 1) { - if (response[i].obj_type === 'user') { - gridUsers.addDataItem({ - sup_uid: response[i].usr_uid, - sup_name: response[i].usr_firstname + ' ' + response[i].usr_lastname, - obj_type: response[i].obj_type - }); - } - if (response[i].obj_type === 'group') { - gridUsers.addDataItem({ - sup_uid: response[i].grp_uid, - sup_name: response[i].grp_name, - obj_type: response[i].obj_type - }); - } - } - gridUsers.sort('sup_name', 'asc'); - }; - loadUsersList = function (response) { - var i; - for (i = 0; i < response.length; i += 1) { - if (response[i].pu_type === 'SUPERVISOR') { - gridUserList.addDataItem({ - sup_uid: response[i].usr_uid, - sup_name: response[i].usr_firstname + ' ' + response[i].usr_lastname, - obj_type: 'user', - pu_type: response[i].pu_type, - pu_uid: response[i].pu_uid - }); - } - if (response[i].pu_type === 'GROUP_SUPERVISOR') { - gridUserList.addDataItem({ - sup_uid: response[i].grp_uid, - sup_name: response[i].grp_name, - obj_type: 'group', - pu_type: response[i].pu_type, - pu_uid: response[i].pu_uid - }); - } - } - gridUserList.sort('sup_name', 'asc'); - }; - groupRows = function (grid, value) { - var i, items; - if (grid.memorystack === undefined) { - grid.memorystack = []; - } - items = grid.getItems(); - while (grid.memorystack.length > 0) { - grid.addItem(grid.memorystack.pop()); - } - if (value !== 'all') { - for (i = 0; i < items.length; i += 1) { - if (items[i].getData().obj_type !== value) { - grid.memorystack.push(items[i]); - grid.removeItem(items[i]); - } - } - } - grid.sort('sup_name', 'asc'); - }; - assignee = function (row) { - var restClient = new PMRestClient({ - endpoint: 'process-supervisor', - typeRequest: 'post', - data: { - usr_uid: row.getData()["obj_type"] == "group" ? row.getData()["grp_uid"] : row.getData()["usr_uid"], - pu_type: row.getData()["obj_type"] === 'group' ? 'GROUP_SUPERVISOR' : 'SUPERVISOR' - }, - functionSuccess: function (xhr, response) { - row.data.customKeys.pu_type = response.pu_type; - row.data.customKeys.pu_uid = response.pu_uid; - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: 'There are problems saving the assigned user, please try again.'.translate() - }); - restClient.executeRestClient(); - }; - remove = function (row) { - var restClient = new PMRestClient({ - endpoint: 'process-supervisor/' + row.getData()["pu_uid"], - typeRequest: 'remove', - functionSuccess: function () { - }, - functionComplete: function () { - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } - }); - restClient.executeRestClient(); - }; - - //steps Dynaforms and InputDocuments - titleTreeObjects = new PMUI.ui.TextLabel({ - id: "titleTreeObjects", - textMode: 'plain', - text: 'Available Objects'.translate(), + assigmentPanelGlobal = new PMUI.core.Panel({ + layout: 'hbox', + width: DEFAULT_WINDOW_WIDTH, style: { cssClasses: [ - 'mafe-designer-assigment-title' + 'mafe-assigment-panel-global' ] } }); - titleGridObjects = new PMUI.ui.TextLabel({ - id: "titleGridObjects", + panelTitleUser = new PMUI.core.Panel({ + layout: 'hbox' + }); + titleUser = new PMUI.ui.TextLabel({ + id: 'titleUser', + label: ' ', textMode: 'plain', - text: 'Assigned objects'.translate(), + text: 'Available Users List'.translate(), style: { cssClasses: [ 'mafe-designer-assigment-title' - ], - cssProperties: { - 'left': 40 - } + ] } }); - - panelLabelObjects = new PMUI.core.Panel({ - width: DEFAULT_WINDOW_WIDTH * 0.94, - fieldset: true, - items: [ - titleTreeObjects, - titleGridObjects - ], - style: { - cssProperties: { - 'margin-bottom': 2, - 'margin-left': 50 - } - }, - layout: "hbox" + panelSearchUser = new PMUI.core.Panel({ + layout: 'hbox' }); - - panelObjects = new PMUI.core.Panel({ - width: DEFAULT_WINDOW_WIDTH * 0.94, - height: 30, - fieldset: true, - items: [ - panelLabelObjects - ], - layout: "vbox" + searchGridUser = new PMUI.field.TextField({ + id: 'searchGridUser', + label: ' ', + placeholder: 'Search ...'.translate() }); - - //Objects - orderDataTree = function (data) { - var items = [], i, - type = ['DYNAFORM', 'INPUT-DOCUMENT'], - label = ['Dynaform', 'Input Document']; - for (i = 0; i < type.length; i += 1) { - items = []; - for (var j = 0; j < data.length; j += 1) { - if (type[i] === data[j].obj_type) { - if (data[j].obj_type == "DYNAFORM") { - items.push({ - step_type_obj: label[i].translate(), - obj_label: label[i].translate(), - obj_title: data[j]['dyn_title'], - obj_type: data[j]['obj_type'], - obj_uid: data[j]['obj_uid'], - dyn_uid: data[j]['dyn_uid'] - }); - } else { - if (data[j].obj_type == "INPUT-DOCUMENT") { - items.push({ - step_type_obj: label[i].translate(), - obj_label: label[i].translate(), - obj_title: data[j]['inp_doc_title'], - obj_type: data[j]['obj_type'], - obj_uid: data[j]['obj_uid'], - obj_uid: data[j]['obj_uid'], - inp_uid: data[j]['inp_doc_uid'] - }); - } - } - } + panelGridUser = new PMUI.core.Panel({layout: 'hbox'}); + buttonsUsers = new PMUI.field.OptionsSelectorField({ + id: 'buttonsUsers', + orientation: 'horizontal', + items: [{ + text: 'All'.translate(), + selected: true, + value: 'all', + style: { + cssClasses: [ + 'pmui-switch-icon-all' + ] } - if (items.length === 0) { - dataTree.push({ - obj_title: label[i].translate(), - items: [{obj_title: 'N/A'.translate(), obj_uid: ''}] - }); - } else { - dataTree.push({ - obj_title: label[i].translate(), - items: items - }); + }, { + text: 'Users'.translate(), + value: 'user', + style: { + cssClasses: [ + 'pmui-switch-icon-user' + ] } - } - }; - - loadGridCaseTacker = function (data) { - var dataOrder = new Array(), i, j; - for (i = 0; i < data.length; i += 1) { - for (j = 0; j < data.length; j += 1) { - positionIndex = (data[j]['obj_type'] == 'DYNAFORM') ? data[j].pud_position : data[j].pui_position; - if (positionIndex == (i + 1)) { - dataOrder.push(data[j]); - switch (dataOrder[i]['obj_type']) { - case 'DYNAFORM': - label = dataOrder[i]['dyn_title'].translate(); - break; - case 'INPUT-DOCUMENT': - label = dataOrder[i]['input_doc_title'].translate(); - break; - default: - break; - } - dataOrder[i]['obj_title'] = label; - break; - } + }, { + text: 'Groups'.translate(), + value: 'group', + style: { + cssClasses: [ + 'pmui-switch-icon-group' + ] } } - gridPanelObjects.setDataItems(dataOrder); - }; - - getValuesAssignmentSteps = function () { - restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - "calls": [ - { - "url": "process-supervisor/available-assignmentsteps", - "method": 'GET' - }, - { - "url": "process-supervisor/assignmentsteps", - "method": 'GET' - } - ] - }, - functionSuccess: function (xhr, response) { - dataTree = []; - orderDataTree(response[0].response); - treePanelObjects.setDataItems(dataTree); - loadGridCaseTacker(response[1].response); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); + ], + listeners: { + select: function (item, event) { + groupRows(gridUsers, item.value); } - }); - restClient.executeRestClient(); - }; - - treePanelObjects = new PMUI.panel.TreePanel({ - id: 'treePanelObjects', - proportion: 0.5, + }, + style: { + cssClasses: [ + 'mafe-assigment-buttons' + ] + } + }); + gridUsers = new PMUI.grid.GridPanel({ + id: 'gridUsers', + pageSize: pageSizeAssignment, + behavior: 'dragdropsort', filterable: true, - filterPlaceholder: 'Text to search'.translate(), + filterPlaceholder: 'Search ...'.translate(), emptyMessage: 'No records found'.translate(), - style: {cssClasses: ['itemsSteps']}, - nodeDefaultSettings: { - behavior: "drag", - labelDataBind: 'obj_title', - itemsDataBind: 'items', - collapsed: false, - childrenDefaultSettings: { - labelDataBind: 'obj_title', - autoBind: true + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + dynamicLoad: { + keys: { + server: HTTP_SERVER_HOSTNAME, + projectID: PMDesigner.project.projectId, + workspace: WORKSPACE, + accessToken: PMDesigner.project.tokens.access_token, + endPoint: 'project/' + PMDesigner.project.id + '/available-process-supervisors/paged' + } + }, + customDataRest: function (data) { + var i; + for (i = 0; i < data.length; i += 1) { + if (data[i].obj_type == "group") { + data[i].available = data[i].grp_name; + } else { + data[i].available = data[i]["usr_firstname"] + " " + data[i]["usr_lastname"] + " (" + data[i]["usr_username"] + ")"; + } + } + return data; + }, + columns: [{ + id: 'gridUsersButtonLabel', + title: '', + dataType: 'button', + width: '10%', + buttonLabel: function (row, data) { + return data.lastName; }, - autoBind: true - } - }); - - //Save Item (Drop) - saveItemDyanformInputDocuments = function (rowStep) { - rowStep = rowStep.getData(); - if (rowStep.obj_type === "DYNAFORM") { - data = { - "dyn_uid": rowStep.obj_uid, - "pud_position": rowStep.obj_position - }; - } else { - data = { - "inp_doc_uid": rowStep.obj_uid, - "pui_position": rowStep.obj_position - }; - } + buttonStyle: { + cssClasses: [ + 'mafe-grid-button' + ] + }, + onButtonClick: function (row, grid) { + var option, select; + select = document.createElement("span"); + select.id = "list-usersIngroup"; + option = document.createElement("span"); + option.id = "list-usersIngroup-iem" + if (row.getData()["obj_type"] === 'group') { + var restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var optionClone, i; + for (i = 0; i < response.length; i += 1) { + if (i == 10) { + optionClone = option.cloneNode(false); + optionClone.innerHTML = ". . ."; + select.appendChild(optionClone); + } else { + optionClone = option.cloneNode(false); + optionClone.textContent = "- " + response[i].usr_firstname + ' ' + response[i].usr_lastname; + optionClone.title = response[i].usr_firstname + ' ' + response[i].usr_lastname; + select.appendChild(optionClone); + } + } + if (!optionClone) { + optionClone = option.cloneNode(false); + optionClone.textContent = "No users".translate(); + select.appendChild(optionClone); + } - restClient = new PMRestClient({ - endpoint: 'process-supervisor/' + rowStep.obj_type.toLowerCase(), - typeRequest: 'post', - data: data, - functionSuccess: function (xhr, response) { - }, - functionFailure: function (xhr, response) { + quickMessageWindow.show($(row.html).find('a')[0], select); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() + }); + restClient.setBaseEndPoint('group/' + row.getData()["grp_uid"] + '/supervisor-users?start=0&limit=11'); + restClient.executeRestClient(); + } } - }); - restClient.executeRestClient(); - return data; - }; - - //Update SORT tree - updateItem = function (rowStep, i) { - var objType, - baseEndPointType, - baseEndPointID; - rowStep = rowStep.getData(); - rowStep.obj_position = i + 1; - objType = rowStep.obj_type.toLowerCase(), - baseEndPointType = (objType === "dynaform") ? 'dynaforms' : 'input-documents'; - baseEndPointID = (objType === "dynaform") ? rowStep.pud_uid : rowStep.pui_uid; - if (objType === "dynaform") { - rowStep.pud_position = rowStep.obj_position; - } else { - rowStep.pui_position = rowStep.obj_position; - } - - restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - "calls": [ - { - "url": 'process-supervisor/' + objType + "/" + baseEndPointID, - "method": 'PUT', - "data": rowStep - } + }, { + title: '', + dataType: 'string', + columnData: 'available', + alignmentCell: 'left', + width: '330px' + }, { + id: 'gridUsersButtonAssign', + title: '', + dataType: 'button', + width: '19%', + buttonStyle: { + cssClasses: [ + 'mafe-button-edit-assign' ] }, - functionSuccess: function (xhr, response) { + buttonLabel: function (row, data) { + row.getCells()[0].content.style.addClasses([row.getData()["obj_type"] === 'user' ? 'button-icon-user' : 'button-icon-group']); + return ''; }, - functionFailure: function (xhr, response) { + onButtonClick: function (row, grid) { + grid = (grid != null) ? grid : gridUsers; + assignee(row); + gridUserList.goToPage(gridUserList.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("The user/group was successfully removed".translate()); + flashMessage.setAppendTo(assigmentWindow.getHTML()); + flashMessage.show(); } - }); - restClient.executeRestClient(); - }; - gridPanelObjects = new PMUI.grid.GridPanel({ - id: 'gridPanelObjects', - proportion: 1.5, - visibleFooter: false, - filterable: false, - style: { - cssClasses: ['itemsSteps'] + } + ], + onDropOut: function (item, origin, destiny) { }, - filterPlaceholder: 'Search ...'.translate(), - emptyMessage: 'No records found'.translate(), - nextLabel: 'Next'.translate(), - previousLabel: 'Previous'.translate(), - customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { - return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + onDrop: function (a, row) { + grid = this; + remove(row); + gridUserList.goToPage(gridUserList.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("The user/group was successfully removed".translate()); + flashMessage.setAppendTo(assigmentWindow.getHTML()); + flashMessage.show(); + return false; }, - behavior: 'dragdropsort', - columns: [ + style: { + cssClasses: [ + 'mafe-designer-assigment-grid' + ] + } + }); + + panelTitleUserList = new PMUI.core.Panel({ + layout: 'hbox' + }); + titleUserList = new PMUI.ui.TextLabel({ + id: 'titleUserList', + textMode: 'plain', + text: 'Assigned supervisors list'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ] + } + }); + panelSearchUserList = new PMUI.core.Panel({ + layout: 'hbox' + }); + searchGridUserList = new PMUI.field.TextField({ + id: 'searchGridUserList', + label: ' ', + placeholder: 'Search ...'.translate() + }); + panelGridUserList = new PMUI.core.Panel({ + layout: 'hbox' + }); + radioUsersList = new PMUI.field.RadioButtonGroupField({ + id: 'idRadioUsersList', + controlPositioning: 'horizontal', + maxDirectionOptions: 3, + options: [ { - title: 'Title'.translate(), - dataType: 'string', - width: 330, - alignment: "left", - columnData: "obj_title", - sortable: false, - alignmentCell: 'left' + label: "View all".translate(), + value: "all" }, { - title: 'Type'.translate(), - dataType: 'string', - width: 120, - alignment: "left", - columnData: "obj_type", - sortable: false, - alignmentCell: 'left' + label: "View users".translate(), + value: "user" }, { - id: 'gridPanelObjectsButtonDelete', - title: '', - dataType: 'button', - buttonLabel: '', - buttonStyle: {cssClasses: ['mafe-button-delete-assign']}, - buttonTooltip: 'Remove Object'.translate(), - onButtonClick: function (row, grid) { - var rowStep, treePanelItems; - flagEdit = 1; - index = arrayDynaformInputDocumentID.indexOf(row.getData().obj_uid); - rowStep = row.getData(); - treePanelItems = treePanelObjects.getItems(); - - if (index > -1) { - arrayObjectRemovedSteps.push(row.getData().obj_uid); - arrayDynaformInputDocumentID.splice(index, 1); - } - function removeRowClass(treeNode) { - var childNodeEl = $(treeNode.html).find('.pmui-gridpanelrow'); - childNodeEl.removeClass('pmui-gridpanelrow'); - } - - function removeEmptyNode(indexNode) { - var parentNode = treePanelItems[indexNode]; - if (parentNode.getItems().length == 1 && - parentNode.getItems()[0].getData()['obj_uid'] == "") { - parentNode.removeItem(0); - } - parentNode.addItem(row); - removeRowClass(parentNode); - } - - if (rowStep.obj_type === "DYNAFORM") { - removeEmptyNode(0); - } else { - removeEmptyNode(1); - } - grid.removeItem(row); - } + label: "View groups".translate(), + value: "group" } ], - onDrop: function (grid, item, index) { - var parentItems; - if (item.getData()['obj_uid'] == "") { - return false; - + onChange: function (newVal, oldVal) { + switch (newVal) { + case "user" : + gridUserList.typeList = "user".translate(); + break; + case "group": + gridUserList.typeList = "group".translate(); + break; + default: + gridUserList.typeList = ""; + break; + } + gridUserList.goToPage(0); + }, + required: true, + value: "all" + }); + buttonsUserList = new PMUI.field.OptionsSelectorField({ + id: 'buttonsUserList', + orientation: 'horizontal', + items: [{ + text: 'All'.translate(), + value: 'all', + selected: true, + style: { + cssClasses: [ + 'pmui-switch-icon-all' + ] + } + }, { + text: 'Users'.translate(), + value: 'user', + style: { + cssClasses: [ + 'pmui-switch-icon-user' + ] } - parentItems = item.parent.getItems(); - if (parentItems.length == 1 && item.getData()['obj_uid'] != "") { - item.parent.addDataItem( - {obj_title: 'N/A'.translate(), obj_uid: ''} - ); - item.parent.behaviorObject.draggedObject = item; + }, { + text: 'Groups'.translate(), + value: 'group', + style: { + cssClasses: [ + 'pmui-switch-icon-group' + ] } - flagEdit = 1; - rowStep = item.getData(); - rowStep.obj_position = index + 1; - item.setData(rowStep); - index = arrayObjectRemovedSteps.indexOf(item.getData().obj_uid); + } - if (index > -1) { - arrayDynaformInputDocumentID.push(item.getData().obj_uid); - arrayObjectRemovedSteps.splice(index, 1); + ], + listeners: { + select: function (item, event) { + groupRows(gridUserList, item.value); } }, - onSort: function (grid, item, index) { - flagEdit = 1; - rowStep = item.getData(); - rowStep.obj_position = index + 1; - } - }); - - //principal Container Steps - panelContainerObjects = new PMUI.core.Panel({ - id: "panelContainerObjects", - width: DEFAULT_WINDOW_WIDTH, - height: 250, - fieldset: true, - items: [treePanelObjects, gridPanelObjects], - layout: "hbox", style: { - cssProperties: { - 'margin-top': '-40px' - } + cssClasses: [ + 'mafe-assigment-buttons' + ] } }); - - assigmentWindow.open(); - panelTitleUser.addItem(titleUser); - panelTitleUserList.addItem(titleUserList); - assigmentWindow.body.style.overflowX = "hidden"; - - panelGridUser.addItem(gridUsers); - panelGridUserList.addItem(gridUserList); - - assigmentPanelGlobal.addItem(assigmentPanelUser); - assigmentPanelGlobal.addItem(assigmentPanelUserList); - assigmentWindow.addItem(assigmentPanelGlobal); - - assigmentWindow.addItem(panelObjects); - assigmentWindow.addItem(panelContainerObjects); - getValuesAssignmentSteps(); - - gridPanelObjects.style.addProperties({overflow: 'auto'}); - gridPanelObjects.style.addProperties({float: 'right'}); - gridPanelObjects.setWidth(630); - gridPanelObjects.setHeight(250); - $('#gridPanelObjects').css("margin-right", "32px"); - $('#treePanelObjects').css("margin-left", "10px"); - - assigmentPanelUser.addItem(panelTitleUser); - assigmentPanelUser.addItem(panelSearchUser); - assigmentPanelUser.addItem(radioUsers); - assigmentPanelUser.addItem(panelGridUser); - - assigmentPanelUserList.addItem(panelTitleUserList); - assigmentPanelUserList.addItem(panelSearchUserList); - assigmentPanelUserList.addItem(radioUsersList); - assigmentPanelUserList.addItem(panelGridUserList); - gridUsers.dom.tableContainer.style.height = "245px"; - gridUserList.dom.tableContainer.style.height = "245px"; - gridUsers.goToPage(0); - gridUserList.goToPage(0); - assigmentWindow.defineEvents(); - applyStyles(); - treePanelObjects.style.addProperties({overflow: 'auto'}); - - applyStylesForToolbar(); - usersgrid = gridUsers; - for (i = 0; i < usersgrid.getItems().length; i += 1) { - arrayObjectUsers2[i] = usersgrid.getItems()[i]; - } - userslist = gridUserList; - for (i = 0; i < userslist.getItems().length; i += 1) { - arrayObjectUserList2[i] = userslist.getItems()[i]; - } - gridpanelobj = gridPanelObjects; - for (i = 0; i < gridpanelobj.getItems().length; i += 1) { - arrayDynaformInputDocumentID[i] = gridpanelobj.getItems()[i].getData().obj_uid; - arrayDynaformInputDocumentObject[i] = gridpanelobj.getItems()[i].getData(); - } - }; -}()); -( - function () { - PMDesigner.propertiesProcess = function () { - var responseProperties = null, - getValuesProperties, - isDirtyFormProcess, - saveProperties, - propertiesWindow, - processUID, - textTitle, - textDescription, - dropCalendar, - dropProcessCat, - dropDynaform, - dropRouting, - checkDebug, - checkHideCase, - checkSubProcess, - dropCaseCreated, - dropCaseDeleted, - dropCaseCancelled, - dropCasePaused, - dropCaseUnpaused, - dropCaseReassigned, - dropCaseOpen, - dropTypeProcess, - proCost, - loadProperties, - proUnitCost, - formEditProcess, - loadDynaforms, - loadCalendar, - loadTemplate, - loadTriggers, - loadTypeProcess, - loadCategory, - clickedClose; - - getValuesProperties = function () { - var restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - "calls": [ - { - "url": "project/" + PMDesigner.project.id + "/dynaforms", - "method": 'GET' - }, - { - "url": "calendars", - "method": 'GET' - }, - { - "url": "project/categories", - "method": 'GET' - }, - { - "url": "project/" + PMDesigner.project.id + "/file-manager?path=templates", - "method": 'GET' - }, - { - "url": "project/" + PMDesigner.project.id + "/triggers", - "method": 'GET' - }, - { - "url": "project/" + PMDesigner.project.id + "/process", - "method": 'GET' - } - ] - }, - functionSuccess: function (xhr, response) { - loadDynaforms(response[0].response); - loadCalendar(response[1].response); - loadCategory(response[2].response); - loadTemplate(response[3].response); - loadTriggers(response[4].response); - loadTypeProcess(response[5].response); - loadProperties(response[5].response); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } - }); - restClient.setBaseEndPoint(''); - restClient.executeRestClient(); - }; - isDirtyFormProcess = function () { - var message_window - if (formEditProcess.isDirty()) { - message_window = new PMUI.ui.MessageWindow({ - id: "cancelMessageTriggers", - windowMessageType: 'warning', - width: 490, - title: "Edit process".translate(), - message: 'Are you sure you want to discard your changes?'.translate(), - footerItems: [ - { - text: "No".translate(), - handler: function () { - message_window.close(); - }, - buttonType: "error" - }, - { - text: "Yes".translate(), - handler: function () { - message_window.close(); - propertiesWindow.close(); - }, - buttonType: "success" - } - ] - }); - message_window.open(); - message_window.showFooter(); - } else { - propertiesWindow.close(); - } - }; - saveProperties = function (data) { - var restClient = new PMRestClient({ - typeRequest: 'update', - data: data, - messageSuccess: "Properties saved successfully".translate(), - functionSuccess: function (xhr, response) { - propertiesWindow.close(); - - PMDesigner.project.setProjectName(data.pro_title); - PMDesigner.project.setDescription(data.pro_description); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - - PMDesigner.project.dirty = false; + gridUserList = new PMUI.grid.GridPanel({ + id: 'gridUserList', + pageSize: pageSizeAssignment, + behavior: 'dragdropsort', + filterPlaceholder: 'Search ...'.translate(), + filterable: true, + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + emptyMessage: function () { + var div = document.createElement('div'), + span = document.createElement('span'); + div.appendChild(span); + div.className = 'mafe-grid-panel-empty'; + span.innerHTML = 'Drag & Drop a User or a Group here'.translate(); + return div; + }, + onEmpty: function (grid, cell) { + gridUserList.dom.tableContainer.style.overflow = 'hidden'; + }, + dynamicLoad: { + keys: { + server: HTTP_SERVER_HOSTNAME, + projectID: PMDesigner.project.projectId, + workspace: WORKSPACE, + accessToken: PMDesigner.project.tokens.access_token, + endPoint: 'project/' + PMDesigner.project.id + '/process-supervisors/paged' + } + }, + customDataRest: function (data) { + var i; + for (i = 0; i < data.length; i += 1) { + if (data[i].pu_type == "GROUP_SUPERVISOR") { + data[i].assignee = data[i].grp_name; + } else { + data[i].assignee = data[i]["usr_firstname"] + " " + data[i]["usr_lastname"] + " (" + data[i]["usr_username"] + ")"; } - }); - restClient.setEndpoint("process"); - restClient.executeRestClient(); - }; - - propertiesWindow = new PMUI.ui.Window({ - id: "propertiesProcessWindow", - title: "Edit process".translate(), - width: DEFAULT_WINDOW_WIDTH, - height: DEFAULT_WINDOW_HEIGHT, - footerHeight: 'auto', - bodyHeight: "auto", - modal: true, - buttonPanelPosition: "bottom", - footerAlign: "right", - onBeforeClose: function () { - clickClose = true; - isDirtyFormProcess(); + } + return data; + }, + columns: [{ + id: 'gridUserListButtonLabel', + title: '', + width: '10%', + dataType: 'button', + buttonLabel: function (row, data) { + return data.lastName; }, - buttons: [ - { - id: 'outputWindowDocButtonCancel', - text: "Cancel".translate(), - buttonType: "error", - handler: function () { - clickedClose = false; - isDirtyFormProcess(); - } - }, - { - id: 'outputWindowDocButtonSave', - text: "Save".translate(), - buttonType: "success", - handler: function () { - var dataForm; - if (formEditProcess.isValid()) { - if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { - dataForm = getData2PMUI(formEditProcess.html); - } else { - dataForm = formEditProcess.getData(); + buttonStyle: { + cssClasses: [ + 'mafe-grid-button' + ] + }, + onButtonClick: function (row, grid) { + var option, select; + select = document.createElement("span"); + select.id = "list-usersIngroup"; + option = document.createElement("span"); + option.id = "list-usersIngroup-iem" + if (row.getData()["pu_type"] === "GROUP_SUPERVISOR") { + var restClient = new PMRestClient({ + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var optionClone, i; + for (i = 0; i < response.length; i += 1) { + if (i == 10) { + optionClone = option.cloneNode(false); + optionClone.innerHTML = ". . ."; + select.appendChild(optionClone); + } else { + optionClone = option.cloneNode(false); + optionClone.textContent = "- " + response[i].usr_firstname + ' ' + response[i].usr_lastname; + optionClone.title = response[i].usr_firstname + ' ' + response[i].usr_lastname; + select.appendChild(optionClone); + } + } + if (!optionClone) { + optionClone = option.cloneNode(false); + optionClone.textContent = "No users".translate(); + select.appendChild(optionClone); } - dataForm.pro_debug = checkDebug.controls[0].selected ? 1 : 0; - dataForm.pro_show_message = checkHideCase.controls[0].selected ? 1 : 0; - dataForm.pro_subprocess = checkSubProcess.controls[0].selected ? 1 : 0; - functionAssignmentUsers = function (xhr, response) { - }; - saveProperties(dataForm); - } - } - } - ] - }); - - processUID = new PMUI.field.TextField({ - label: "UID".translate(), - id: "process_uid", - name: "pro_uid", - labelWidth: "35%", - controlsWidth: "300px" - }); - - textTitle = new PMUI.field.TextField({ - label: "Title".translate(), - id: 'textTitle', - name: 'pro_title', - labelWidth: "35%", - placeholder: 'a text here'.translate(), - controlsWidth: "300px", - required: true - }); - - textDescription = new PMUI.field.TextAreaField({ - id: 'textDescription', - name: 'pro_description', - label: "Description".translate(), - labelWidth: "35%", - controlsWidth: "500px", - rows: 150, - style: {cssClasses: ['mafe-textarea-resize']} - }); - dropCalendar = new PMUI.field.DropDownListField({ - id: "dropCalendar", - name: "pro_calendar", - labelWidth: "35%", - label: "Calendar".translate(), - controlsWidth: "300px", - valueType: 'string', - onChange: function (newValue, prevValue) { + quickMessageWindow.show($(row.html).find('a')[0], select); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() + }); + restClient.setBaseEndPoint('group/' + row.getData()["grp_uid"] + '/supervisor-users?start=0&limit=11'); + restClient.executeRestClient(); + } } - }); - - dropProcessCat = new PMUI.field.DropDownListField({ - id: "dropProcessCat", - name: "pro_category", - controlsWidth: "300px", - labelWidth: "35%", - label: "Process Category".translate(), - valueType: 'string', - onChange: function (newValue, prevValue) { + }, { + title: '', + dataType: 'string', + columnData: 'assignee', + width: '330px', + alignmentCell: 'left' + }, { + id: 'gridUserListButtonDelete', + title: '', + dataType: 'button', + width: '10%', + buttonStyle: { + cssClasses: [ + 'mafe-button-delete-assign' + ] + }, + buttonLabel: function (row, data) { + row.getCells()[0].content.style.addClasses([row.getData()["pu_type"] === "SUPERVISOR" ? 'button-icon-user' : 'button-icon-group']); + return ''; + }, + onButtonClick: function (row, grid) { + grid = (grid != null) ? grid : gridUsers; + remove(row); + gridUsers.goToPage(gridUsers.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("Assignee saved successfully".translate()); + flashMessage.setAppendTo(assigmentWindow.getHTML()); + flashMessage.show(); } - }); - - dropDynaform = new PMUI.field.DropDownListField({ - id: "dropDynaform", - name: "pro_summary_dynaform", - controlsWidth: "300px", - labelWidth: "35%", - label: "Dynaform to show a case summary".translate(), - valueType: 'string', - onChange: function (newValue, prevValue) { + } + ], + onDropOut: function (item, origin, destiny) { + }, + onDrop: function (grid, row) { + var dataRow = {}; + grid = this; + assignee(row); + gridUsers.goToPage(gridUsers.currentPage); + grid.goToPage(grid.currentPage); + flashMessage.setMessage("Assignee saved successfully".translate()); + flashMessage.setAppendTo(assigmentWindow.getHTML()); + flashMessage.show(); + return false; + }, + style: { + cssClasses: [ + 'mafe-designer-assigment-grid' + ] + } + }); + radioUsers = new PMUI.field.RadioButtonGroupField({ + id: 'idRadioUsers', + controlPositioning: 'horizontal', + maxDirectionOptions: 3, + options: [ + { + label: "View all".translate(), + value: "all" + }, + { + label: "View users".translate(), + value: "user" + }, + { + label: "View groups".translate(), + value: "group" + } + ], + onChange: function (newVal, oldVal) { + switch (newVal) { + case "user" : + gridUsers.typeList = "user"; + break; + case "group": + gridUsers.typeList = "group"; + break; + default: + gridUsers.typeList = ""; + break; } - }); - - dropRouting = new PMUI.field.DropDownListField({ - id: "dropRouting", - name: "pro_derivation_screen_tpl", - controlsWidth: "300px", - labelWidth: "35%", - label: "Routing Screen Template".translate(), - valueType: 'string', - onChange: function (newValue, prevValue) { + gridUsers.goToPage(0); + }, + required: true, + value: "all", + style: { + cssProperties: { + 'margin-top': '15px' } - }); + } + }); + applyStylesRadioButtonGroupField = function () { + $('#idRadioUsers .pmui-field-control-table').css("border", "none"); + $('#idRadioUsers').css("margin-top", "12px"); + radioUsers.defineEvents(); - checkDebug = new PMUI.field.CheckBoxGroupField({ - id: 'checkDebug', - labelWidth: "35%", - label: "Debug".translate(), - name: "pro_debug", - value: '1', - controlPositioning: 'vertical', - options: [ - { - id: 'pro_debug', - disabled: false, - value: '1', - selected: false - } - ], - onChange: function (newVal, oldVal) { - } - }); + $('#idRadioUsersList .pmui-field-control-table').css("border", "none"); + $('#idRadioUsersList').css("margin-top", "12px"); + radioUsersList.defineEvents(); + }; - checkHideCase = new PMUI.field.CheckBoxGroupField({ - id: 'checkHideCase', - labelWidth: "35%", - label: "Hide the case number and the case title in the steps".translate(), - value: '1', - name: "pro_show_message", - controlPositioning: 'vertical', - options: [ - { - disabled: false, - value: '1', - selected: false - } - ], - onChange: function (newVal, oldVal) { - } + applyStylesForToolbar = function () { + $('.pmui-gridpanel-toolbar')[0].childNodes[0].style.width = "300px"; + $('.pmui-gridpanel-toolbar')[1].childNodes[0].style.width = "300px"; + $('.pmui-gridpanel-toolbar')[0].childNodes[0].style.backgroundColor = "#f5f5f5"; + $('.pmui-gridpanel-toolbar')[1].childNodes[0].style.backgroundColor = "#f5f5f5"; + $('#assigmentUserWindow')[0].childNodes[1].childNodes[0].childNodes[1].style.backgroundColor = "white"; + $('#gridUserList')[0].style.backgroundColor = "white"; + $('#gridUserList').css("width", "452px"); + $('#gridUsers').css({"width": "452px", "height": "175px"}); + $('.pmui-window-body .pmui-panel:eq(9)').css({ + 'width': '1000px', + 'border-top': '1px solid #cdd2d5', + 'margin-top': '36px', + 'height': '80px' }); + }; - checkSubProcess = new PMUI.field.CheckBoxGroupField({ - id: 'checkSubProcess', - labelWidth: "35%", - label: "This a sub-process".translate(), - value: '1', - name: "pro_subprocess", - controlPositioning: 'vertical', - options: [ - { - disabled: false, - value: '1', - selected: false - } - ], - onChange: function (newVal, oldVal) { + applyStyles = function () { + applyStylesRadioButtonGroupField(); + gridUsers.dom.toolbar.appendChild(radioUsers.getHTML()); + gridUsers.dom.toolbar.style.height = "76px"; + gridUserList.dom.toolbar.appendChild(radioUsersList.getHTML()); + gridUserList.dom.toolbar.style.height = "76px"; + radioUsers.dom.labelTextContainer.style.display = "none"; + radioUsersList.dom.labelTextContainer.style.display = "none"; + gridUsers.hideHeaders(); + gridUserList.hideHeaders(); + assigmentPanelUserList.setHeight('100%'); + gridUsers.filterControl.html.style.width = "300px"; + gridUserList.filterControl.html.style.width = "300px"; + assigmentWindow.getItems()[0].getItems()[0].html.style.borderRight = "1px solid #cdd2d5"; + assigmentWindow.getItems()[0].getItems()[0].html.style.borderBottom = "1px solid #cdd2d5"; + assigmentWindow.getItems()[0].getItems()[1].html.style.borderBottom = "1px solid #cdd2d5"; + assigmentWindow.getItems()[0].getItems()[0].html.style.height = "415px"; + assigmentWindow.getItems()[0].getItems()[1].html.style.height = "415px"; + assigmentWindow.getItems()[0].getItems()[1].html.style.paddingLeft = "10px"; + $('#gridPanelObjects .pmui-gridpanel-tableContainer').css({'height': '245px'}); + $(".pmui-gridpanel-footer").addClass("pmui-gridpanel-footer-dinamic"); + }; + loadUsers = function (response) { + var i; + for (i = 0; i < response.length; i += 1) { + if (response[i].obj_type === 'user') { + gridUsers.addDataItem({ + sup_uid: response[i].usr_uid, + sup_name: response[i].usr_firstname + ' ' + response[i].usr_lastname, + obj_type: response[i].obj_type + }); } - }); - dropCaseCreated = new PMUI.field.DropDownListField({ - id: "dropCaseCreated", - name: "pro_tri_create", - labelWidth: "35%", - label: "Execute a trigger when a case is created".translate(), - valueType: 'string', - controlsWidth: "300px", - onChange: function (newValue, prevValue) { + if (response[i].obj_type === 'group') { + gridUsers.addDataItem({ + sup_uid: response[i].grp_uid, + sup_name: response[i].grp_name, + obj_type: response[i].obj_type + }); } - }); - - dropCaseDeleted = new PMUI.field.DropDownListField({ - id: "dropCaseDeleted", - name: "pro_tri_deleted", - labelWidth: "35%", - label: "Execute a trigger when a case is deleted".translate(), - valueType: 'string', - controlsWidth: "300px", - onChange: function (newValue, prevValue) { + } + gridUsers.sort('sup_name', 'asc'); + }; + loadUsersList = function (response) { + var i; + for (i = 0; i < response.length; i += 1) { + if (response[i].pu_type === 'SUPERVISOR') { + gridUserList.addDataItem({ + sup_uid: response[i].usr_uid, + sup_name: response[i].usr_firstname + ' ' + response[i].usr_lastname, + obj_type: 'user', + pu_type: response[i].pu_type, + pu_uid: response[i].pu_uid + }); } - }); - - dropCaseCancelled = new PMUI.field.DropDownListField({ - id: "dropCaseCancelled", - name: "pro_tri_canceled", - labelWidth: "35%", - label: "Execute a trigger when a case is cancelled".translate(), - valueType: 'string', - controlsWidth: "300px", - onChange: function (newValue, prevValue) { + if (response[i].pu_type === 'GROUP_SUPERVISOR') { + gridUserList.addDataItem({ + sup_uid: response[i].grp_uid, + sup_name: response[i].grp_name, + obj_type: 'group', + pu_type: response[i].pu_type, + pu_uid: response[i].pu_uid + }); } - }); - - dropCasePaused = new PMUI.field.DropDownListField({ - id: "dropCasePaused", - name: "pro_tri_paused", - labelWidth: "35%", - label: "Execute a trigger when a case is paused".translate(), - valueType: 'string', - controlsWidth: "300px", - onChange: function (newValue, prevValue) { + } + gridUserList.sort('sup_name', 'asc'); + }; + groupRows = function (grid, value) { + var i, items; + if (grid.memorystack === undefined) { + grid.memorystack = []; + } + items = grid.getItems(); + while (grid.memorystack.length > 0) { + grid.addItem(grid.memorystack.pop()); + } + if (value !== 'all') { + for (i = 0; i < items.length; i += 1) { + if (items[i].getData().obj_type !== value) { + grid.memorystack.push(items[i]); + grid.removeItem(items[i]); + } } + } + grid.sort('sup_name', 'asc'); + }; + assignee = function (row) { + var restClient = new PMRestClient({ + endpoint: 'process-supervisor', + typeRequest: 'post', + data: { + usr_uid: row.getData()["obj_type"] == "group" ? row.getData()["grp_uid"] : row.getData()["usr_uid"], + pu_type: row.getData()["obj_type"] === 'group' ? 'GROUP_SUPERVISOR' : 'SUPERVISOR' + }, + functionSuccess: function (xhr, response) { + row.data.customKeys.pu_type = response.pu_type; + row.data.customKeys.pu_uid = response.pu_uid; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: 'There are problems saving the assigned user, please try again.'.translate() }); - - dropCaseUnpaused = new PMUI.field.DropDownListField({ - id: "dropCaseUnpaused", - name: "pro_tri_unpaused", - labelWidth: "35%", - label: "Execute a trigger when a case is unpaused".translate(), - valueType: "string", - controlsWidth: "300px" - }); - - dropCaseReassigned = new PMUI.field.DropDownListField({ - id: "dropCaseReassigned", - name: "pro_tri_reassigned", - labelWidth: "35%", - label: "Execute a trigger when a case is reassigned".translate(), - valueType: 'string', - controlsWidth: "300px", - onChange: function (newValue, prevValue) { + restClient.executeRestClient(); + }; + remove = function (row) { + var restClient = new PMRestClient({ + endpoint: 'process-supervisor/' + row.getData()["pu_uid"], + typeRequest: 'remove', + functionSuccess: function () { + }, + functionComplete: function () { + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); } }); + restClient.executeRestClient(); + }; - dropCaseOpen = new PMUI.field.DropDownListField({ - id: "dropCaseOpen", - name: "pro_tri_open", - label: "Execute a trigger when a case is opened".translate(), - labelWidth: "35%", - valueType: "string", - controlsWidth: "300px", + //steps Dynaforms and InputDocuments + titleTreeObjects = new PMUI.ui.TextLabel({ + id: "titleTreeObjects", + textMode: 'plain', + text: 'Available Objects'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ] + } + }); - onChange: function (newValue, prevValue) { + titleGridObjects = new PMUI.ui.TextLabel({ + id: "titleGridObjects", + textMode: 'plain', + text: 'Assigned objects'.translate(), + style: { + cssClasses: [ + 'mafe-designer-assigment-title' + ], + cssProperties: { + 'left': 40 } - }); + } + }); - dropTypeProcess = new PMUI.field.DropDownListField({ - id: "dropTypeProcess", - name: "pro_type_process", - labelWidth: "35%", - label: "Process Design Access: Public / Private (Owner)".translate(), - valueType: 'string', - controlsWidth: "300px", - onChange: function (newValue, prevValue) { + panelLabelObjects = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH * 0.94, + fieldset: true, + items: [ + titleTreeObjects, + titleGridObjects + ], + style: { + cssProperties: { + 'margin-bottom': 2, + 'margin-left': 50 } - }); + }, + layout: "hbox" + }); - proCost = new PMUI.field.TextField({ - id: 'proCost', - name: 'pro_cost', - labelWidth: "35%", - value: 0, - placeholder: 'a cost here'.translate(), - label: "Cost".translate(), - valueType: 'integer', - controlsWidth: "300px", - required: window.enterprise === "1" ? true : false, - style: { - cssProperties: { - float: "left" - } - } - }); + panelObjects = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH * 0.94, + height: 30, + fieldset: true, + items: [ + panelLabelObjects + ], + layout: "vbox" + }); - proUnitCost = new PMUI.field.TextField({ - id: 'proUnitCost', - name: 'pro_unit_cost', - labelWidth: "35%", - value: '$', - placeholder: 'a unit cost here'.translate(), - controlsWidth: "300px", - label: "Units".translate(), - valueType: 'string', - required: window.enterprise === "1" ? true : false, - style: { - cssProperties: { - float: "left" + //Objects + orderDataTree = function (data) { + var items = [], i, + type = ['DYNAFORM', 'INPUT-DOCUMENT'], + label = ['Dynaform', 'Input Document']; + for (i = 0; i < type.length; i += 1) { + items = []; + for (var j = 0; j < data.length; j += 1) { + if (type[i] === data[j].obj_type) { + if (data[j].obj_type == "DYNAFORM") { + items.push({ + step_type_obj: label[i].translate(), + obj_label: label[i].translate(), + obj_title: data[j]['dyn_title'], + obj_type: data[j]['obj_type'], + obj_uid: data[j]['obj_uid'], + dyn_uid: data[j]['dyn_uid'] + }); + } else { + if (data[j].obj_type == "INPUT-DOCUMENT") { + items.push({ + step_type_obj: label[i].translate(), + obj_label: label[i].translate(), + obj_title: data[j]['inp_doc_title'], + obj_type: data[j]['obj_type'], + obj_uid: data[j]['obj_uid'], + obj_uid: data[j]['obj_uid'], + inp_uid: data[j]['inp_doc_uid'] + }); + } + } } } - }); - - formEditProcess = new PMUI.form.Form({ - id: 'formEditProcess', - fieldset: true, - title: "Process Information".translate(), - width: DEFAULT_WINDOW_WIDTH - DEFAULT_WINDOW_WIDTH * 0.10, - items: [ - processUID, - textTitle, - textDescription, - dropCalendar, - dropProcessCat, - dropDynaform, - dropRouting, - checkDebug, - checkHideCase, - checkSubProcess, - dropCaseCreated, - dropCaseDeleted, - dropCaseCancelled, - dropCasePaused, - dropCaseUnpaused, - dropCaseReassigned, - dropCaseOpen, - dropTypeProcess, - proCost, - proUnitCost - ] - }); - - //Load Dynaforms - loadDynaforms = function (response) { - var i; - dropDynaform.addOption({ - label: "None".translate(), - value: "", - select: false - }); - for (i = 0; i < response.length; i += 1) { - dropDynaform.addOption({ - label: response[i].dyn_title, - value: response[i].dyn_uid, - select: false + if (items.length === 0) { + dataTree.push({ + obj_title: label[i].translate(), + items: [{obj_title: 'N/A'.translate(), obj_uid: ''}] + }); + } else { + dataTree.push({ + obj_title: label[i].translate(), + items: items }); } - }; + } + }; - //Load calendar - loadCalendar = function (response) { - var i; - dropCalendar.addOption({ - label: "None".translate(), - value: "", - select: false - }); - for (i = 0; i < response.length; i += 1) { - dropCalendar.addOption({ - label: response[i].cal_name, - value: response[i].cal_uid, - select: false - }); + loadGridCaseTacker = function (data) { + var dataOrder = new Array(), i, j; + for (i = 0; i < data.length; i += 1) { + for (j = 0; j < data.length; j += 1) { + positionIndex = (data[j]['obj_type'] == 'DYNAFORM') ? data[j].pud_position : data[j].pui_position; + if (positionIndex == (i + 1)) { + dataOrder.push(data[j]); + switch (dataOrder[i]['obj_type']) { + case 'DYNAFORM': + label = dataOrder[i]['dyn_title'].translate(); + break; + case 'INPUT-DOCUMENT': + label = dataOrder[i]['input_doc_title'].translate(); + break; + default: + break; + } + dataOrder[i]['obj_title'] = label; + break; + } } - }; + } + gridPanelObjects.setDataItems(dataOrder); + }; - //Load category - loadCategory = function (response) { - var i; - dropProcessCat.addOption({ - label: "None".translate(), - value: "", - select: false - }); - for (i = 0; i < response.length; i += 1) { - dropProcessCat.addOption({ - label: response[i].cat_name, - value: response[i].cat_uid, - select: false - }); + getValuesAssignmentSteps = function () { + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": "process-supervisor/available-assignmentsteps", + "method": 'GET' + }, + { + "url": "process-supervisor/assignmentsteps", + "method": 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + dataTree = []; + orderDataTree(response[0].response); + treePanelObjects.setDataItems(dataTree); + loadGridCaseTacker(response[1].response); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); } - }; + }); + restClient.executeRestClient(); + }; - //Load Templates - loadTemplate = function (response) { - var i; - dropRouting.addOption({ - label: "None".translate(), - value: "", - select: false - }); - for (i = 0; i < response.length; i += 1) { - if (response[i].prf_filename != "alert_message.html") { - dropRouting.addOption({ - label: response[i].prf_filename, - value: response[i].prf_filename, - select: false - }); - } - } - }; + treePanelObjects = new PMUI.panel.TreePanel({ + id: 'treePanelObjects', + proportion: 0.5, + filterable: true, + filterPlaceholder: 'Text to search'.translate(), + emptyMessage: 'No records found'.translate(), + style: {cssClasses: ['itemsSteps']}, + nodeDefaultSettings: { + behavior: "drag", + labelDataBind: 'obj_title', + itemsDataBind: 'items', + collapsed: false, + childrenDefaultSettings: { + labelDataBind: 'obj_title', + autoBind: true + }, + autoBind: true + } + }); - //Load triggers - loadTriggers = function (response) { - var i; - dropCaseCreated.addOption({ - label: "None".translate(), - value: "", - select: false - }); - dropCaseDeleted.addOption({ - label: "None".translate(), - value: "", - select: false - }); - dropCaseCancelled.addOption({ - label: "None".translate(), - value: "", - select: false - }); - dropCasePaused.addOption({ - label: "None".translate(), - value: "", - select: false - }); - dropCaseUnpaused.addOption({ - label: "None".translate(), - value: "", - select: false - }); - dropCaseReassigned.addOption({ - label: "None".translate(), - value: "", - select: false - }); + //Save Item (Drop) + saveItemDyanformInputDocuments = function (rowStep) { + rowStep = rowStep.getData(); + if (rowStep.obj_type === "DYNAFORM") { + data = { + "dyn_uid": rowStep.obj_uid, + "pud_position": rowStep.obj_position + }; + } else { + data = { + "inp_doc_uid": rowStep.obj_uid, + "pui_position": rowStep.obj_position + }; + } - dropCaseOpen.addOption({ - label: "None".translate(), - value: "", - select: false - }); + restClient = new PMRestClient({ + endpoint: 'process-supervisor/' + rowStep.obj_type.toLowerCase(), + typeRequest: 'post', + data: data, + functionSuccess: function (xhr, response) { + }, + functionFailure: function (xhr, response) { + } + }); + restClient.executeRestClient(); + return data; + }; - for (i = 0; i < response.length; i += 1) { - dropCaseCreated.addOption({ - label: response[i].tri_title, - value: response[i].tri_uid, - select: false - }); - dropCaseDeleted.addOption({ - label: response[i].tri_title, - value: response[i].tri_uid, - select: false - }); - dropCaseCancelled.addOption({ - label: response[i].tri_title, - value: response[i].tri_uid, - select: false - }); - dropCasePaused.addOption({ - label: response[i].tri_title, - value: response[i].tri_uid, - select: false - }); - dropCaseUnpaused.addOption({ - label: response[i].tri_title, - value: response[i].tri_uid, - select: false - }); - dropCaseReassigned.addOption({ - label: response[i].tri_title, - value: response[i].tri_uid, - select: false - }); + //Update SORT tree + updateItem = function (rowStep, i) { + var objType, + baseEndPointType, + baseEndPointID; + rowStep = rowStep.getData(); + rowStep.obj_position = i + 1; + objType = rowStep.obj_type.toLowerCase(), + baseEndPointType = (objType === "dynaform") ? 'dynaforms' : 'input-documents'; + baseEndPointID = (objType === "dynaform") ? rowStep.pud_uid : rowStep.pui_uid; + if (objType === "dynaform") { + rowStep.pud_position = rowStep.obj_position; + } else { + rowStep.pui_position = rowStep.obj_position; + } - dropCaseOpen.addOption({ - label: response[i].tri_title, - value: response[i].tri_uid, - select: false - }); + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": 'process-supervisor/' + objType + "/" + baseEndPointID, + "method": 'PUT', + "data": rowStep + } + ] + }, + functionSuccess: function (xhr, response) { + }, + functionFailure: function (xhr, response) { } - }; + }); + restClient.executeRestClient(); + }; + gridPanelObjects = new PMUI.grid.GridPanel({ + id: 'gridPanelObjects', + proportion: 1.5, + visibleFooter: false, + filterable: false, + style: { + cssClasses: ['itemsSteps'] + }, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + behavior: 'dragdropsort', + columns: [ + { + title: 'Title'.translate(), + dataType: 'string', + width: 330, + alignment: "left", + columnData: "obj_title", + sortable: false, + alignmentCell: 'left' + }, + { + title: 'Type'.translate(), + dataType: 'string', + width: 120, + alignment: "left", + columnData: "obj_type", + sortable: false, + alignmentCell: 'left' + }, + { + id: 'gridPanelObjectsButtonDelete', + title: '', + dataType: 'button', + buttonLabel: '', + buttonStyle: {cssClasses: ['mafe-button-delete-assign']}, + buttonTooltip: 'Remove Object'.translate(), + onButtonClick: function (row, grid) { + var rowStep, treePanelItems; + flagEdit = 1; + index = arrayDynaformInputDocumentID.indexOf(row.getData().obj_uid); + rowStep = row.getData(); + treePanelItems = treePanelObjects.getItems(); - // Load type of process - loadTypeProcess = function (response) { - dropTypeProcess.addOption({ - label: "Public".translate(), - value: "PUBLIC", - select: false - }); - dropTypeProcess.addOption({ - label: "Private".translate(), - value: "PRIVATE", - select: false - }); - }; + if (index > -1) { + arrayObjectRemovedSteps.push(row.getData().obj_uid); + arrayDynaformInputDocumentID.splice(index, 1); + } + function removeRowClass(treeNode) { + var childNodeEl = $(treeNode.html).find('.pmui-gridpanelrow'); + childNodeEl.removeClass('pmui-gridpanelrow'); + } + + function removeEmptyNode(indexNode) { + var parentNode = treePanelItems[indexNode]; + if (parentNode.getItems().length == 1 && + parentNode.getItems()[0].getData()['obj_uid'] == "") { + parentNode.removeItem(0); + } + parentNode.addItem(row); + removeRowClass(parentNode); + } - // Load properties of process - loadProperties = function (response) { - propertiesWindow.addItem(formEditProcess); - propertiesWindow.open(); - formEditProcess.getField("pro_type_process").hideColon(); - formEditProcess.reset(); - responseProperties = response; - processUID.setValue(response.pro_uid); - processUID.setReadOnly(true); - textTitle.setValue(response.pro_title); - textDescription.setValue(response.pro_description); - dropDynaform.setValue(response.pro_summary_dynaform); - dropCaseCancelled.setValue(response.pro_tri_canceled); - dropCaseCreated.setValue(response.pro_tri_create); - dropCaseDeleted.setValue(response.pro_tri_deleted); - dropCasePaused.setValue(response.pro_tri_paused); - dropCaseUnpaused.setValue(response.pro_tri_unpaused); - dropCaseReassigned.setValue(response.pro_tri_reassigned); - dropCaseOpen.setValue(response.pro_tri_open); - dropRouting.setValue(response.pro_derivation_screen_tpl); - dropCalendar.setValue(response.pro_calendar); - dropProcessCat.setValue(response.pro_category); - dropTypeProcess.setValue(response.pro_type_process); - checkHideCase.setHeight(57) - if (response.pro_debug == 1) { - checkDebug.getControls()[0].select(); + if (rowStep.obj_type === "DYNAFORM") { + removeEmptyNode(0); + } else { + removeEmptyNode(1); + } + grid.removeItem(row); + } } - if (response.pro_show_message == 1) { - checkHideCase.getControls()[0].select(); + ], + onDrop: function (grid, item, index) { + var parentItems; + if (item.getData()['obj_uid'] == "") { + return false; + } - if (response.pro_subprocess == 1) { - checkSubProcess.getControls()[0].select(); + parentItems = item.parent.getItems(); + if (parentItems.length == 1 && item.getData()['obj_uid'] != "") { + item.parent.addDataItem( + {obj_title: 'N/A'.translate(), obj_uid: ''} + ); + item.parent.behaviorObject.draggedObject = item; } - proCost.setValue(response.pro_cost); - if (response.pro_unit_cost != null && response.pro_unit_cost != '') { - proUnitCost.setValue(response.pro_unit_cost); + flagEdit = 1; + rowStep = item.getData(); + rowStep.obj_position = index + 1; + item.setData(rowStep); + index = arrayObjectRemovedSteps.indexOf(item.getData().obj_uid); + + if (index > -1) { + arrayDynaformInputDocumentID.push(item.getData().obj_uid); + arrayObjectRemovedSteps.splice(index, 1); } - }; + }, + onSort: function (grid, item, index) { + flagEdit = 1; + rowStep = item.getData(); + rowStep.obj_position = index + 1; + } + }); - getValuesProperties(); + //principal Container Steps + panelContainerObjects = new PMUI.core.Panel({ + id: "panelContainerObjects", + width: DEFAULT_WINDOW_WIDTH, + height: 250, + fieldset: true, + items: [treePanelObjects, gridPanelObjects], + layout: "hbox", + style: { + cssProperties: { + 'margin-top': '-40px' + } + } + }); - propertiesWindow.showFooter(); - propertiesWindow.defineEvents(); - applyStyleWindowForm(propertiesWindow); - formEditProcess.getField('pro_title').setFocus(); - formEditProcess.getField("pro_type_process").html.style.float = "left"; + assigmentWindow.open(); + panelTitleUser.addItem(titleUser); + panelTitleUserList.addItem(titleUserList); + assigmentWindow.body.style.overflowX = "hidden"; - dropCaseCancelled.style.addProperties({"float": "left"}); - dropCasePaused.style.addProperties({"float": "left"}); - dropCaseUnpaused.style.addProperties({"float": "left"}); - dropCaseReassigned.style.addProperties({"float": "left"}); - dropCaseOpen.style.addProperties({"float": "left"}); + panelGridUser.addItem(gridUsers); + panelGridUserList.addItem(gridUserList); - $("#dropCaseCancelled,#dropCasePaused,#dropCaseReassigned,#dropTypeProcess,#dropCaseOpen").find("select:eq(0)").css("z-index", 1); + assigmentPanelGlobal.addItem(assigmentPanelUser); + assigmentPanelGlobal.addItem(assigmentPanelUserList); + assigmentWindow.addItem(assigmentPanelGlobal); - if (window.enterprise === "1") { - proCost.setVisible(true); - proUnitCost.setVisible(true); - } else { - proCost.setVisible(false); - proUnitCost.setVisible(false); - } - }; + assigmentWindow.addItem(panelObjects); + assigmentWindow.addItem(panelContainerObjects); + getValuesAssignmentSteps(); - }() -); -(function () { - PMDesigner.caseTracker = function () { - var caseTrackerForm, - index, - flagEdit = 0, - caseTrackerWindow, - dataCaseTracker, - dataTree, - conditionform, - conditionWindows, - disableAllItems, - formIsDirty, - conditionformIsDirty, - orderDataTree, - saveItem, - updateItem, - treePanelObjects, - loadGridCaseTacker, - editCondition, - gridPanelObjects, - titleTreeObjects, - getValuesCaseTrackerObjects, - updateCaseTrackerPropertiesAndObjects, - loadPropertiesCaseTracker, - titleGridObjects, - panelLabelObjects, - panelContainerObjects, - panelObjects, - applyStylesWindow, - showObjects, - arrayObjectDropAssignedObjects = new Array(), - arrayObjectAvailableObjects = new Array(), - arrayObjectStepsCaseTracker = new Array(); + gridPanelObjects.style.addProperties({overflow: 'auto'}); + gridPanelObjects.style.addProperties({float: 'right'}); + gridPanelObjects.setWidth(630); + gridPanelObjects.setHeight(250); + $('#gridPanelObjects').css("margin-right", "32px"); + $('#treePanelObjects').css("margin-left", "10px"); - disableAllItems = function () { - caseTrackerWindow.getItems()[0].setVisible(false); - caseTrackerWindow.getItems()[1].setVisible(false); - caseTrackerWindow.hideFooter(); - }; - formIsDirty = function () { - if (caseTrackerForm.isDirty() || flagEdit == 1) { - var message_window = new PMUI.ui.MessageWindow({ - id: "cancelMessageTriggers", - windowMessageType: 'warning', - width: 490, - title: "Case Tracker".translate(), - message: 'Are you sure you want to discard your changes?'.translate(), - footerItems: [ - { - text: "No".translate(), - handler: function () { - message_window.close(); + assigmentPanelUser.addItem(panelTitleUser); + assigmentPanelUser.addItem(panelSearchUser); + assigmentPanelUser.addItem(radioUsers); + assigmentPanelUser.addItem(panelGridUser); + + assigmentPanelUserList.addItem(panelTitleUserList); + assigmentPanelUserList.addItem(panelSearchUserList); + assigmentPanelUserList.addItem(radioUsersList); + assigmentPanelUserList.addItem(panelGridUserList); + gridUsers.dom.tableContainer.style.height = "245px"; + gridUserList.dom.tableContainer.style.height = "245px"; + gridUsers.goToPage(0); + gridUserList.goToPage(0); + assigmentWindow.defineEvents(); + applyStyles(); + treePanelObjects.style.addProperties({overflow: 'auto'}); + + applyStylesForToolbar(); + usersgrid = gridUsers; + for (i = 0; i < usersgrid.getItems().length; i += 1) { + arrayObjectUsers2[i] = usersgrid.getItems()[i]; + } + userslist = gridUserList; + for (i = 0; i < userslist.getItems().length; i += 1) { + arrayObjectUserList2[i] = userslist.getItems()[i]; + } + gridpanelobj = gridPanelObjects; + for (i = 0; i < gridpanelobj.getItems().length; i += 1) { + arrayDynaformInputDocumentID[i] = gridpanelobj.getItems()[i].getData().obj_uid; + arrayDynaformInputDocumentObject[i] = gridpanelobj.getItems()[i].getData(); + } + }; +}()); +( + function () { + PMDesigner.propertiesProcess = function () { + var responseProperties = null, + getValuesProperties, + isDirtyFormProcess, + saveProperties, + propertiesWindow, + processUID, + textTitle, + textDescription, + dropCalendar, + dropProcessCat, + dropDynaform, + dropRouting, + checkDebug, + checkHideCase, + checkSubProcess, + dropCaseCreated, + dropCaseDeleted, + dropCaseCancelled, + dropCasePaused, + dropCaseUnpaused, + dropCaseReassigned, + dropCaseOpen, + dropTypeProcess, + proCost, + loadProperties, + proUnitCost, + formEditProcess, + loadDynaforms, + loadCalendar, + loadTemplate, + loadTriggers, + loadTypeProcess, + loadCategory, + clickedClose; + + getValuesProperties = function () { + var restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": "project/" + PMDesigner.project.id + "/dynaforms", + "method": 'GET' + }, + { + "url": "calendars", + "method": 'GET' }, - buttonType: "error" - }, - { - text: "Yes".translate(), - handler: function () { - message_window.close(); - caseTrackerWindow.close(); + { + "url": "project/categories", + "method": 'GET' }, - buttonType: "success" - } - ] - }); - message_window.open(); - message_window.showFooter(); - } else { - caseTrackerWindow.close(); - } - }; - - conditionformIsDirty = function () { - if (conditionform.isDirty()) { - var message_window = new PMUI.ui.MessageWindow({ - id: "cancelMessageTriggers", - windowMessageType: 'warning', - width: 490, - title: "Case Tracker".translate(), - message: 'Are you sure you want to discard your changes?'.translate(), - footerItems: [ - { - text: "No".translate(), - handler: function () { - message_window.close(); + { + "url": "project/" + PMDesigner.project.id + "/file-manager?path=templates", + "method": 'GET' }, - buttonType: "error" - }, - { - text: "Yes".translate(), - handler: function () { - message_window.close(); - conditionWindows.close(); + { + "url": "project/" + PMDesigner.project.id + "/triggers", + "method": 'GET' }, - buttonType: "success" - } - ] - }); - message_window.open(); - message_window.showFooter(); - } else { - conditionWindows.close(); - } - - }; - orderDataTree = function (data) { - var items = []; - var type = ['DYNAFORM', 'INPUT_DOCUMENT', 'OUTPUT_DOCUMENT', 'EXTERNAL_STEP']; - var label = ['Dynaform', 'Input Document', 'OutPut Document', 'External Step']; - for (var i = 0; i < type.length; i += 1) { - items = []; - for (var j = 0; j < data.length; j += 1) { - if (type[i] === data[j].obj_type) { - items.push({ - step_type_obj: label[i].translate(), - obj_label: label[i].translate(), - obj_title: data[j]['obj_title'], - obj_type: data[j]['obj_type'], - obj_uid: data[j]['obj_uid'] - }); + { + "url": "project/" + PMDesigner.project.id + "/process", + "method": 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + loadDynaforms(response[0].response); + loadCalendar(response[1].response); + loadCategory(response[2].response); + loadTemplate(response[3].response); + loadTriggers(response[4].response); + loadTypeProcess(response[5].response); + loadProperties(response[5].response); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); } - } - if (items.length === 0) { - dataTree.push({ - obj_title: label[i].translate(), - items: [] + }); + restClient.setBaseEndPoint(''); + restClient.executeRestClient(); + }; + isDirtyFormProcess = function () { + var message_window + if (formEditProcess.isDirty()) { + message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: "Edit process".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + propertiesWindow.close(); + }, + buttonType: "success" + } + ] }); + message_window.open(); + message_window.showFooter(); } else { - dataTree.push({ - obj_title: label[i].translate(), - items: items - }); + propertiesWindow.close(); } - } - }; + }; + saveProperties = function (data) { + var restClient = new PMRestClient({ + typeRequest: 'update', + data: data, + messageSuccess: "Properties saved successfully".translate(), + functionSuccess: function (xhr, response) { + propertiesWindow.close(); - //Properties - loadPropertiesCaseTracker = function () { - dataCaseTracker = []; - restClient = new PMRestClient({ - endpoint: 'case-tracker/property', - typeRequest: 'get', - functionSuccess: function (xhr, response) { - dataCaseTracker = response; - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } - }); - restClient.executeRestClient(); - }; + PMDesigner.project.setProjectName(data.pro_title); + PMDesigner.project.setDescription(data.pro_description); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); - updateCaseTrackerPropertiesAndObjects = function (data) { - //save steps Objects Case Tracker - var i, j; - index = 0; - for (i = 0; i < gridPanelObjects.getItems().length; i += 1) { - idObject = (typeof gridPanelObjects.getItems()[i].getData().cto_uid_obj != 'undefined') ? gridPanelObjects.getItems()[i].getData().cto_uid_obj : gridPanelObjects.getItems()[i].getData().obj_uid; - index = arrayObjectStepsCaseTracker.indexOf(idObject); - if (index <= -1) { - saveItem(gridPanelObjects.getItems()[i]); - } else { - updateItem(gridPanelObjects.getItems()[i], i); - } - } - ; - for (i = 0; i < arrayObjectAvailableObjects.length; i += 1) { - for (j = 0; j < arrayObjectDropAssignedObjects.length; j += 1) { - index = (arrayObjectAvailableObjects[i] == arrayObjectDropAssignedObjects[j].cto_uid_obj) ? 0 : 1; - if (index == 0) { - restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - "calls": [ - { - "url": 'case-tracker/object/' + arrayObjectDropAssignedObjects[j].cto_uid, - "method": 'DELETE' - } - ] - }, - functionSuccess: function (xhr, response) { - }, - functionFailure: function (xhr, response) { - } - }); - restClient.executeRestClient(); - break; + PMDesigner.project.dirty = false; } - } - } - - //save Properties Case Tracker - data ['map_type'] = data ['map_type'] == '["1"]' ? "PROCESSMAP" : "NONE"; - data ['routing_history'] = data ['routing_history'] == '["1"]' ? 1 : 0; - data ['message_history'] = data ['message_history'] == '["1"]' ? 1 : 0; - restClient = new PMRestClient({ - endpoint: 'case-tracker/property', - typeRequest: 'update', - data: data, - functionSuccess: function (xhr, response) { - caseTrackerWindow.close(); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: "There are problems updating the Case Tracker, please try again.".translate(), - messageSuccess: 'Case Tracker updated successfully'.translate(), - flashContainer: document.body - }); - restClient.executeRestClient(); - }; + }); + restClient.setEndpoint("process"); + restClient.executeRestClient(); + }; - caseTrackerForm = new PMUI.form.Form({ - id: 'caseTrackerForm', - fieldset: true, - title: "", - width: DEFAULT_WINDOW_WIDTH - 70, - height: 30, - layout: "hbox", - items: [ - { - pmType: "annotation", - text: "Display :".translate(), - id: "DisplayMessage", - name: "DisplayMessage" - }, - { - id: 'map_type', - pmType: 'checkbox', - labelVisible: false, - options: [ - { - label: 'Processmap'.translate(), - value: '1' - } - ] + propertiesWindow = new PMUI.ui.Window({ + id: "propertiesProcessWindow", + title: "Edit process".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT, + footerHeight: 'auto', + bodyHeight: "auto", + modal: true, + buttonPanelPosition: "bottom", + footerAlign: "right", + onBeforeClose: function () { + clickClose = true; + isDirtyFormProcess(); }, - { - id: 'routing_history', - pmType: 'checkbox', - labelVisible: false, - options: [ - { - label: 'Routing History'.translate(), - value: '1' + buttons: [ + { + id: 'outputWindowDocButtonCancel', + text: "Cancel".translate(), + buttonType: "error", + handler: function () { + clickedClose = false; + isDirtyFormProcess(); } - ] - }, - { - id: 'message_history', - pmType: 'checkbox', - labelVisible: false, - options: [ - { - id: 'message_history', - label: 'Messages'.translate(), - value: '1' + }, + { + id: 'outputWindowDocButtonSave', + text: "Save".translate(), + buttonType: "success", + handler: function () { + var dataForm; + if (formEditProcess.isValid()) { + if ((navigator.userAgent.indexOf("MSIE") != -1) || (navigator.userAgent.indexOf("Trident") != -1)) { + dataForm = getData2PMUI(formEditProcess.html); + } else { + dataForm = formEditProcess.getData(); + } + dataForm.pro_debug = checkDebug.controls[0].selected ? 1 : 0; + dataForm.pro_show_message = checkHideCase.controls[0].selected ? 1 : 0; + dataForm.pro_subprocess = checkSubProcess.controls[0].selected ? 1 : 0; + functionAssignmentUsers = function (xhr, response) { + }; + saveProperties(dataForm); + } } - ] - } - ], - style: { - cssProperties: { - 'margin-bottom': '70px' - } - } - }); + } + ] + }); - //objects - loadGridCaseTacker = function (data) { - var i; - for (i = 0; i < data.length; i += 1) { - switch (data[i]['cto_type_obj']) { - case 'DYNAFORM': - label = 'Dynaform'.translate(); - break; - case 'INPUT_DOCUMENT': - label = 'Input Document'.translate(); - break; - case 'OUTPUT_DOCUMENT': - label = 'OutPut Document'.translate(); - break; - case 'EXTERNAL_STEP': - label = 'External Step'.translate(); - break; - default: - label = data[i]['tri_type']; - break; - } - data[i]['obj_label'] = label; - } - gridPanelObjects.setDataItems(data); - }; + processUID = new PMUI.field.TextField({ + label: "UID".translate(), + id: "process_uid", + name: "pro_uid", + labelWidth: "35%", + controlsWidth: "300px" + }); - getValuesCaseTrackerObjects = function () { - restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - "calls": [ - { - "url": "case-tracker/available-objects", - "method": 'GET' - }, - { - "url": "case-tracker/objects", - "method": 'GET' - } - ] - }, - functionSuccess: function (xhr, response) { - dataTree = []; - orderDataTree(response[0].response); - treePanelObjects.setDataItems(dataTree); - loadGridCaseTacker(response[1].response); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - } + textTitle = new PMUI.field.TextField({ + label: "Title".translate(), + id: 'textTitle', + name: 'pro_title', + labelWidth: "35%", + placeholder: 'a text here'.translate(), + controlsWidth: "300px", + required: true }); - restClient.executeRestClient(); - }; - saveItem = function (rowStep) { - rowStep = rowStep.getData(); - data = { - "cto_type_obj": rowStep.obj_type, - "cto_uid_obj": rowStep.obj_uid, - "cto_condition": (typeof rowStep.cto_condition != 'undefined') ? rowStep.cto_condition : '', - "cto_position": rowStep.cto_position - }; - restClient = new PMRestClient({ - endpoint: 'case-tracker/object', - typeRequest: 'post', - data: data, - functionSuccess: function (xhr, response) { - data = response; - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - }, - messageError: "There are problems saved, please try again.".translate() + + textDescription = new PMUI.field.TextAreaField({ + id: 'textDescription', + name: 'pro_description', + label: "Description".translate(), + labelWidth: "35%", + controlsWidth: "500px", + rows: 150, + style: {cssClasses: ['mafe-textarea-resize']} }); - restClient.executeRestClient(); - return data; - }; - updateItem = function (rowStep, i) { - rowStep = rowStep.getData(); - rowStep.cto_position = i + 1; - restClient = new PMRestClient({ - typeRequest: 'post', - multipart: true, - data: { - "calls": [ - { - "url": 'case-tracker/object/' + rowStep.cto_uid, - "method": 'PUT', - "data": rowStep - } - ] - }, - functionSuccess: function (xhr, response) { - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); + dropCalendar = new PMUI.field.DropDownListField({ + id: "dropCalendar", + name: "pro_calendar", + labelWidth: "35%", + label: "Calendar".translate(), + controlsWidth: "300px", + valueType: 'string', + onChange: function (newValue, prevValue) { } }); - restClient.executeRestClient(); - }; - - treePanelObjects = new PMUI.panel.TreePanel({ - id: 'treePanelObjects', - proportion: 0.5, - filterable: true, - filterPlaceholder: 'Search ...'.translate(), - emptyMessage: 'No records found'.translate(), - style: {cssClasses: ['itemsSteps']}, - nodeDefaultSettings: { - behavior: "drag", - labelDataBind: 'obj_title', - itemsDataBind: 'items', - collapsed: false, - childrenDefaultSettings: { - labelDataBind: 'obj_title', - autoBind: true - }, - autoBind: true - } - }); - editCondition = function () { - var visible, dataEdit; + dropProcessCat = new PMUI.field.DropDownListField({ + id: "dropProcessCat", + name: "pro_category", + controlsWidth: "300px", + labelWidth: "35%", + label: "Process Category".translate(), + valueType: 'string', + onChange: function (newValue, prevValue) { + } + }); - conditionform = new PMUI.form.Form({ - id: 'conditionform', - title: "", - fieldset: true, - visibleHeader: false, - width: 500, - items: [ - new CriteriaField({ - id: 'cto_condition', - pmType: 'textarea', - name: 'cto_condition', - valueType: 'string', - label: 'Condition'.translate(), - placeholder: 'Insert a condition'.translate(), - rows: 200, - width: 250, - controlsWidth: 285, - renderType: 'textarea' - }) - ] + dropDynaform = new PMUI.field.DropDownListField({ + id: "dropDynaform", + name: "pro_summary_dynaform", + controlsWidth: "300px", + labelWidth: "35%", + label: "Dynaform to show a case summary".translate(), + valueType: 'string', + onChange: function (newValue, prevValue) { + } }); - if (rowStep != '' && rowStep != undefined) { - dataEdit = conditionform.getFields(); - dataEdit[0].setValue(rowStep['cto_condition']); - } + dropRouting = new PMUI.field.DropDownListField({ + id: "dropRouting", + name: "pro_derivation_screen_tpl", + controlsWidth: "300px", + labelWidth: "35%", + label: "Routing Screen Template".translate(), + valueType: 'string', + onChange: function (newValue, prevValue) { + } + }); - conditionWindows = new PMUI.ui.Window({ - id: 'conditionWindows', - title: 'Condition'.translate(), - width: 500, - height: 'auto', - footerHeight: 'auto', - bodyHeight: 'auto', - modal: true, - buttonPanelPosition: 'bottom', - footerAlign: "right", - onBeforeClose: conditionformIsDirty, - buttons: [ - { - id: 'conditionObjectWindowButtonClose', - text: "Cancel".translate(), - handler: conditionformIsDirty, - buttonType: 'error' - }, + checkDebug = new PMUI.field.CheckBoxGroupField({ + id: 'checkDebug', + labelWidth: "35%", + label: "Debug".translate(), + name: "pro_debug", + value: '1', + controlPositioning: 'vertical', + options: [ { - id: 'conditionObjectWindowButtonSave', - text: "Save".translate(), - handler: function () { - var i, item; - if (conditionform.isValid()) { - idrowStep = (typeof rowStep.cto_uid_obj != 'undefined') ? rowStep.cto_uid_obj : rowStep.obj_uid; - for (i = 0; i < gridPanelObjects.getItems().length; i += 1) { - item = gridPanelObjects.getItems()[i].getData(); - idObj = (typeof item.cto_uid_obj != 'undefined') ? item.cto_uid_obj : item.obj_uid; - if (idObj == idrowStep) { - rowStep.cto_condition = conditionform.getData()['cto_condition']; - gridPanelObjects.getItems()[i].setData(rowStep); - break; - } - } - conditionWindows.close(); - } - }, - buttonType: 'success' + id: 'pro_debug', + disabled: false, + value: '1', + selected: false } - ] + ], + onChange: function (newVal, oldVal) { + } }); - conditionWindows.addItem(conditionform); - conditionWindows.open(); - conditionWindows.showFooter(); - applyStyleWindowForm(conditionWindows); - conditionWindows.defineEvents(); - conditionWindows.footer.html.style.textAlign = 'right'; - conditionform.setFocus(); - style = $('#cto_condition .pmui-field-label').attr("style"); - style = style + ' float: left;'; - $('#cto_condition .pmui-field-label').attr("style", style); - }; - gridPanelObjects = new PMUI.grid.GridPanel({ - id: 'gridPanelObjects', - proportion: 1.5, - visibleFooter: false, - filterable: false, - width: '640px', - style: {cssClasses: ['itemsSteps']}, - filterPlaceholder: 'Search ...'.translate(), - emptyMessage: 'No records found'.translate(), - nextLabel: 'Next'.translate(), - previousLabel: 'Previous'.translate(), - customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { - return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); - }, - behavior: 'dragdropsort', - columns: [ - { - title: 'Title'.translate(), - dataType: 'string', - width: 330, - alignment: "left", - columnData: "obj_title", - sortable: false, - alignmentCell: 'left' - }, - { - title: 'Type'.translate(), - dataType: 'string', - width: 120, - alignment: "left", - columnData: "obj_label", - sortable: false, - alignmentCell: 'left' - }, - { - id: 'gridPanelObjectsButtonProperties', - title: '', - dataType: 'button', - buttonLabel: "Condition".translate(), - iconPosition: "center", - buttonStyle: {cssClasses: ['mafe-button-editstep']}, - buttonTooltip: 'Edit Properties'.translate(), - onButtonClick: function (row, grid) { - rowStep = row.getData(); - editCondition(); + checkHideCase = new PMUI.field.CheckBoxGroupField({ + id: 'checkHideCase', + labelWidth: "35%", + label: "Hide the case number and the case title in the steps".translate(), + value: '1', + name: "pro_show_message", + controlPositioning: 'vertical', + options: [ + { + disabled: false, + value: '1', + selected: false } - }, - { - id: 'gridPanelObjectsButtonDelete', - title: '', - dataType: 'button', - buttonLabel: '', - buttonStyle: {cssClasses: ['mafe-button-delete-assign']}, - buttonTooltip: 'Remove Object'.translate(), - onButtonClick: function (row, grid) { - flagEdit = 1; - rowStep = row.getData(); - index = (row.getData().cto_uid_obj != 'undefined') ? arrayObjectStepsCaseTracker.indexOf(row.getData().cto_uid_obj) : arrayObjectStepsCaseTracker.indexOf(row.getData().obj_uid); - if (index > -1) { - arrayObjectAvailableObjects.push(row.getData().cto_uid_obj); - arrayObjectStepsCaseTracker.splice(index, 1); - } - objType = (typeof row.getData().cto_type_obj != 'undefined') ? row.getData().cto_type_obj : row.getData().obj_type; - grid.removeItem(row); - switch (objType) { - case 'DYNAFORM': - treePanelObjects.getItems()[0].addItem(row); - break; - case 'INPUT_DOCUMENT': - treePanelObjects.getItems()[1].addItem(row); - break; - case 'OUTPUT_DOCUMENT': - treePanelObjects.getItems()[2].addItem(row); - break; - case 'EXTERNAL_STEP': - treePanelObjects.getItems()[3].addItem(row); - break; - default: - break; - } + ], + onChange: function (newVal, oldVal) { + } + }); + + checkSubProcess = new PMUI.field.CheckBoxGroupField({ + id: 'checkSubProcess', + labelWidth: "35%", + label: "This a sub-process".translate(), + value: '1', + name: "pro_subprocess", + controlPositioning: 'vertical', + options: [ + { + disabled: false, + value: '1', + selected: false } + ], + onChange: function (newVal, oldVal) { } - ], - onDrop: function (grid, item, index) { - flagEdit = 1; - if (item.data.customKeys.obj_uid === '') { - return false; + }); + dropCaseCreated = new PMUI.field.DropDownListField({ + id: "dropCaseCreated", + name: "pro_tri_create", + labelWidth: "35%", + label: "Execute a trigger when a case is created".translate(), + valueType: 'string', + controlsWidth: "300px", + onChange: function (newValue, prevValue) { + } + }); + + dropCaseDeleted = new PMUI.field.DropDownListField({ + id: "dropCaseDeleted", + name: "pro_tri_deleted", + labelWidth: "35%", + label: "Execute a trigger when a case is deleted".translate(), + valueType: 'string', + controlsWidth: "300px", + onChange: function (newValue, prevValue) { + } + }); + + dropCaseCancelled = new PMUI.field.DropDownListField({ + id: "dropCaseCancelled", + name: "pro_tri_canceled", + labelWidth: "35%", + label: "Execute a trigger when a case is cancelled".translate(), + valueType: 'string', + controlsWidth: "300px", + onChange: function (newValue, prevValue) { + } + }); + + dropCasePaused = new PMUI.field.DropDownListField({ + id: "dropCasePaused", + name: "pro_tri_paused", + labelWidth: "35%", + label: "Execute a trigger when a case is paused".translate(), + valueType: 'string', + controlsWidth: "300px", + onChange: function (newValue, prevValue) { + } + }); + + dropCaseUnpaused = new PMUI.field.DropDownListField({ + id: "dropCaseUnpaused", + name: "pro_tri_unpaused", + labelWidth: "35%", + label: "Execute a trigger when a case is unpaused".translate(), + valueType: "string", + controlsWidth: "300px" + }); + + dropCaseReassigned = new PMUI.field.DropDownListField({ + id: "dropCaseReassigned", + name: "pro_tri_reassigned", + labelWidth: "35%", + label: "Execute a trigger when a case is reassigned".translate(), + valueType: 'string', + controlsWidth: "300px", + onChange: function (newValue, prevValue) { } - rowStep = item.getData(); - rowStep.cto_position = index + 1; - item.setData(rowStep); + }); - index = (typeof item.getData().cto_uid_obj != 'undefined') ? arrayObjectAvailableObjects.indexOf(item.getData().cto_uid_obj) : arrayObjectAvailableObjects.indexOf(item.getData().obj_uid); + dropCaseOpen = new PMUI.field.DropDownListField({ + id: "dropCaseOpen", + name: "pro_tri_open", + label: "Execute a trigger when a case is opened".translate(), + labelWidth: "35%", + valueType: "string", + controlsWidth: "300px", - if (index > -1) { - itemPush = (typeof item.getData().cto_uid_obj != 'undefined') ? item.getData().cto_uid_obj : item.getData().obj_uid; - arrayObjectStepsCaseTracker.push(itemPush); - arrayObjectAvailableObjects.splice(index, 1); + onChange: function (newValue, prevValue) { } - }, - onSort: function (grid, item, index) { - rowStep = item.getData(); - } - }); - - titleTreeObjects = new PMUI.ui.TextLabel({ - id: "titleTreeObjects", - textMode: 'plain', - text: 'Available Objects'.translate(), - style: { - cssClasses: [ - 'mafe-designer-steps-tree' - ] - } - }); - - titleGridObjects = new PMUI.ui.TextLabel({ - id: "titleGridObjects", - textMode: 'plain', - text: 'Assigned objects'.translate(), - style: { - cssClasses: [ - 'mafe-designer-stesp-grid' - ] - } - }); + }); - panelLabelObjects = new PMUI.core.Panel({ - width: DEFAULT_WINDOW_WIDTH * 0.94, - fieldset: true, - items: [ - titleTreeObjects, - titleGridObjects - ], - style: { - cssProperties: { - 'margin-bottom': 4, - 'margin-top': 4, - 'margin-left': 4 + dropTypeProcess = new PMUI.field.DropDownListField({ + id: "dropTypeProcess", + name: "pro_type_process", + labelWidth: "35%", + label: "Process Design Access: Public / Private (Owner)".translate(), + valueType: 'string', + controlsWidth: "300px", + onChange: function (newValue, prevValue) { } - }, - layout: "hbox" - }); - - panelContainerObjects = new PMUI.core.Panel({ - width: DEFAULT_WINDOW_WIDTH * 0.94, - height: 320, - fieldset: true, - items: [ - treePanelObjects, - gridPanelObjects - ], - layout: "hbox" - }); - - panelObjects = new PMUI.core.Panel({ - width: DEFAULT_WINDOW_WIDTH * 0.94, - height: DEFAULT_WINDOW_HEIGHT * 0.70, - fieldset: true, - items: [ - panelLabelObjects, - panelContainerObjects - ], - layout: "vbox" - }); + }); - caseTrackerWindow = new PMUI.ui.Window({ - id: 'caseTrackerWindow', - title: "Case Tracker".translate(), - width: DEFAULT_WINDOW_WIDTH, - height: DEFAULT_WINDOW_HEIGHT, - footerHeight: 'auto', - bodyHeight: 'auto', - modal: true, - buttonPanelPosition: "bottom", - onBeforeClose: formIsDirty, - visibleFooter: false, - footerAling: "right", - footerItems: [{ - id: 'btnCloseCaseTracker', - text: 'Cancel'.translate(), - buttonType: "error", - handler: formIsDirty - }, - { - id: 'btnSaveCaseTracker', - text: "Save".translate(), - buttonType: "success", - handler: function () { - if (caseTrackerForm.isValid()) { - data = caseTrackerForm.getData(); - updateCaseTrackerPropertiesAndObjects(data); - } + proCost = new PMUI.field.TextField({ + id: 'proCost', + name: 'pro_cost', + labelWidth: "35%", + value: 0, + placeholder: 'a cost here'.translate(), + label: "Cost".translate(), + valueType: 'integer', + controlsWidth: "300px", + required: window.enterprise === "1" ? true : false, + style: { + cssProperties: { + float: "left" } } - ], - spaceButtons: 30 - }); - - caseTrackerWindow.addItem(caseTrackerForm); - caseTrackerWindow.addItem(panelObjects); - caseTrackerWindow.open(); - caseTrackerWindow.showFooter(); - applyStyleWindowForm(caseTrackerWindow); - caseTrackerWindow.defineEvents(); - caseTrackerWindow.footer.html.style.textAlign = 'right'; - caseTrackerForm.setFocus(); - - applyStylesWindow = function () { - $('#gridPanelObjects .pmui-gridpanel-tableContainer').css({'height': 'auto'}); - $('#caseTrackerForm :eq(2)').css({'padding': '0px 10px 0px 10px'}); - $('#caseTrackerForm :eq(0)').remove(); - items = caseTrackerWindow.getItems()[0].getItems(); - $(items[1].getHTML()).find('table').css('border', 'none'); - $(items[2].getHTML()).find('table').css('border', 'none'); - $(items[3].getHTML()).find('table').css('border', 'none'); - }; + }); - showObjects = function () { - disableAllItems(); + proUnitCost = new PMUI.field.TextField({ + id: 'proUnitCost', + name: 'pro_unit_cost', + labelWidth: "35%", + value: '$', + placeholder: 'a unit cost here'.translate(), + controlsWidth: "300px", + label: "Units".translate(), + valueType: 'string', + required: window.enterprise === "1" ? true : false, + style: { + cssProperties: { + float: "left" + } + } + }); - loadPropertiesCaseTracker(); - caseTrackerWindow.getItems()[0].setVisible(true); - caseTrackerWindow.showFooter(); - caseTrackerWindow.setTitle("Case Tracker Properties".translate()); + formEditProcess = new PMUI.form.Form({ + id: 'formEditProcess', + fieldset: true, + title: "Process Information".translate(), + width: DEFAULT_WINDOW_WIDTH - DEFAULT_WINDOW_WIDTH * 0.10, + items: [ + processUID, + textTitle, + textDescription, + dropCalendar, + dropProcessCat, + dropDynaform, + dropRouting, + checkDebug, + checkHideCase, + checkSubProcess, + dropCaseCreated, + dropCaseDeleted, + dropCaseCancelled, + dropCasePaused, + dropCaseUnpaused, + dropCaseReassigned, + dropCaseOpen, + dropTypeProcess, + proCost, + proUnitCost + ] + }); - if (dataCaseTracker != '') { - var dataEdit = caseTrackerForm.getFields(); - dataEdit[1].setValue((dataCaseTracker['map_type'] == 'PROCESSMAP') ? '["1"]' : '[]'); - dataEdit[2].setValue((dataCaseTracker['routing_history'] == 1) ? '["1"]' : '[]'); - dataEdit[3].setValue((dataCaseTracker['message_history'] == 1) ? '["1"]' : '[]'); - } + //Load Dynaforms + loadDynaforms = function (response) { + var i; + dropDynaform.addOption({ + label: "None".translate(), + value: "", + select: false + }); + for (i = 0; i < response.length; i += 1) { + dropDynaform.addOption({ + label: response[i].dyn_title, + value: response[i].dyn_uid, + select: false + }); + } + }; + //Load calendar + loadCalendar = function (response) { + var i; + dropCalendar.addOption({ + label: "None".translate(), + value: "", + select: false + }); + for (i = 0; i < response.length; i += 1) { + dropCalendar.addOption({ + label: response[i].cal_name, + value: response[i].cal_uid, + select: false + }); + } + }; - getValuesCaseTrackerObjects(); - caseTrackerWindow.getItems()[1].setVisible(true); - caseTrackerWindow.setTitle("Case Tracker".translate()); + //Load category + loadCategory = function (response) { + var i; + dropProcessCat.addOption({ + label: "None".translate(), + value: "", + select: false + }); + for (i = 0; i < response.length; i += 1) { + dropProcessCat.addOption({ + label: response[i].cat_name, + value: response[i].cat_uid, + select: false + }); + } + }; - caseTrackerWindow.body.style.overflow = 'initial'; + //Load Templates + loadTemplate = function (response) { + var i; + dropRouting.addOption({ + label: "None".translate(), + value: "", + select: false + }); + for (i = 0; i < response.length; i += 1) { + if (response[i].prf_filename != "alert_message.html") { + dropRouting.addOption({ + label: response[i].prf_filename, + value: response[i].prf_filename, + select: false + }); + } + } + }; - gridPanelObjects.style.addProperties({overflow: 'auto'}); - gridPanelObjects.style.addProperties({float: 'right'}); - gridPanelObjects.setWidth(640); - gridPanelObjects.setHeight(270); - applyStylesWindow(); - treePanelObjects.style.addProperties({float: 'left'}); - treePanelObjects.style.addProperties({overflow: 'auto'}); - treePanelObjects.setWidth(200); - treePanelObjects.setHeight(270); + //Load triggers + loadTriggers = function (response) { + var i; + dropCaseCreated.addOption({ + label: "None".translate(), + value: "", + select: false + }); + dropCaseDeleted.addOption({ + label: "None".translate(), + value: "", + select: false + }); + dropCaseCancelled.addOption({ + label: "None".translate(), + value: "", + select: false + }); + dropCasePaused.addOption({ + label: "None".translate(), + value: "", + select: false + }); + dropCaseUnpaused.addOption({ + label: "None".translate(), + value: "", + select: false + }); + dropCaseReassigned.addOption({ + label: "None".translate(), + value: "", + select: false + }); - applyStyleTreePanel(treePanelObjects); + dropCaseOpen.addOption({ + label: "None".translate(), + value: "", + select: false + }); - panelLabelObjects.setHeight(15); - caseTrackerWindow.defineEvents(); + for (i = 0; i < response.length; i += 1) { + dropCaseCreated.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + dropCaseDeleted.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + dropCaseCancelled.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + dropCasePaused.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + dropCaseUnpaused.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + dropCaseReassigned.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); - caseTrackerWindow.setBodyPadding(5); + dropCaseOpen.addOption({ + label: response[i].tri_title, + value: response[i].tri_uid, + select: false + }); + } + }; - panelObjects.style.addProperties({marginLeft: '15px'}); - for (var i = 0; i < gridPanelObjects.getItems().length; i += 1) { - arrayObjectStepsCaseTracker[i] = gridPanelObjects.getItems()[i].getData().cto_uid_obj; - arrayObjectDropAssignedObjects[i] = gridPanelObjects.getItems()[i].getData(); - } - }; - showObjects(); - }; + // Load type of process + loadTypeProcess = function (response) { + dropTypeProcess.addOption({ + label: "Public".translate(), + value: "PUBLIC", + select: false + }); + dropTypeProcess.addOption({ + label: "Private".translate(), + value: "PRIVATE", + select: false + }); + }; - PMDesigner.caseTracker.showObjects = function () { - PMDesigner.caseTracker(); - }; + // Load properties of process + loadProperties = function (response) { + propertiesWindow.addItem(formEditProcess); + propertiesWindow.open(); + formEditProcess.getField("pro_type_process").hideColon(); + formEditProcess.reset(); + responseProperties = response; + processUID.setValue(response.pro_uid); + processUID.setReadOnly(true); + textTitle.setValue(response.pro_title); + textDescription.setValue(response.pro_description); + dropDynaform.setValue(response.pro_summary_dynaform); + dropCaseCancelled.setValue(response.pro_tri_canceled); + dropCaseCreated.setValue(response.pro_tri_create); + dropCaseDeleted.setValue(response.pro_tri_deleted); + dropCasePaused.setValue(response.pro_tri_paused); + dropCaseUnpaused.setValue(response.pro_tri_unpaused); + dropCaseReassigned.setValue(response.pro_tri_reassigned); + dropCaseOpen.setValue(response.pro_tri_open); + dropRouting.setValue(response.pro_derivation_screen_tpl); + dropCalendar.setValue(response.pro_calendar); + dropProcessCat.setValue(response.pro_category); + dropTypeProcess.setValue(response.pro_type_process); + checkHideCase.setHeight(57) + if (response.pro_debug == 1) { + checkDebug.getControls()[0].select(); + } + if (response.pro_show_message == 1) { + checkHideCase.getControls()[0].select(); + } + if (response.pro_subprocess == 1) { + checkSubProcess.getControls()[0].select(); + } + proCost.setValue(response.pro_cost); + if (response.pro_unit_cost != null && response.pro_unit_cost != '') { + proUnitCost.setValue(response.pro_unit_cost); + } + }; -}()); -PMDesigner.gatewayProperties = function (gateway) { - if (gateway.getGatewayType() !== "PARALLEL") { - PMDesigner.RoutingRule(gateway); - } -}; + getValuesProperties(); -PMDesigner.RoutingRule = function (shape) { - var formRoutingRule, - formPanelSelected, - arrayShapeIdRemoved = [], - buttonAdd, - windowConnections, - warningMessageWindowDelete, - warningMessageWindowDirty, - containerLabels, - deleteButton, - buttonSave, - buttonCancel, - labelNextTask, - labelCondition, - typeShapeValueText, - dataRouteGroup = [], - arrayElementName = [], - availableShapes = []; + propertiesWindow.showFooter(); + propertiesWindow.defineEvents(); + applyStyleWindowForm(propertiesWindow); + formEditProcess.getField('pro_title').setFocus(); + formEditProcess.getField("pro_type_process").html.style.float = "left"; - warningMessageWindowDelete = new PMUI.ui.MessageWindow({ - id: 'warningMessageWindowDelete', - windowMessageType: 'warning', - width: 490, - bodyHeight: 'auto', - title: 'Routing Rule'.translate(), - message: 'Do you want to delete this routing rule?'.translate(), - footerItems: [ - { - id: 'warningMessageWindowDeleteButtonNo', - text: 'No'.translate(), - visible: true, - handler: function () { - warningMessageWindowDelete.close(); - }, - buttonType: "error" - }, - { - id: 'warningMessageWindowDeleteButtonYes', - text: 'Yes'.translate(), - visible: true, - handler: function () { - deleteRow(); - warningMessageWindowDelete.close(); - }, - buttonType: "success" - } - ] - }); - warningMessageWindowDirty = new PMUI.ui.MessageWindow({ - id: 'warningMessageWindowDirty', - windowMessageType: 'warning', - width: 490, - bodyHeight: 'auto', - title: 'Routing Rule'.translate(), - message: 'Are you sure you want to discard your changes?'.translate(), - footerItems: [ - { - id: 'warningMessageWindowDirtyButtonNo', - text: 'No'.translate(), - visible: true, - handler: function () { - warningMessageWindowDirty.close(); - }, - buttonType: "error" - }, { - id: 'warningMessageWindowDirtyButtonYes', - text: 'Yes'.translate(), - visible: true, - handler: function () { - warningMessageWindowDirty.close(); - windowConnections.close(); - }, - buttonType: "success" - } - ] - }); + dropCaseCancelled.style.addProperties({"float": "left"}); + dropCasePaused.style.addProperties({"float": "left"}); + dropCaseUnpaused.style.addProperties({"float": "left"}); + dropCaseReassigned.style.addProperties({"float": "left"}); + dropCaseOpen.style.addProperties({"float": "left"}); - buttonAdd = new PMUI.ui.Button({ - id: 'routingRuleButtonAdd', - text: 'Add Routing Rule'.translate(), - style: { - cssProperties: { - marginLeft: '50px', - marginTop: '10px', - marginBottom: '10px', - padding: "5px" - } - }, - buttonType: 'success', - handler: function () { - // to add a new row - addRow(); - enableSorting(); - } - }); - buttonSave = new PMUI.ui.Button({ - id: 'windowConnectionsButtonSave', - text: 'Save'.translate(), - handler: function () { - //validate routing rules form - if (isValidRoutingRules()) { - //remove all flows an get points - var allPoints = removeConnectionsIntoCanvas(); - saveConnections(allPoints); - } + $("#dropCaseCancelled,#dropCasePaused,#dropCaseReassigned,#dropTypeProcess,#dropCaseOpen").find("select:eq(0)").css("z-index", 1); - }, - buttonType: 'success' - }); - buttonCancel = new PMUI.ui.Button({ - id: 'windowConnectionsButtonCancel', - text: 'Cancel'.translate(), - buttonType: 'error', - handler: function () { - if (formRoutingRule.isDirty()) { - warningMessageWindowDirty.open(); - warningMessageWindowDirty.showFooter(); + if (window.enterprise === "1") { + proCost.setVisible(true); + proUnitCost.setVisible(true); } else { - windowConnections.close(); + proCost.setVisible(false); + proUnitCost.setVisible(false); } - } - }); - - labelNextTask = new PMUI.ui.TextLabel({ - text: 'Next Task'.translate() - }); - labelNextTask.setWidth(382); - labelNextTask.style.addProperties({padding: '5px 0px 0px 50px'}); + }; - labelCondition = new PMUI.ui.TextLabel({ - text: 'Condition'.translate() - }); - labelCondition.setWidth(410); - labelCondition.style.addProperties({padding: '5px 0px 0px 5px'}); - labelCondition.style.addProperties({marginLeft: '31%'}); + }() +); +(function () { + PMDesigner.caseTracker = function () { + var caseTrackerForm, + index, + flagEdit = 0, + caseTrackerWindow, + dataCaseTracker, + dataTree, + conditionform, + conditionWindows, + disableAllItems, + formIsDirty, + conditionformIsDirty, + orderDataTree, + saveItem, + updateItem, + treePanelObjects, + loadGridCaseTacker, + editCondition, + gridPanelObjects, + titleTreeObjects, + getValuesCaseTrackerObjects, + updateCaseTrackerPropertiesAndObjects, + loadPropertiesCaseTracker, + titleGridObjects, + panelLabelObjects, + panelContainerObjects, + panelObjects, + applyStylesWindow, + showObjects, + arrayObjectDropAssignedObjects = new Array(), + arrayObjectAvailableObjects = new Array(), + arrayObjectStepsCaseTracker = new Array(); - containerLabels = new PMUI.core.Panel({ - layout: 'hbox', - width: 'auto', - height: 29, - style: { - cssProperties: { - 'border-bottom': '1px solid #c0c0c0' + disableAllItems = function () { + caseTrackerWindow.getItems()[0].setVisible(false); + caseTrackerWindow.getItems()[1].setVisible(false); + caseTrackerWindow.hideFooter(); + }; + formIsDirty = function () { + if (caseTrackerForm.isDirty() || flagEdit == 1) { + var message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: "Case Tracker".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + caseTrackerWindow.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + caseTrackerWindow.close(); } - } - }); - containerLabels.addItem(labelNextTask); - containerLabels.addItem(labelCondition); - containerLabels.style.addProperties({'border-bottom': '1px solid #e7e7e7'}); + }; - formRoutingRule = new PMUI.form.Form({ - id: 'formRoutingRule', - visibleHeader: false, - width: DEFAULT_WINDOW_WIDTH - 60, - height: 'auto', - items: [], - style: { - cssProperties: { - 'margin-left': '35px' + conditionformIsDirty = function () { + if (conditionform.isDirty()) { + var message_window = new PMUI.ui.MessageWindow({ + id: "cancelMessageTriggers", + windowMessageType: 'warning', + width: 490, + title: "Case Tracker".translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + text: "No".translate(), + handler: function () { + message_window.close(); + }, + buttonType: "error" + }, + { + text: "Yes".translate(), + handler: function () { + message_window.close(); + conditionWindows.close(); + }, + buttonType: "success" + } + ] + }); + message_window.open(); + message_window.showFooter(); + } else { + conditionWindows.close(); } - } - }); - formRoutingRule.hideFooter(); - - windowConnections = new PMUI.ui.Window({ - id: 'windowConnections', - title: 'Routing Rule'.translate(), - height: DEFAULT_WINDOW_HEIGHT, - width: DEFAULT_WINDOW_WIDTH, - footerAlign: 'right', - buttonPanelPosition: 'bottom', - items: [ - buttonAdd - ], - buttons: [ - buttonCancel, - buttonSave - ] - }); - - typeShapeValueText = (shape.gat_type === 'EXCLUSIVE') ? 'EXCLUSIVE'.translate() : 'INCLUSIVE'.translate(); - windowConnections.setTitle('Routing Rule'.translate() + ' - ' + typeShapeValueText); - windowConnections.showFooter(); - windowConnections.addItem(containerLabels); - if (formRoutingRule.dirty === null) { - formRoutingRule.dirty = false; - } - windowConnections.addItem(formRoutingRule); - windowConnections.open(); - loadConnections(); - enableSorting(); - /** - * add a new row - * @returns {PMUI.form.FormPanel|*} - */ - function addRow() { - var dropDownControl, - criteriaField, - deleteButton, - newRow, - max, - i; - newRow = new PMUI.form.FormPanel({ - layout: 'hbox' - }); + }; + orderDataTree = function (data) { + var items = []; + var type = ['DYNAFORM', 'INPUT_DOCUMENT', 'OUTPUT_DOCUMENT', 'EXTERNAL_STEP']; + var label = ['Dynaform', 'Input Document', 'OutPut Document', 'External Step']; + for (var i = 0; i < type.length; i += 1) { + items = []; + for (var j = 0; j < data.length; j += 1) { + if (type[i] === data[j].obj_type) { + items.push({ + step_type_obj: label[i].translate(), + obj_label: label[i].translate(), + obj_title: data[j]['obj_title'], + obj_type: data[j]['obj_type'], + obj_uid: data[j]['obj_uid'] + }); + } + } + if (items.length === 0) { + dataTree.push({ + obj_title: label[i].translate(), + items: [] + }); + } else { + dataTree.push({ + obj_title: label[i].translate(), + items: items + }); + } + } + }; - dropDownControl = new PMUI.field.DropDownListField({ - id: 'dropdownNextTask', - name: 'act_name', - valueType: 'string', - label: 'Next Task'.translate(), - labelPosition: 'top', - labelVisible: false, - value: '', - readOnly: false, - controlsWidth: 360, - proportion: 0.9, - style: { - cssProperties: { - 'vertical-align': 'top' + //Properties + loadPropertiesCaseTracker = function () { + dataCaseTracker = []; + restClient = new PMRestClient({ + endpoint: 'case-tracker/property', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + dataCaseTracker = response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); } - } - }); + }); + restClient.executeRestClient(); + }; - criteriaField = new CriteriaField({ - id: 'textCondition', - pmType: 'text', - renderType: 'textarea', - name: 'flo_condition', - valueType: 'string', - label: 'Condition'.translate(), - labelPosition: 'top', - labelVisible: false, - controlsWidth: 345, - required: false, - style: { - cssProperties: { - 'vertical-align': 'top' + updateCaseTrackerPropertiesAndObjects = function (data) { + //save steps Objects Case Tracker + var i, j; + index = 0; + for (i = 0; i < gridPanelObjects.getItems().length; i += 1) { + idObject = (typeof gridPanelObjects.getItems()[i].getData().cto_uid_obj != 'undefined') ? gridPanelObjects.getItems()[i].getData().cto_uid_obj : gridPanelObjects.getItems()[i].getData().obj_uid; + index = arrayObjectStepsCaseTracker.indexOf(idObject); + if (index <= -1) { + saveItem(gridPanelObjects.getItems()[i]); + } else { + updateItem(gridPanelObjects.getItems()[i], i); } } - }); - deleteButton = new PMUI.field.ButtonField({ - id: 'buttonDelete', - value: 'Delete'.translate(), - handler: function (e, a) { - formPanelSelected = this.getParent(); - warningMessageWindowDelete.open(); - warningMessageWindowDelete.dom.titleContainer.style.height = '17px'; - warningMessageWindowDelete.showFooter(); - enableSorting(); - }, - name: 'delete', - labelVisible: false, - buttonAling: 'left', - controlsWidth: 60, - proportion: 0.1, - style: { - cssProperties: { - 'vertical-align': 'top' + ; + for (i = 0; i < arrayObjectAvailableObjects.length; i += 1) { + for (j = 0; j < arrayObjectDropAssignedObjects.length; j += 1) { + index = (arrayObjectAvailableObjects[i] == arrayObjectDropAssignedObjects[j].cto_uid_obj) ? 0 : 1; + if (index == 0) { + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": 'case-tracker/object/' + arrayObjectDropAssignedObjects[j].cto_uid, + "method": 'DELETE' + } + ] + }, + functionSuccess: function (xhr, response) { + }, + functionFailure: function (xhr, response) { + } + }); + restClient.executeRestClient(); + break; + } } } - }); - newRow.addItem(dropDownControl); - newRow.addItem(criteriaField); - newRow.addItem(deleteButton); - loadOptions(dropDownControl); - //apply styles; - if (availableShapes && availableShapes.length > 0) { - deleteButton.controls[0].button.setButtonType('error'); - $(deleteButton.getHTML()).find("a").css({ - padding: "5px" + //save Properties Case Tracker + data ['map_type'] = data ['map_type'] == '["1"]' ? "PROCESSMAP" : "NONE"; + data ['routing_history'] = data ['routing_history'] == '["1"]' ? 1 : 0; + data ['message_history'] = data ['message_history'] == '["1"]' ? 1 : 0; + restClient = new PMRestClient({ + endpoint: 'case-tracker/property', + typeRequest: 'update', + data: data, + functionSuccess: function (xhr, response) { + caseTrackerWindow.close(); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems updating the Case Tracker, please try again.".translate(), + messageSuccess: 'Case Tracker updated successfully'.translate(), + flashContainer: document.body }); - formRoutingRule.addItem(newRow); - for (i = 0, max = formRoutingRule.getItems().length; i < max; i += 1) { - formRoutingRule.getItems()[i].style.addProperties({'padding': 'initial'}); - } - dropDownControl.dom.labelTextContainer.style.display = 'none'; - criteriaField.dom.labelTextContainer.style.display = 'none'; - criteriaField.setValue(true); - } else { - PMDesigner.msgFlash('There are no items.'.translate(), windowConnections.footer, 'error'); - } - return newRow; - } - - function loadOptions(dropdown) { - var i, - customShapes, - element, - nameGroup, - evnLabelMap; - //Important! Any changes to synchronize the assessment of the condition - //of the functions: countActivities and loadActivities - dropdown.clearOptions(); - dropdown.setUID = function (uid) { - this.uid = uid; - }; - dropdown.getUID = function () { - return this.uid; + restClient.executeRestClient(); }; - dropdown.addOptionGroup({ - label: 'Task'.translate(), - selected: true, - options: [] - }); - dropdown.addOptionGroup({ - label: 'Sub-process'.translate(), - options: [] - }); - dropdown.addOptionGroup({ - label: 'Event'.translate(), - options: [] - }); - dropdown.addOptionGroup({ - label: 'Gateway'.translate(), - options: [] - }); - customShapes = PMUI.getActiveCanvas().getCustomShapes(); - - for (i = 0; i < customShapes.getSize(); i += 1) { - element = customShapes.get(i); - // verify pool and participant - if (element.getType() !== 'PMParticipant' && element.getType() !== 'PMPool') { - //itself verify and same parent - if (shape.getID() !== element.getID() - && element.businessObject - && shape.businessObject - && shape.businessObject.elem.$parent - && element.businessObject.elem.$parent - && element.businessObject.elem.$parent.id === shape.businessObject.elem.$parent.id) { - switch (element.type) { - case 'PMActivity': - nameGroup = element.act_type === 'TASK' ? 'Task'.translate() : 'Sub-process'.translate(); - dropdown.addOption({ - value: element.act_uid, - label: element.act_name - }, nameGroup); - arrayElementName[element.act_uid] = element.act_name; - availableShapes.push(element); - break; - case 'PMEvent': - evnLabelMap = { - 'END': 'End Event'.translate(), - 'INTERMEDIATE': 'Intermediate Event'.translate() - }; - if (element.evn_type !== 'START') { - dropdown.addOption({ - value: element.evn_uid, - label: element.evn_name || evnLabelMap[element.evn_type] - }, 'Event'.translate()); + caseTrackerForm = new PMUI.form.Form({ + id: 'caseTrackerForm', + fieldset: true, + title: "", + width: DEFAULT_WINDOW_WIDTH - 70, + height: 30, + layout: "hbox", + items: [ + { + pmType: "annotation", + text: "Display :".translate(), + id: "DisplayMessage", + name: "DisplayMessage" + }, + { + id: 'map_type', + pmType: 'checkbox', + labelVisible: false, + options: [ + { + label: 'Processmap'.translate(), + value: '1' + } + ] + }, + { + id: 'routing_history', + pmType: 'checkbox', + labelVisible: false, + options: [ + { + label: 'Routing History'.translate(), + value: '1' + } + ] + }, + { + id: 'message_history', + pmType: 'checkbox', + labelVisible: false, + options: [ + { + id: 'message_history', + label: 'Messages'.translate(), + value: '1' + } + ] + } + ], + style: { + cssProperties: { + 'margin-bottom': '70px' + } + } + }); - arrayElementName[element.evn_uid] = element.evn_name || evnLabelMap[element.evn_type]; - availableShapes.push(element); - } - break; - case 'PMGateway': - dropdown.addOption({ - value: element.gat_uid, - label: element.gat_name || 'Gateway'.translate() - }, 'Gateway'); - arrayElementName[element.gat_uid] = element.gat_name || 'Gateway'.translate(); - availableShapes.push(element); - break; - } + //objects + loadGridCaseTacker = function (data) { + var i; + for (i = 0; i < data.length; i += 1) { + switch (data[i]['cto_type_obj']) { + case 'DYNAFORM': + label = 'Dynaform'.translate(); + break; + case 'INPUT_DOCUMENT': + label = 'Input Document'.translate(); + break; + case 'OUTPUT_DOCUMENT': + label = 'OutPut Document'.translate(); + break; + case 'EXTERNAL_STEP': + label = 'External Step'.translate(); + break; + default: + label = data[i]['tri_type']; + break; } + data[i]['obj_label'] = label; } - } - } + gridPanelObjects.setDataItems(data); + }; - function removeConnectionsIntoCanvas() { - var shapeDest, connection, dt, allPoints = {}, i, j; - for (j = 0; j < arrayShapeIdRemoved.length; j += 1) { - shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', arrayShapeIdRemoved[j]); - dt = shape.getPorts().asArray(); - for (i = 0; i < dt.length; i += 1) { - connection = dt[i].getConnection(); - if (shape.getID() === connection.getSrcPort().getParent().getID() && - shapeDest.getID() === connection.getDestPort().getParent().getID()) { - //caching points - allPoints[shapeDest.getID()] = getPoints(connection); - removeConnection(connection); + getValuesCaseTrackerObjects = function () { + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": "case-tracker/available-objects", + "method": 'GET' + }, + { + "url": "case-tracker/objects", + "method": 'GET' + } + ] + }, + functionSuccess: function (xhr, response) { + dataTree = []; + orderDataTree(response[0].response); + treePanelObjects.setDataItems(dataTree); + loadGridCaseTacker(response[1].response); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + } + }); + restClient.executeRestClient(); + }; + saveItem = function (rowStep) { + rowStep = rowStep.getData(); + data = { + "cto_type_obj": rowStep.obj_type, + "cto_uid_obj": rowStep.obj_uid, + "cto_condition": (typeof rowStep.cto_condition != 'undefined') ? rowStep.cto_condition : '', + "cto_position": rowStep.cto_position + }; + restClient = new PMRestClient({ + endpoint: 'case-tracker/object', + typeRequest: 'post', + data: data, + functionSuccess: function (xhr, response) { + data = response; + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + }, + messageError: "There are problems saved, please try again.".translate() + }); + restClient.executeRestClient(); + return data; + }; - break; + updateItem = function (rowStep, i) { + rowStep = rowStep.getData(); + rowStep.cto_position = i + 1; + restClient = new PMRestClient({ + typeRequest: 'post', + multipart: true, + data: { + "calls": [ + { + "url": 'case-tracker/object/' + rowStep.cto_uid, + "method": 'PUT', + "data": rowStep + } + ] + }, + functionSuccess: function (xhr, response) { + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); } - } - } - arrayShapeIdRemoved = []; - return allPoints; - } - - /** - * to remove a individual connection and getting points - * @param connection - */ - function removeConnection(connection) { - - PMUI.getActiveCanvas().emptyCurrentSelection(); - PMUI.getActiveCanvas().setCurrentConnection(connection); - PMUI.getActiveCanvas().removeElements(); - connection.saveAndDestroy(); - PMUI.getActiveCanvas().removeConnection(connection); - } - - /** - * gets conenctions inital and final points - * @param connection - */ - function getPoints(connection) { - var result = []; - result[0] = connection.points[0]; - result[1] = connection.points[connection.points.length - 1]; - return result; - } - - - function editAllConnections(connArray) { - var i, - elem, - canvas = PMUI.getActiveCanvas(); - for(i = 0; i < connArray.length; i += 1) { - elem = connArray[i]; - if (elem && elem.connection) { - elem.oldShapeDest.removePort(elem.connection.destPort); - elem.shapeDest.addPort(elem.connection.destPort, 100, 100, - false, elem.connection.srcPort); + }); + restClient.executeRestClient(); + }; - elem.connection.lineSegments.clear(); - canvas.commandStack.add(new PMUI.command.CommandConnect(elem.connection)); - elem.connection.connect(); - canvas.triggerPortChangeEvent(elem.connection.destPort); + treePanelObjects = new PMUI.panel.TreePanel({ + id: 'treePanelObjects', + proportion: 0.5, + filterable: true, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + style: {cssClasses: ['itemsSteps']}, + nodeDefaultSettings: { + behavior: "drag", + labelDataBind: 'obj_title', + itemsDataBind: 'items', + collapsed: false, + childrenDefaultSettings: { + labelDataBind: 'obj_title', + autoBind: true + }, + autoBind: true } - } - } - - - function createEndShape() { - var customShape, canvas = PMUI.getActiveCanvas(), command, x, y; - customShape = canvas.shapeFactory('END'); - - x = shape.getX() + shape.getWidth(); - y = shape.getY() + shape.getHeight() + 20; - - canvas.addElement(customShape, x, y, - customShape.topLeftOnCreation); - - //since it is a new element in the designer, we triggered the - //custom on create element event - canvas.updatedElement = customShape; + }); - // create the command for this new shape - command = new PMUI.command.CommandCreate(customShape); - canvas.commandStack.add(command); - command.execute(); - return customShape; - } + editCondition = function () { + var visible, dataEdit; - /** - * new method to validate routing rules - * @returns {boolean} - */ - function isValidRoutingRules() { - var result = true, - arrayAux = [], - i, - max, - id, - dt = formRoutingRule.getItems(); - if (!formRoutingRule.isValid()) { - result = false; - return; - } + conditionform = new PMUI.form.Form({ + id: 'conditionform', + title: "", + fieldset: true, + visibleHeader: false, + width: 500, + items: [ + new CriteriaField({ + id: 'cto_condition', + pmType: 'textarea', + name: 'cto_condition', + valueType: 'string', + label: 'Condition'.translate(), + placeholder: 'Insert a condition'.translate(), + rows: 200, + width: 250, + controlsWidth: 285, + renderType: 'textarea' + }) + ] + }); - for (i = 0, max = dt.length; i < max; i += 1) { - id = dt[i].getField("act_name").getValue(); - if (typeof(arrayAux[id]) === "undefined") { - arrayAux[id] = "1"; - } else { - result = false; - PMDesigner.msgWinError("The routing rule to \"{0}\" already exists".translate([arrayElementName[id]])); - return; + if (rowStep != '' && rowStep != undefined) { + dataEdit = conditionform.getFields(); + dataEdit[0].setValue(rowStep['cto_condition']); } - } - return result; - } - - function saveConnections(allPoints) { - var dt = formRoutingRule.getItems(), - id, - i, - oldId, - shapeDest, - oldShapeDest, - connection, - newConnection, - dataRouteAll, - dataRoute, - restClient, - newPoints, - conectionsArray = []; - - - for (i = 0; i < dt.length; i += 1) { - id = dt[i].getField('act_name').getValue(); - oldId = dt[i].getField('act_name').getUID(); - if (id !== '0') { - dataRouteGroup.push(id); - if (dt[i].getField('flo_condition').getValue() == "") { - dt[i].getField('flo_condition').setValue(true); - } - if (oldId === undefined) { - shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', id); - //getting current connection - - newPoints = allPoints[id]; - newConnection = createConnection(shape, shapeDest, newPoints); - newConnection.setFlowCondition(dt[i].getField('flo_condition').getValue()); - } - if (oldId !== undefined && id === oldId) { - shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', id); - connection = isConnection(shape, shapeDest); + conditionWindows = new PMUI.ui.Window({ + id: 'conditionWindows', + title: 'Condition'.translate(), + width: 500, + height: 'auto', + footerHeight: 'auto', + bodyHeight: 'auto', + modal: true, + buttonPanelPosition: 'bottom', + footerAlign: "right", + onBeforeClose: conditionformIsDirty, + buttons: [ + { + id: 'conditionObjectWindowButtonClose', + text: "Cancel".translate(), + handler: conditionformIsDirty, + buttonType: 'error' + }, + { + id: 'conditionObjectWindowButtonSave', + text: "Save".translate(), + handler: function () { + var i, item; + if (conditionform.isValid()) { + idrowStep = (typeof rowStep.cto_uid_obj != 'undefined') ? rowStep.cto_uid_obj : rowStep.obj_uid; + for (i = 0; i < gridPanelObjects.getItems().length; i += 1) { + item = gridPanelObjects.getItems()[i].getData(); + idObj = (typeof item.cto_uid_obj != 'undefined') ? item.cto_uid_obj : item.obj_uid; + if (idObj == idrowStep) { + rowStep.cto_condition = conditionform.getData()['cto_condition']; + gridPanelObjects.getItems()[i].setData(rowStep); + break; + } + } + conditionWindows.close(); + } + }, + buttonType: 'success' + } + ] + }); + conditionWindows.addItem(conditionform); + conditionWindows.open(); + conditionWindows.showFooter(); + applyStyleWindowForm(conditionWindows); + conditionWindows.defineEvents(); + conditionWindows.footer.html.style.textAlign = 'right'; + conditionform.setFocus(); + style = $('#cto_condition .pmui-field-label').attr("style"); + style = style + ' float: left;'; + $('#cto_condition .pmui-field-label').attr("style", style); + }; - if (typeof(connection) != "object") { - connection = createConnection(shape, shapeDest); + gridPanelObjects = new PMUI.grid.GridPanel({ + id: 'gridPanelObjects', + proportion: 1.5, + visibleFooter: false, + filterable: false, + width: '640px', + style: {cssClasses: ['itemsSteps']}, + filterPlaceholder: 'Search ...'.translate(), + emptyMessage: 'No records found'.translate(), + nextLabel: 'Next'.translate(), + previousLabel: 'Previous'.translate(), + customStatusBar: function (currentPage, pageSize, numberItems, criteria, filter) { + return messagePageGrid(currentPage, pageSize, numberItems, criteria, filter); + }, + behavior: 'dragdropsort', + columns: [ + { + title: 'Title'.translate(), + dataType: 'string', + width: 330, + alignment: "left", + columnData: "obj_title", + sortable: false, + alignmentCell: 'left' + }, + { + title: 'Type'.translate(), + dataType: 'string', + width: 120, + alignment: "left", + columnData: "obj_label", + sortable: false, + alignmentCell: 'left' + }, + { + id: 'gridPanelObjectsButtonProperties', + title: '', + dataType: 'button', + buttonLabel: "Condition".translate(), + iconPosition: "center", + buttonStyle: {cssClasses: ['mafe-button-editstep']}, + buttonTooltip: 'Edit Properties'.translate(), + onButtonClick: function (row, grid) { + rowStep = row.getData(); + editCondition(); + } + }, + { + id: 'gridPanelObjectsButtonDelete', + title: '', + dataType: 'button', + buttonLabel: '', + buttonStyle: {cssClasses: ['mafe-button-delete-assign']}, + buttonTooltip: 'Remove Object'.translate(), + onButtonClick: function (row, grid) { + flagEdit = 1; + rowStep = row.getData(); + index = (row.getData().cto_uid_obj != 'undefined') ? arrayObjectStepsCaseTracker.indexOf(row.getData().cto_uid_obj) : arrayObjectStepsCaseTracker.indexOf(row.getData().obj_uid); + if (index > -1) { + arrayObjectAvailableObjects.push(row.getData().cto_uid_obj); + arrayObjectStepsCaseTracker.splice(index, 1); + } + objType = (typeof row.getData().cto_type_obj != 'undefined') ? row.getData().cto_type_obj : row.getData().obj_type; + grid.removeItem(row); + switch (objType) { + case 'DYNAFORM': + treePanelObjects.getItems()[0].addItem(row); + break; + case 'INPUT_DOCUMENT': + treePanelObjects.getItems()[1].addItem(row); + break; + case 'OUTPUT_DOCUMENT': + treePanelObjects.getItems()[2].addItem(row); + break; + case 'EXTERNAL_STEP': + treePanelObjects.getItems()[3].addItem(row); + break; + default: + break; + } } - - connection.setFlowCondition(dt[i].getField('flo_condition').getValue()); } - if (oldId !== undefined && id !== oldId) { - shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', id); - oldShapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', oldId); - connection = isConnection(shape, oldShapeDest); - - if (typeof(connection) != "object") { - connection = createConnection(shape, shapeDest); - } - - connection.setFlowCondition(dt[i].getField('flo_condition').getValue()); - - if (typeof(connection) != "object") { - connection = createConnection(shape, shapeDest); - } + ], + onDrop: function (grid, item, index) { + flagEdit = 1; + if (item.data.customKeys.obj_uid === '') { + return false; + } + rowStep = item.getData(); + rowStep.cto_position = index + 1; + item.setData(rowStep); - connection.setFlowCondition(dt[i].getField('flo_condition').getValue()); + index = (typeof item.getData().cto_uid_obj != 'undefined') ? arrayObjectAvailableObjects.indexOf(item.getData().cto_uid_obj) : arrayObjectAvailableObjects.indexOf(item.getData().obj_uid); - conectionsArray.push({ - "connection" : isConnection(shape, oldShapeDest) || null, - "shapeDest": shapeDest, - "oldShapeDest": oldShapeDest - }); + if (index > -1) { + itemPush = (typeof item.getData().cto_uid_obj != 'undefined') ? item.getData().cto_uid_obj : item.getData().obj_uid; + arrayObjectStepsCaseTracker.push(itemPush); + arrayObjectAvailableObjects.splice(index, 1); } - } else { - var customShape = createEndShape(); - createConnection(shape, customShape); - } - } - editAllConnections(conectionsArray); - - /*update routing order*/ - dataRouteAll = []; - for (i = 0; i < dataRouteGroup.length; i += 1) { - dataRoute = { - 'rou_case': parseInt(i) + 1, - 'rou_next_task': dataRouteGroup[i], - 'pro_uid': PMDesigner.project.id - }; - dataRouteAll.push(dataRoute); - } - restClient = new PMRestClient({ - endpoint: 'update-route-order', - typeRequest: 'update', - data: dataRouteAll, - functionSuccess: function () { - PMDesigner.msgFlash('Saved correctly'.translate(), document.body, 'success', 3000, 5); }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - PMDesigner.msgFlash('There are problems updating the routing rule, please try again.'.translate(), document.body, 'error', 3000, 5); + onSort: function (grid, item, index) { + rowStep = item.getData(); } }); - restClient.executeRestClient(); - /*end update routing order*/ - - windowConnections.close(); - PMDesigner.msgFlash('Saved correctly'.translate(), document.body); - PMDesigner.project.dirty = true; - PMDesigner.project.setDirty(true); - } - function createConnection(sourceShape, shape, points) { - var sourcePort, endPort, connection, canvas = PMUI.getActiveCanvas(), points; - sourcePort = new PMUI.draw.Port({ - width: 10, - height: 10 + titleTreeObjects = new PMUI.ui.TextLabel({ + id: "titleTreeObjects", + textMode: 'plain', + text: 'Available Objects'.translate(), + style: { + cssClasses: [ + 'mafe-designer-steps-tree' + ] + } }); - endPort = new PMUI.draw.Port({ - width: 10, - height: 10 + + titleGridObjects = new PMUI.ui.TextLabel({ + id: "titleGridObjects", + textMode: 'plain', + text: 'Assigned objects'.translate(), + style: { + cssClasses: [ + 'mafe-designer-stesp-grid' + ] + } }); - if (!points) { - points = findBestPorts(sourceShape, shape); - } - sourceShape.addPort(sourcePort, points[0].x - sourceShape.getZoomX(), points[0].y - sourceShape.getZoomY()); - shape.addPort(endPort, points[1].x - shape.getZoomX(), points[1].y - shape.getZoomY(), false, sourcePort); - //add ports to the canvas array for regularShapes - //shape.canvas.regularShapes.insert(sourcePort).insert(endPort); - //create the connection - connection = new PMFlow({ - srcPort: sourcePort, - destPort: endPort, - segmentColor: new PMUI.util.Color(0, 0, 0), - name: '', - canvas: shape.canvas, - segmentStyle: shape.connectionType.segmentStyle, - flo_type: shape.connectionType.type + panelLabelObjects = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH * 0.94, + fieldset: true, + items: [ + titleTreeObjects, + titleGridObjects + ], + style: { + cssProperties: { + 'margin-bottom': 4, + 'margin-top': 4, + 'margin-left': 4 + } + }, + layout: "hbox" }); - connection.setSrcDecorator(new PMUI.draw.ConnectionDecorator({ - width: 11, - height: 11, - canvas: canvas, - decoratorPrefix: (typeof shape.connectionType.srcDecorator !== 'undefined' - && shape.connectionType.srcDecorator !== null) ? - shape.connectionType.srcDecorator : 'mafe-sequence', - decoratorType: 'source', - parent: connection - })); - connection.setDestDecorator(new PMUI.draw.ConnectionDecorator({ - width: 11, - height: 11, - canvas: canvas, - decoratorPrefix: (typeof shape.connectionType.destDecorator !== 'undefined' - && shape.connectionType.destDecorator !== null) ? - shape.connectionType.destDecorator : 'mafe-sequence', - decoratorType: 'target', - parent: connection - })); - connection.canvas.commandStack.add(new PMUI.command.CommandConnect(connection)); - //connect the two ports - connection.connect(); - connection.setSegmentMoveHandlers(); + panelContainerObjects = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH * 0.94, + height: 320, + fieldset: true, + items: [ + treePanelObjects, + gridPanelObjects + ], + layout: "hbox" + }); - //add the connection to the canvas, that means insert its html to - // the DOM and adding it to the connections array - canvas.addConnection(connection); + panelObjects = new PMUI.core.Panel({ + width: DEFAULT_WINDOW_WIDTH * 0.94, + height: DEFAULT_WINDOW_HEIGHT * 0.70, + fieldset: true, + items: [ + panelLabelObjects, + panelContainerObjects + ], + layout: "vbox" + }); - // Filling PMFlow fields - connection.setTargetShape(endPort.parent); - connection.setOriginShape(sourcePort.parent); - connection.savePoints(); + caseTrackerWindow = new PMUI.ui.Window({ + id: 'caseTrackerWindow', + title: "Case Tracker".translate(), + width: DEFAULT_WINDOW_WIDTH, + height: DEFAULT_WINDOW_HEIGHT, + footerHeight: 'auto', + bodyHeight: 'auto', + modal: true, + buttonPanelPosition: "bottom", + onBeforeClose: formIsDirty, + visibleFooter: false, + footerAling: "right", + footerItems: [{ + id: 'btnCloseCaseTracker', + text: 'Cancel'.translate(), + buttonType: "error", + handler: formIsDirty + }, + { + id: 'btnSaveCaseTracker', + text: "Save".translate(), + buttonType: "success", + handler: function () { + if (caseTrackerForm.isValid()) { + data = caseTrackerForm.getData(); + updateCaseTrackerPropertiesAndObjects(data); + } + } + } + ], + spaceButtons: 30 + }); - // now that the connection was drawn try to create the intersections - connection.checkAndCreateIntersectionsWithAll(); + caseTrackerWindow.addItem(caseTrackerForm); + caseTrackerWindow.addItem(panelObjects); + caseTrackerWindow.open(); + caseTrackerWindow.showFooter(); + applyStyleWindowForm(caseTrackerWindow); + caseTrackerWindow.defineEvents(); + caseTrackerWindow.footer.html.style.textAlign = 'right'; + caseTrackerForm.setFocus(); - //attaching port listeners - sourcePort.attachListeners(sourcePort); - endPort.attachListeners(endPort); + applyStylesWindow = function () { + $('#gridPanelObjects .pmui-gridpanel-tableContainer').css({'height': 'auto'}); + $('#caseTrackerForm :eq(2)').css({'padding': '0px 10px 0px 10px'}); + $('#caseTrackerForm :eq(0)').remove(); + items = caseTrackerWindow.getItems()[0].getItems(); + $(items[1].getHTML()).find('table').css('border', 'none'); + $(items[2].getHTML()).find('table').css('border', 'none'); + $(items[3].getHTML()).find('table').css('border', 'none'); + }; - // finally trigger createEvent - canvas.triggerCreateEvent(connection, []); - connection.flo_state = connection.points; - return connection; - } + showObjects = function () { + disableAllItems(); - function findBestPorts(sourceShape, shape) { - var result = [], i, j, - distance = 99999999, - initPoint, - secondPoint, - midPoints = getMiddlePoints(sourceShape), - midPoints2 = getMiddlePoints(shape); - for (i = 0; i < midPoints.length; i += 1) { - initPoint = midPoints[i]; - for (j = 0; j < midPoints2.length; j += 1) { - secondPoint = midPoints2[j]; - if (distance > initPoint.getManhattanDistance(secondPoint)) { - distance = initPoint.getManhattanDistance(midPoints2[j]); - result[0] = (initPoint); - result[1] = (midPoints2[j]); - } - } - } - return result; - } + loadPropertiesCaseTracker(); + caseTrackerWindow.getItems()[0].setVisible(true); + caseTrackerWindow.showFooter(); + caseTrackerWindow.setTitle("Case Tracker Properties".translate()); - function getMiddlePoints(shape) { - return [ - new PMUI.util.Point(Math.round(shape.zoomWidth / 2) + shape.getZoomX(), 0 + shape.getZoomY()), // TOP - new PMUI.util.Point(shape.zoomWidth + shape.getZoomX(), Math.round(shape.zoomHeight / 2) + shape.getZoomY()), // RIGHT - new PMUI.util.Point(Math.round(shape.zoomWidth / 2) + shape.getZoomX(), shape.zoomHeight + shape.getZoomY()), // BOTTOM - new PMUI.util.Point(0 + shape.getZoomX(), Math.round(shape.zoomHeight / 2) + shape.getZoomY()) // LEFT - ]; - } + if (dataCaseTracker != '') { + var dataEdit = caseTrackerForm.getFields(); + dataEdit[1].setValue((dataCaseTracker['map_type'] == 'PROCESSMAP') ? '["1"]' : '[]'); + dataEdit[2].setValue((dataCaseTracker['routing_history'] == 1) ? '["1"]' : '[]'); + dataEdit[3].setValue((dataCaseTracker['message_history'] == 1) ? '["1"]' : '[]'); + } - function loadConnections() { - var row, connection, dt = shape.getPorts().asArray(), - i, j; - for (i = 0; i < dt.length; i += 1) { - connection = dt[i].getConnection(); - if (shape.getID() !== connection.getDestPort().getParent().getID() && shape.gat_default_flow !== connection.flo_uid) { - row = addRow(); - row.getField('act_name').setValue(connection.getDestPort().getParent().getID()); - row.getField('act_name').setUID(connection.getDestPort().getParent().getID()); - row.getField('flo_condition').setValue(connection.getFlowCondition()); - row.getItems()[2].style.addProperties({display: 'none'}); - row.getItems()[2].controls[0].button.setButtonType('error'); - $(row.getItems()[2].getHTML()).find("a").css({ - padding: "5px" - }); - formRoutingRule.addItem(row); - for (j = 0; j < formRoutingRule.getItems().length; j += 1) { - formRoutingRule.getItems()[j].style.addProperties({'padding': 'initial'}); - } - row.getItems()[0].dom.labelTextContainer.style.display = 'none'; - row.getItems()[1].dom.labelTextContainer.style.display = 'none'; - } - } - } + getValuesCaseTrackerObjects(); + caseTrackerWindow.getItems()[1].setVisible(true); + caseTrackerWindow.setTitle("Case Tracker".translate()); - function isConnection(sourceShape, shape) { - var connection, - i, - dt = sourceShape.getPorts().asArray(); - for (i = 0; i < dt.length; i += 1) { - connection = dt[i].getConnection(); - if (sourceShape.getID() === connection.getSrcPort().getParent().getID() && - shape.getID() === connection.getDestPort().getParent().getID()) { - return connection; - } - } - return false; - } + caseTrackerWindow.body.style.overflow = 'initial'; - function deleteRow() { - arrayShapeIdRemoved.push(formPanelSelected.getField('act_name').getValue()); - formRoutingRule.removeItem(formPanelSelected); - PMDesigner.msgFlash('Routing rule removed correctly'.translate(), windowConnections.footer); - } + gridPanelObjects.style.addProperties({overflow: 'auto'}); + gridPanelObjects.style.addProperties({float: 'right'}); + gridPanelObjects.setWidth(640); + gridPanelObjects.setHeight(270); + applyStylesWindow(); + treePanelObjects.style.addProperties({float: 'left'}); + treePanelObjects.style.addProperties({overflow: 'auto'}); + treePanelObjects.setWidth(200); + treePanelObjects.setHeight(270); - function enableSorting() { - var index = 0, - div = $(formRoutingRule.getHTML()).find(">div:nth-child(2)").css({"overflow": "initial"}); - div.sortable({ - items: '>div', - placeholder: 'steps-placeholder', - cursor: "move", - change: function (event, ui) { - index = ui.placeholder.index(); - }, - start: function (event, ui) { - }, - stop: function (event, ui) { - var dt = [], - row, - formPanelSelected, - id, - i, - j, - shapeDest, - connection; + applyStyleTreePanel(treePanelObjects); - ui.item.parent().find(">div").each(function (i, e) { - dt.push(PMUI.getPMUIObject(e)); - }); - for (i = 0; i < dt.length; i += 1) { - formPanelSelected = dt[i]; - arrayShapeIdRemoved.push(formPanelSelected.getField('act_name').getValue()); - formRoutingRule.removeItem(formPanelSelected); - } - for (i = 0; i < dt.length; i += 1) { - row = addRow(); - row.getItems()[2].style.addProperties({display: 'none'}); - row.getItems()[2].controls[0].button.setButtonType('error'); - $(row.getItems()[2].getHTML()).find("a").css({ - padding: "5px" - }); - formRoutingRule.addItem(row); - for (j = 0; j < formRoutingRule.getItems().length; j += 1) { - formRoutingRule.getItems()[j].style.addProperties({'padding': 'initial'}); - } - row.getItems()[0].dom.labelTextContainer.style.display = 'none'; - row.getItems()[1].dom.labelTextContainer.style.display = 'none'; - row.getField('act_name').setValue(dt[i].getField('act_name').getValue()); - row.getField('flo_condition').setValue(dt[i].getField('flo_condition').getValue()); - id = dt[i].getField('act_name').getValue(); - shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', id); - connection = isConnection(shape, shapeDest); - } - enableSorting(); - } - }); - } -}; + panelLabelObjects.setHeight(15); + caseTrackerWindow.defineEvents(); -PMDesigner.RoutingRuleDeleteAllFlow = function (shape) { - var warningMessageWindowDelete = new PMUI.ui.MessageWindow({ - windowMessageType: 'warning', - width: 490, - bodyHeight: 'auto', - title: 'Routing Rule'.translate(), - id: 'warningMessageWindowDelete', - message: 'Do you want to delete all routing rules?'.translate(), - footerItems: [ - { - id: 'warningMessageWindowDeleteButtonNo', - text: 'No'.translate(), - visible: true, - handler: function () { - warningMessageWindowDelete.close(); - }, - buttonType: "error" - }, { - id: 'warningMessageWindowDeleteButtonYes', - text: 'Yes'.translate(), - visible: true, - handler: function () { - deleteAllConnection(); - warningMessageWindowDelete.close(); - }, - buttonType: "success" - } - ] - }); + caseTrackerWindow.setBodyPadding(5); - function deleteAllConnection() { - var connection, elements = [], - i, - sw, - msg, - ports; - PMUI.getActiveCanvas().emptyCurrentSelection(); - //IMPORTANT: You must empty elements in another array due to the array reference indices managed. - //referer: PMDesigner.canvas.removeConnection & element.getPorts().asArray() - - ports = shape.getPorts().asArray(); - for (i = 0; i < ports.length; i += 1) { - elements.push(ports[i]); - } - sw = false; - for (i = 0; i < elements.length; i += 1) { - connection = elements[i].getConnection(); - if (shape.getID() !== connection.getDestPort().getParent().getID()) { - PMUI.getActiveCanvas().setCurrentConnection(connection); - PMUI.getActiveCanvas().removeElements(); - connection.saveAndDestroy(); - PMUI.getActiveCanvas().removeConnection(connection); - sw = true; + panelObjects.style.addProperties({marginLeft: '15px'}); + for (var i = 0; i < gridPanelObjects.getItems().length; i += 1) { + arrayObjectStepsCaseTracker[i] = gridPanelObjects.getItems()[i].getData().cto_uid_obj; + arrayObjectDropAssignedObjects[i] = gridPanelObjects.getItems()[i].getData(); } - } - msg = sw ? 'Routing rules deleted successfully' : 'There aren\'t routing rules'; - PMDesigner.msgFlash(msg.translate(), document.body); - } + }; + showObjects(); + }; - warningMessageWindowDelete.open(); - warningMessageWindowDelete.showFooter(); - warningMessageWindowDelete.dom.titleContainer.style.height = '17px'; -}; + PMDesigner.caseTracker.showObjects = function () { + PMDesigner.caseTracker(); + }; -PMDesigner.RoutingRuleSetOrder = function (diagram) { - var restClient = new PMRestClient({ - endpoint: 'update-route-order-from-project', - typeRequest: 'update', - data: {}, - functionSuccess: function () { - PMDesigner.msgFlash('Saved correctly'.translate(), document.body, 'success', 3000, 5); - } - }); - restClient.executeRestClient(); +}()); +PMDesigner.gatewayProperties = function (gateway) { + if (gateway.getGatewayType() !== "PARALLEL") { + PMDesigner.RoutingRule(gateway); + } +}; + +PMDesigner.RoutingRule = function (shape) { + var formRoutingRule, + formPanelSelected, + arrayShapeIdRemoved = [], + buttonAdd, + windowConnections, + warningMessageWindowDelete, + warningMessageWindowDirty, + containerLabels, + deleteButton, + buttonSave, + buttonCancel, + labelNextTask, + labelCondition, + typeShapeValueText, + dataRouteGroup = [], + arrayElementName = [], + availableShapes = []; + + warningMessageWindowDelete = new PMUI.ui.MessageWindow({ + id: 'warningMessageWindowDelete', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: 'Routing Rule'.translate(), + message: 'Do you want to delete this routing rule?'.translate(), + footerItems: [ + { + id: 'warningMessageWindowDeleteButtonNo', + text: 'No'.translate(), + visible: true, + handler: function () { + warningMessageWindowDelete.close(); + }, + buttonType: "error" + }, + { + id: 'warningMessageWindowDeleteButtonYes', + text: 'Yes'.translate(), + visible: true, + handler: function () { + deleteRow(); + warningMessageWindowDelete.close(); + }, + buttonType: "success" + } + ] + }); + warningMessageWindowDirty = new PMUI.ui.MessageWindow({ + id: 'warningMessageWindowDirty', + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: 'Routing Rule'.translate(), + message: 'Are you sure you want to discard your changes?'.translate(), + footerItems: [ + { + id: 'warningMessageWindowDirtyButtonNo', + text: 'No'.translate(), + visible: true, + handler: function () { + warningMessageWindowDirty.close(); + }, + buttonType: "error" + }, { + id: 'warningMessageWindowDirtyButtonYes', + text: 'Yes'.translate(), + visible: true, + handler: function () { + warningMessageWindowDirty.close(); + windowConnections.close(); + }, + buttonType: "success" + } + ] + }); + + buttonAdd = new PMUI.ui.Button({ + id: 'routingRuleButtonAdd', + text: 'Add Routing Rule'.translate(), + style: { + cssProperties: { + marginLeft: '50px', + marginTop: '10px', + marginBottom: '10px', + padding: "5px" + } + }, + buttonType: 'success', + handler: function () { + // to add a new row + addRow(); + enableSorting(); + } + }); + buttonSave = new PMUI.ui.Button({ + id: 'windowConnectionsButtonSave', + text: 'Save'.translate(), + handler: function () { + //validate routing rules form + if (isValidRoutingRules()) { + //remove all flows an get points + var allPoints = removeConnectionsIntoCanvas(); + saveConnections(allPoints); + } + + }, + buttonType: 'success' + }); + buttonCancel = new PMUI.ui.Button({ + id: 'windowConnectionsButtonCancel', + text: 'Cancel'.translate(), + buttonType: 'error', + handler: function () { + if (formRoutingRule.isDirty()) { + warningMessageWindowDirty.open(); + warningMessageWindowDirty.showFooter(); + } else { + windowConnections.close(); + } + } + }); + + labelNextTask = new PMUI.ui.TextLabel({ + text: 'Next Task'.translate() + }); + labelNextTask.setWidth(382); + labelNextTask.style.addProperties({padding: '5px 0px 0px 50px'}); + + labelCondition = new PMUI.ui.TextLabel({ + text: 'Condition'.translate() + }); + labelCondition.setWidth(410); + labelCondition.style.addProperties({padding: '5px 0px 0px 5px'}); + labelCondition.style.addProperties({marginLeft: '31%'}); + + containerLabels = new PMUI.core.Panel({ + layout: 'hbox', + width: 'auto', + height: 29, + style: { + cssProperties: { + 'border-bottom': '1px solid #c0c0c0' + } + } + }); + containerLabels.addItem(labelNextTask); + containerLabels.addItem(labelCondition); + containerLabels.style.addProperties({'border-bottom': '1px solid #e7e7e7'}); + + formRoutingRule = new PMUI.form.Form({ + id: 'formRoutingRule', + visibleHeader: false, + width: DEFAULT_WINDOW_WIDTH - 60, + height: 'auto', + items: [], + style: { + cssProperties: { + 'margin-left': '35px' + } + } + }); + formRoutingRule.hideFooter(); + + windowConnections = new PMUI.ui.Window({ + id: 'windowConnections', + title: 'Routing Rule'.translate(), + height: DEFAULT_WINDOW_HEIGHT, + width: DEFAULT_WINDOW_WIDTH, + footerAlign: 'right', + buttonPanelPosition: 'bottom', + items: [ + buttonAdd + ], + buttons: [ + buttonCancel, + buttonSave + ] + }); + + typeShapeValueText = (shape.gat_type === 'EXCLUSIVE') ? 'EXCLUSIVE'.translate() : 'INCLUSIVE'.translate(); + windowConnections.setTitle('Routing Rule'.translate() + ' - ' + typeShapeValueText); + windowConnections.showFooter(); + windowConnections.addItem(containerLabels); + if (formRoutingRule.dirty === null) { + formRoutingRule.dirty = false; + } + windowConnections.addItem(formRoutingRule); + windowConnections.open(); + + loadConnections(); + enableSorting(); + /** + * add a new row + * @returns {PMUI.form.FormPanel|*} + */ + function addRow() { + var dropDownControl, + criteriaField, + deleteButton, + newRow, + max, + i; + newRow = new PMUI.form.FormPanel({ + layout: 'hbox' + }); + + dropDownControl = new PMUI.field.DropDownListField({ + id: 'dropdownNextTask', + name: 'act_name', + valueType: 'string', + label: 'Next Task'.translate(), + labelPosition: 'top', + labelVisible: false, + value: '', + readOnly: false, + controlsWidth: 360, + proportion: 0.9, + style: { + cssProperties: { + 'vertical-align': 'top' + } + } + }); + + criteriaField = new CriteriaField({ + id: 'textCondition', + pmType: 'text', + renderType: 'textarea', + name: 'flo_condition', + valueType: 'string', + label: 'Condition'.translate(), + labelPosition: 'top', + labelVisible: false, + controlsWidth: 345, + required: false, + style: { + cssProperties: { + 'vertical-align': 'top' + } + } + }); + deleteButton = new PMUI.field.ButtonField({ + id: 'buttonDelete', + value: 'Delete'.translate(), + handler: function (e, a) { + formPanelSelected = this.getParent(); + warningMessageWindowDelete.open(); + warningMessageWindowDelete.dom.titleContainer.style.height = '17px'; + warningMessageWindowDelete.showFooter(); + enableSorting(); + }, + name: 'delete', + labelVisible: false, + buttonAling: 'left', + controlsWidth: 60, + proportion: 0.1, + style: { + cssProperties: { + 'vertical-align': 'top' + } + } + }); + + newRow.addItem(dropDownControl); + newRow.addItem(criteriaField); + newRow.addItem(deleteButton); + loadOptions(dropDownControl); + //apply styles; + if (availableShapes && availableShapes.length > 0) { + deleteButton.controls[0].button.setButtonType('error'); + $(deleteButton.getHTML()).find("a").css({ + padding: "5px" + }); + formRoutingRule.addItem(newRow); + for (i = 0, max = formRoutingRule.getItems().length; i < max; i += 1) { + formRoutingRule.getItems()[i].style.addProperties({'padding': 'initial'}); + } + dropDownControl.dom.labelTextContainer.style.display = 'none'; + criteriaField.dom.labelTextContainer.style.display = 'none'; + criteriaField.setValue(true); + } else { + PMDesigner.msgFlash('There are no items.'.translate(), windowConnections.footer, 'error'); + } + return newRow; + } + + function loadOptions(dropdown) { + var i, + customShapes, + element, + nameGroup, + evnLabelMap; + //Important! Any changes to synchronize the assessment of the condition + //of the functions: countActivities and loadActivities + dropdown.clearOptions(); + dropdown.setUID = function (uid) { + this.uid = uid; + }; + dropdown.getUID = function () { + return this.uid; + }; + dropdown.addOptionGroup({ + label: 'Task'.translate(), + selected: true, + options: [] + }); + dropdown.addOptionGroup({ + label: 'Sub-process'.translate(), + options: [] + }); + dropdown.addOptionGroup({ + label: 'Event'.translate(), + options: [] + }); + dropdown.addOptionGroup({ + label: 'Gateway'.translate(), + options: [] + }); + customShapes = PMUI.getActiveCanvas().getCustomShapes(); + + for (i = 0; i < customShapes.getSize(); i += 1) { + element = customShapes.get(i); + // verify pool and participant + if (element.getType() !== 'PMParticipant' && element.getType() !== 'PMPool') { + //itself verify and same parent + if (shape.getID() !== element.getID() + && element.businessObject + && shape.businessObject + && shape.businessObject.elem.$parent + && element.businessObject.elem.$parent + && element.businessObject.elem.$parent.id === shape.businessObject.elem.$parent.id) { + switch (element.type) { + case 'PMActivity': + nameGroup = element.act_type === 'TASK' ? 'Task'.translate() : 'Sub-process'.translate(); + dropdown.addOption({ + value: element.act_uid, + label: element.act_name + }, nameGroup); + arrayElementName[element.act_uid] = element.act_name; + availableShapes.push(element); + break; + case 'PMEvent': + evnLabelMap = { + 'END': 'End Event'.translate(), + 'INTERMEDIATE': 'Intermediate Event'.translate() + }; + + if (element.evn_type !== 'START') { + dropdown.addOption({ + value: element.evn_uid, + label: element.evn_name || evnLabelMap[element.evn_type] + }, 'Event'.translate()); + + arrayElementName[element.evn_uid] = element.evn_name || evnLabelMap[element.evn_type]; + availableShapes.push(element); + } + break; + case 'PMGateway': + dropdown.addOption({ + value: element.gat_uid, + label: element.gat_name || 'Gateway'.translate() + }, 'Gateway'); + arrayElementName[element.gat_uid] = element.gat_name || 'Gateway'.translate(); + availableShapes.push(element); + break; + } + } + } + } + } + + function removeConnectionsIntoCanvas() { + var shapeDest, connection, dt, allPoints = {}, i, j; + for (j = 0; j < arrayShapeIdRemoved.length; j += 1) { + shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', arrayShapeIdRemoved[j]); + dt = shape.getPorts().asArray(); + for (i = 0; i < dt.length; i += 1) { + connection = dt[i].getConnection(); + if (shape.getID() === connection.getSrcPort().getParent().getID() && + shapeDest.getID() === connection.getDestPort().getParent().getID()) { + //caching points + allPoints[shapeDest.getID()] = getPoints(connection); + removeConnection(connection); + + break; + } + } + } + arrayShapeIdRemoved = []; + return allPoints; + } + + /** + * to remove a individual connection and getting points + * @param connection + */ + function removeConnection(connection) { + + PMUI.getActiveCanvas().emptyCurrentSelection(); + PMUI.getActiveCanvas().setCurrentConnection(connection); + PMUI.getActiveCanvas().removeElements(); + connection.saveAndDestroy(); + PMUI.getActiveCanvas().removeConnection(connection); + } + + /** + * gets conenctions inital and final points + * @param connection + */ + function getPoints(connection) { + var result = []; + result[0] = connection.points[0]; + result[1] = connection.points[connection.points.length - 1]; + return result; + } + + + function editAllConnections(connArray) { + var i, + elem, + canvas = PMUI.getActiveCanvas(); + for(i = 0; i < connArray.length; i += 1) { + elem = connArray[i]; + if (elem && elem.connection) { + elem.oldShapeDest.removePort(elem.connection.destPort); + elem.shapeDest.addPort(elem.connection.destPort, 100, 100, + false, elem.connection.srcPort); + + elem.connection.lineSegments.clear(); + canvas.commandStack.add(new PMUI.command.CommandConnect(elem.connection)); + elem.connection.connect(); + canvas.triggerPortChangeEvent(elem.connection.destPort); + } + } + } + + + function createEndShape() { + var customShape, canvas = PMUI.getActiveCanvas(), command, x, y; + customShape = canvas.shapeFactory('END'); + + x = shape.getX() + shape.getWidth(); + y = shape.getY() + shape.getHeight() + 20; + + canvas.addElement(customShape, x, y, + customShape.topLeftOnCreation); + + //since it is a new element in the designer, we triggered the + //custom on create element event + canvas.updatedElement = customShape; + + // create the command for this new shape + command = new PMUI.command.CommandCreate(customShape); + canvas.commandStack.add(command); + command.execute(); + return customShape; + } + + /** + * new method to validate routing rules + * @returns {boolean} + */ + function isValidRoutingRules() { + var result = true, + arrayAux = [], + i, + max, + id, + dt = formRoutingRule.getItems(); + if (!formRoutingRule.isValid()) { + result = false; + return; + } + + for (i = 0, max = dt.length; i < max; i += 1) { + id = dt[i].getField("act_name").getValue(); + if (typeof(arrayAux[id]) === "undefined") { + arrayAux[id] = "1"; + } else { + result = false; + PMDesigner.msgWinError("The routing rule to \"{0}\" already exists".translate([arrayElementName[id]])); + return; + } + } + return result; + } + + function saveConnections(allPoints) { + var dt = formRoutingRule.getItems(), + id, + i, + oldId, + shapeDest, + oldShapeDest, + connection, + newConnection, + dataRouteAll, + dataRoute, + restClient, + newPoints, + conectionsArray = []; + + + for (i = 0; i < dt.length; i += 1) { + id = dt[i].getField('act_name').getValue(); + oldId = dt[i].getField('act_name').getUID(); + if (id !== '0') { + dataRouteGroup.push(id); + if (dt[i].getField('flo_condition').getValue() == "") { + dt[i].getField('flo_condition').setValue(true); + } + if (oldId === undefined) { + shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', id); + //getting current connection + + newPoints = allPoints[id]; + + newConnection = createConnection(shape, shapeDest, newPoints); + newConnection.setFlowCondition(dt[i].getField('flo_condition').getValue()); + } + if (oldId !== undefined && id === oldId) { + shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', id); + connection = isConnection(shape, shapeDest); + + if (typeof(connection) != "object") { + connection = createConnection(shape, shapeDest); + } + + connection.setFlowCondition(dt[i].getField('flo_condition').getValue()); + } + if (oldId !== undefined && id !== oldId) { + shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', id); + oldShapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', oldId); + connection = isConnection(shape, oldShapeDest); + + if (typeof(connection) != "object") { + connection = createConnection(shape, shapeDest); + } + + connection.setFlowCondition(dt[i].getField('flo_condition').getValue()); + + if (typeof(connection) != "object") { + connection = createConnection(shape, shapeDest); + } + + connection.setFlowCondition(dt[i].getField('flo_condition').getValue()); + + conectionsArray.push({ + "connection" : isConnection(shape, oldShapeDest) || null, + "shapeDest": shapeDest, + "oldShapeDest": oldShapeDest + }); + } + } else { + var customShape = createEndShape(); + createConnection(shape, customShape); + } + } + editAllConnections(conectionsArray); + + /*update routing order*/ + dataRouteAll = []; + for (i = 0; i < dataRouteGroup.length; i += 1) { + dataRoute = { + 'rou_case': parseInt(i) + 1, + 'rou_next_task': dataRouteGroup[i], + 'pro_uid': PMDesigner.project.id + }; + dataRouteAll.push(dataRoute); + } + restClient = new PMRestClient({ + endpoint: 'update-route-order', + typeRequest: 'update', + data: dataRouteAll, + functionSuccess: function () { + PMDesigner.msgFlash('Saved correctly'.translate(), document.body, 'success', 3000, 5); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems updating the routing rule, please try again.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + /*end update routing order*/ + + windowConnections.close(); + PMDesigner.msgFlash('Saved correctly'.translate(), document.body); + PMDesigner.project.dirty = true; + PMDesigner.project.setDirty(true); + } + + function createConnection(sourceShape, shape, points) { + var sourcePort, endPort, connection, canvas = PMUI.getActiveCanvas(), points; + sourcePort = new PMUI.draw.Port({ + width: 10, + height: 10 + }); + endPort = new PMUI.draw.Port({ + width: 10, + height: 10 + }); + if (!points) { + points = findBestPorts(sourceShape, shape); + } + sourceShape.addPort(sourcePort, points[0].x - sourceShape.getZoomX(), points[0].y - sourceShape.getZoomY()); + shape.addPort(endPort, points[1].x - shape.getZoomX(), points[1].y - shape.getZoomY(), false, sourcePort); + + //add ports to the canvas array for regularShapes + //shape.canvas.regularShapes.insert(sourcePort).insert(endPort); + //create the connection + connection = new PMFlow({ + srcPort: sourcePort, + destPort: endPort, + segmentColor: new PMUI.util.Color(0, 0, 0), + name: '', + canvas: shape.canvas, + segmentStyle: shape.connectionType.segmentStyle, + flo_type: shape.connectionType.type + }); + connection.setSrcDecorator(new PMUI.draw.ConnectionDecorator({ + width: 11, + height: 11, + canvas: canvas, + decoratorPrefix: (typeof shape.connectionType.srcDecorator !== 'undefined' + && shape.connectionType.srcDecorator !== null) ? + shape.connectionType.srcDecorator : 'mafe-sequence', + decoratorType: 'source', + parent: connection + })); + connection.setDestDecorator(new PMUI.draw.ConnectionDecorator({ + width: 11, + height: 11, + canvas: canvas, + decoratorPrefix: (typeof shape.connectionType.destDecorator !== 'undefined' + && shape.connectionType.destDecorator !== null) ? + shape.connectionType.destDecorator : 'mafe-sequence', + decoratorType: 'target', + parent: connection + })); + connection.canvas.commandStack.add(new PMUI.command.CommandConnect(connection)); + + //connect the two ports + connection.connect(); + connection.setSegmentMoveHandlers(); + + //add the connection to the canvas, that means insert its html to + // the DOM and adding it to the connections array + canvas.addConnection(connection); + + // Filling PMFlow fields + connection.setTargetShape(endPort.parent); + connection.setOriginShape(sourcePort.parent); + connection.savePoints(); + + // now that the connection was drawn try to create the intersections + connection.checkAndCreateIntersectionsWithAll(); + + //attaching port listeners + sourcePort.attachListeners(sourcePort); + endPort.attachListeners(endPort); + + // finally trigger createEvent + canvas.triggerCreateEvent(connection, []); + connection.flo_state = connection.points; + return connection; + } + + function findBestPorts(sourceShape, shape) { + var result = [], i, j, + distance = 99999999, + initPoint, + secondPoint, + midPoints = getMiddlePoints(sourceShape), + midPoints2 = getMiddlePoints(shape); + for (i = 0; i < midPoints.length; i += 1) { + initPoint = midPoints[i]; + for (j = 0; j < midPoints2.length; j += 1) { + secondPoint = midPoints2[j]; + if (distance > initPoint.getManhattanDistance(secondPoint)) { + distance = initPoint.getManhattanDistance(midPoints2[j]); + result[0] = (initPoint); + result[1] = (midPoints2[j]); + } + } + } + return result; + } + + function getMiddlePoints(shape) { + return [ + new PMUI.util.Point(Math.round(shape.zoomWidth / 2) + shape.getZoomX(), 0 + shape.getZoomY()), // TOP + new PMUI.util.Point(shape.zoomWidth + shape.getZoomX(), Math.round(shape.zoomHeight / 2) + shape.getZoomY()), // RIGHT + new PMUI.util.Point(Math.round(shape.zoomWidth / 2) + shape.getZoomX(), shape.zoomHeight + shape.getZoomY()), // BOTTOM + new PMUI.util.Point(0 + shape.getZoomX(), Math.round(shape.zoomHeight / 2) + shape.getZoomY()) // LEFT + ]; + } + + function loadConnections() { + var row, connection, dt = shape.getPorts().asArray(), + i, j; + for (i = 0; i < dt.length; i += 1) { + connection = dt[i].getConnection(); + if (shape.getID() !== connection.getDestPort().getParent().getID() && shape.gat_default_flow !== connection.flo_uid) { + row = addRow(); + row.getField('act_name').setValue(connection.getDestPort().getParent().getID()); + row.getField('act_name').setUID(connection.getDestPort().getParent().getID()); + row.getField('flo_condition').setValue(connection.getFlowCondition()); + + row.getItems()[2].style.addProperties({display: 'none'}); + row.getItems()[2].controls[0].button.setButtonType('error'); + $(row.getItems()[2].getHTML()).find("a").css({ + padding: "5px" + }); + formRoutingRule.addItem(row); + for (j = 0; j < formRoutingRule.getItems().length; j += 1) { + formRoutingRule.getItems()[j].style.addProperties({'padding': 'initial'}); + } + row.getItems()[0].dom.labelTextContainer.style.display = 'none'; + row.getItems()[1].dom.labelTextContainer.style.display = 'none'; + } + } + } + + function isConnection(sourceShape, shape) { + var connection, + i, + dt = sourceShape.getPorts().asArray(); + for (i = 0; i < dt.length; i += 1) { + connection = dt[i].getConnection(); + if (sourceShape.getID() === connection.getSrcPort().getParent().getID() && + shape.getID() === connection.getDestPort().getParent().getID()) { + return connection; + } + } + return false; + } + + function deleteRow() { + arrayShapeIdRemoved.push(formPanelSelected.getField('act_name').getValue()); + formRoutingRule.removeItem(formPanelSelected); + PMDesigner.msgFlash('Routing rule removed correctly'.translate(), windowConnections.footer); + } + + function enableSorting() { + var index = 0, + div = $(formRoutingRule.getHTML()).find(">div:nth-child(2)").css({"overflow": "initial"}); + div.sortable({ + items: '>div', + placeholder: 'steps-placeholder', + cursor: "move", + change: function (event, ui) { + index = ui.placeholder.index(); + }, + start: function (event, ui) { + }, + stop: function (event, ui) { + var dt = [], + row, + formPanelSelected, + id, + i, + j, + shapeDest, + connection; + + ui.item.parent().find(">div").each(function (i, e) { + dt.push(PMUI.getPMUIObject(e)); + }); + for (i = 0; i < dt.length; i += 1) { + formPanelSelected = dt[i]; + arrayShapeIdRemoved.push(formPanelSelected.getField('act_name').getValue()); + formRoutingRule.removeItem(formPanelSelected); + } + for (i = 0; i < dt.length; i += 1) { + row = addRow(); + row.getItems()[2].style.addProperties({display: 'none'}); + row.getItems()[2].controls[0].button.setButtonType('error'); + $(row.getItems()[2].getHTML()).find("a").css({ + padding: "5px" + }); + formRoutingRule.addItem(row); + for (j = 0; j < formRoutingRule.getItems().length; j += 1) { + formRoutingRule.getItems()[j].style.addProperties({'padding': 'initial'}); + } + row.getItems()[0].dom.labelTextContainer.style.display = 'none'; + row.getItems()[1].dom.labelTextContainer.style.display = 'none'; + row.getField('act_name').setValue(dt[i].getField('act_name').getValue()); + row.getField('flo_condition').setValue(dt[i].getField('flo_condition').getValue()); + id = dt[i].getField('act_name').getValue(); + shapeDest = PMUI.getActiveCanvas().getCustomShapes().find('id', id); + connection = isConnection(shape, shapeDest); + } + enableSorting(); + } + }); + } +}; + +PMDesigner.RoutingRuleDeleteAllFlow = function (shape) { + var warningMessageWindowDelete = new PMUI.ui.MessageWindow({ + windowMessageType: 'warning', + width: 490, + bodyHeight: 'auto', + title: 'Routing Rule'.translate(), + id: 'warningMessageWindowDelete', + message: 'Do you want to delete all routing rules?'.translate(), + footerItems: [ + { + id: 'warningMessageWindowDeleteButtonNo', + text: 'No'.translate(), + visible: true, + handler: function () { + warningMessageWindowDelete.close(); + }, + buttonType: "error" + }, { + id: 'warningMessageWindowDeleteButtonYes', + text: 'Yes'.translate(), + visible: true, + handler: function () { + deleteAllConnection(); + warningMessageWindowDelete.close(); + }, + buttonType: "success" + } + ] + }); + + function deleteAllConnection() { + var connection, elements = [], + i, + sw, + msg, + ports; + PMUI.getActiveCanvas().emptyCurrentSelection(); + //IMPORTANT: You must empty elements in another array due to the array reference indices managed. + //referer: PMDesigner.canvas.removeConnection & element.getPorts().asArray() + + ports = shape.getPorts().asArray(); + for (i = 0; i < ports.length; i += 1) { + elements.push(ports[i]); + } + sw = false; + for (i = 0; i < elements.length; i += 1) { + connection = elements[i].getConnection(); + if (shape.getID() !== connection.getDestPort().getParent().getID()) { + PMUI.getActiveCanvas().setCurrentConnection(connection); + PMUI.getActiveCanvas().removeElements(); + connection.saveAndDestroy(); + PMUI.getActiveCanvas().removeConnection(connection); + sw = true; + } + } + msg = sw ? 'Routing rules deleted successfully' : 'There aren\'t routing rules'; + PMDesigner.msgFlash(msg.translate(), document.body); + } + + warningMessageWindowDelete.open(); + warningMessageWindowDelete.showFooter(); + warningMessageWindowDelete.dom.titleContainer.style.height = '17px'; +}; + +PMDesigner.RoutingRuleSetOrder = function (diagram) { + var restClient = new PMRestClient({ + endpoint: 'update-route-order-from-project', + typeRequest: 'update', + data: {}, + functionSuccess: function () { + PMDesigner.msgFlash('Saved correctly'.translate(), document.body, 'success', 3000, 5); + } + }); + restClient.executeRestClient(); }; PMDesigner.dynaformDesigner = function (data) { var old = PMUI.activeCanvas, a; @@ -27478,132 +27478,132 @@ UserPicker.prototype.close = function () { } }; -var CriteriaUserField = function (options) { - this.renderType = (options && options.renderType) || "text"; - PMUI.field.TextField.call(this, options); - this.process = null; - this.workspace = null; - this.buttonHTML = null; - this.rows = options.rows; - this.user_uid = null; - CriteriaUserField.prototype.init.call(this, options); -}; - -CriteriaUserField.prototype = new PMUI.field.TextField(); - -CriteriaUserField.prototype.setProcess = function (process) { - this.process = process; - return this; -}; - -CriteriaUserField.prototype.setWorkspace = function (workspace) { - this.workspace = workspace; - return this; -}; - -CriteriaUserField.prototype.init = function (options) { - var defaults = { - process: PMDesigner.project.projectId, - workspace: WORKSPACE - }; - jQuery.extend(true, defaults, options); - this.setProcess(defaults.process) - .setWorkspace(defaults.workspace); -}; - -CriteriaUserField.prototype.createVariablePicker = function () { - var vp = new UserPicker({ - relatedField: this, - processId: this.process - }); - return vp; -}; - -CriteriaUserField.prototype.setControls = function () { - if (this.controls.length) { - return this; - } - if (this.renderType === 'text') { - this.controls.push(new PMUI.control.TextControl()); - } else { - this.controls.push(new PMUI.control.TextAreaControl({style: {cssProperties: {resize: 'vertical'}}})); - } - return this; -}; - -CriteriaUserField.prototype.createCallBack = function () { - var that = this, oldValue, newValue, init = 0; - return { - success: function (variable) { - init = that.controls[0].html.selectionStart; - prevText = that.controls[0].html.value.substr(0, init); - lastText = that.controls[0].html.value.substr(that.controls[0].html.selectionEnd, that.controls[0].html.value.length); - newValue = variable.username; - - that.setValue(newValue); - that.user_uid = variable.uid; - that.controls[0].html.selectionEnd = init + variable.username.length; - } - }; -}; - -CriteriaUserField.prototype.createHTML = function () { - var button, that = this; - PMUI.field.TextField.prototype.createHTML.call(this); - - button = new PMUI.ui.Button({ - id: 'buttonCriteriaUserField', - text: '...', - handler: function () { - that.createVariablePicker().open(that.createCallBack()); - }, - style: { - cssProperties: { - background: '#2d3e50', - fontSize: 18, - paddingLeft: '15px', - paddingRight: '15px', - borderRadius: '4px', - verticalAlign: 'top' - } - } - }); - - this.buttonHTML = button; - $(this.helper.html).before(button.getHTML()) - this.buttonHTML.style.addProperties({"margin-left": "10px"}); - this.buttonHTML.html.tabIndex = -1; - - if (this.rows != null) - this.controls[0].setHeight(this.rows); - button.defineEvents(); - - return this.html; -}; - -// Overwrite original init function for FormItemFactory -PMUI.form.FormItemFactory.prototype.init = function () { - var defaults = { - products: { - "criteria": CriteriaUserField, - "field": PMUI.form.Field, - "panel": PMUI.form.FormPanel, - "text": PMUI.field.TextField, - "password": PMUI.field.PasswordField, - "dropdown": PMUI.field.DropDownListField, - "radio": PMUI.field.RadioButtonGroupField, - "checkbox": PMUI.field.CheckBoxGroupField, - "textarea": PMUI.field.TextAreaField, - "datetime": PMUI.field.DateTimeField, - "optionsSelector": PMUI.field.OptionsSelectorField, - "buttonField": PMUI.field.ButtonField, - "annotation": PMUI.field.TextAnnotationField - }, - defaultProduct: "panel" - }; - this.setProducts(defaults.products) - .setDefaultProduct(defaults.defaultProduct); -}; +var CriteriaUserField = function (options) { + this.renderType = (options && options.renderType) || "text"; + PMUI.field.TextField.call(this, options); + this.process = null; + this.workspace = null; + this.buttonHTML = null; + this.rows = options.rows; + this.user_uid = null; + CriteriaUserField.prototype.init.call(this, options); +}; + +CriteriaUserField.prototype = new PMUI.field.TextField(); + +CriteriaUserField.prototype.setProcess = function (process) { + this.process = process; + return this; +}; + +CriteriaUserField.prototype.setWorkspace = function (workspace) { + this.workspace = workspace; + return this; +}; + +CriteriaUserField.prototype.init = function (options) { + var defaults = { + process: PMDesigner.project.projectId, + workspace: WORKSPACE + }; + jQuery.extend(true, defaults, options); + this.setProcess(defaults.process) + .setWorkspace(defaults.workspace); +}; + +CriteriaUserField.prototype.createVariablePicker = function () { + var vp = new UserPicker({ + relatedField: this, + processId: this.process + }); + return vp; +}; + +CriteriaUserField.prototype.setControls = function () { + if (this.controls.length) { + return this; + } + if (this.renderType === 'text') { + this.controls.push(new PMUI.control.TextControl()); + } else { + this.controls.push(new PMUI.control.TextAreaControl({style: {cssProperties: {resize: 'vertical'}}})); + } + return this; +}; + +CriteriaUserField.prototype.createCallBack = function () { + var that = this, oldValue, newValue, init = 0; + return { + success: function (variable) { + init = that.controls[0].html.selectionStart; + prevText = that.controls[0].html.value.substr(0, init); + lastText = that.controls[0].html.value.substr(that.controls[0].html.selectionEnd, that.controls[0].html.value.length); + newValue = variable.username; + + that.setValue(newValue); + that.user_uid = variable.uid; + that.controls[0].html.selectionEnd = init + variable.username.length; + } + }; +}; + +CriteriaUserField.prototype.createHTML = function () { + var button, that = this; + PMUI.field.TextField.prototype.createHTML.call(this); + + button = new PMUI.ui.Button({ + id: 'buttonCriteriaUserField', + text: '...', + handler: function () { + that.createVariablePicker().open(that.createCallBack()); + }, + style: { + cssProperties: { + background: '#2d3e50', + fontSize: 18, + paddingLeft: '15px', + paddingRight: '15px', + borderRadius: '4px', + verticalAlign: 'top' + } + } + }); + + this.buttonHTML = button; + $(this.helper.html).before(button.getHTML()) + this.buttonHTML.style.addProperties({"margin-left": "10px"}); + this.buttonHTML.html.tabIndex = -1; + + if (this.rows != null) + this.controls[0].setHeight(this.rows); + button.defineEvents(); + + return this.html; +}; + +// Overwrite original init function for FormItemFactory +PMUI.form.FormItemFactory.prototype.init = function () { + var defaults = { + products: { + "criteria": CriteriaUserField, + "field": PMUI.form.Field, + "panel": PMUI.form.FormPanel, + "text": PMUI.field.TextField, + "password": PMUI.field.PasswordField, + "dropdown": PMUI.field.DropDownListField, + "radio": PMUI.field.RadioButtonGroupField, + "checkbox": PMUI.field.CheckBoxGroupField, + "textarea": PMUI.field.TextAreaField, + "datetime": PMUI.field.DateTimeField, + "optionsSelector": PMUI.field.OptionsSelectorField, + "buttonField": PMUI.field.ButtonField, + "annotation": PMUI.field.TextAnnotationField + }, + defaultProduct: "panel" + }; + this.setProducts(defaults.products) + .setDefaultProduct(defaults.defaultProduct); +}; /** * Class representing a Web Entry @@ -32783,89 +32783,89 @@ MessageEventDefinition.prototype._resetEditMessageForm = function () { }; /*----------------------------------********---------------------------------*/ -/** - * @class IntroHelper - * Handle Intro helper - * - * @constructor - * Creates a new instance of the class - * @param {Object} options - */ -var IntroHelper = function (options) { - this.steps = []; - this.onExit = null; - this.introjs = null; - IntroHelper.prototype.initObject.call(this, options); -}; -IntroHelper.prototype.type = 'IntroHelper'; - -IntroHelper.prototype.initObject = function (options) { - var defaults = { - steps: [], - skipLabel: "Skip", - onExit : new Function() - }; - $.extend(true, defaults, options); - this.setSteps(defaults.steps); - - this.setSkipLabel(defaults.skipLabel); - this.setNextLabel(defaults.nextLabel); - this.setPrevLabel(defaults.prevLabel); - this.setDoneLabel(defaults.doneLabel); - this.setOnExit(defaults.onExit); -}; - -IntroHelper.prototype.setSteps = function (steps) { - this.steps = steps; - return this; -}; - -IntroHelper.prototype.setSkipLabel = function (label) { - this.skipLabel = label; - return this; -}; -IntroHelper.prototype.setNextLabel = function (label) { - this.nextLabel = label; - return this; -}; - -IntroHelper.prototype.setPrevLabel = function (label) { - this.prevLabel = label; - return this; -}; - -IntroHelper.prototype.setDoneLabel = function (label) { - this.doneLabel = label; - return this; -}; - -IntroHelper.prototype.setSkipLabel = function (label) { - this.skipLabel = label; - return this; -}; - -IntroHelper.prototype.setOnExit = function (callback) { - if (callback && typeof callback == "function") { - this.onExit = callback; - } - return this; -}; - -IntroHelper.prototype.startIntro = function () { - var that = this; - this.introjs = introJs(); - this.introjs.setOptions({ - steps: this.steps, - skipLabel: this.skipLabel, - nextLabel: this.nextLabel, - prevLabel: this.prevLabel, - doneLabel: this.doneLabel - }); - this.introjs.onexit(function () { - that.onExit(); - }); - - this.introjs.start(); +/** + * @class IntroHelper + * Handle Intro helper + * + * @constructor + * Creates a new instance of the class + * @param {Object} options + */ +var IntroHelper = function (options) { + this.steps = []; + this.onExit = null; + this.introjs = null; + IntroHelper.prototype.initObject.call(this, options); +}; +IntroHelper.prototype.type = 'IntroHelper'; + +IntroHelper.prototype.initObject = function (options) { + var defaults = { + steps: [], + skipLabel: "Skip", + onExit : new Function() + }; + $.extend(true, defaults, options); + this.setSteps(defaults.steps); + + this.setSkipLabel(defaults.skipLabel); + this.setNextLabel(defaults.nextLabel); + this.setPrevLabel(defaults.prevLabel); + this.setDoneLabel(defaults.doneLabel); + this.setOnExit(defaults.onExit); +}; + +IntroHelper.prototype.setSteps = function (steps) { + this.steps = steps; + return this; +}; + +IntroHelper.prototype.setSkipLabel = function (label) { + this.skipLabel = label; + return this; +}; +IntroHelper.prototype.setNextLabel = function (label) { + this.nextLabel = label; + return this; +}; + +IntroHelper.prototype.setPrevLabel = function (label) { + this.prevLabel = label; + return this; +}; + +IntroHelper.prototype.setDoneLabel = function (label) { + this.doneLabel = label; + return this; +}; + +IntroHelper.prototype.setSkipLabel = function (label) { + this.skipLabel = label; + return this; +}; + +IntroHelper.prototype.setOnExit = function (callback) { + if (callback && typeof callback == "function") { + this.onExit = callback; + } + return this; +}; + +IntroHelper.prototype.startIntro = function () { + var that = this; + this.introjs = introJs(); + this.introjs.setOptions({ + steps: this.steps, + skipLabel: this.skipLabel, + nextLabel: this.nextLabel, + prevLabel: this.prevLabel, + doneLabel: this.doneLabel + }); + this.introjs.onexit(function () { + that.onExit(); + }); + + this.introjs.start(); }; (function () { PMDesigner.scriptTaskProperties = function (activity) { @@ -34938,173 +34938,173 @@ SaveAs.prototype.init = function () { that.setTitle("Save as".translate()); that.addItem(that.saveAsForm); }; -(function () { - PMDesigner.granularProcessExport = function () { - var totalObjects = 0, - objectValues, - buttonSave, - objectsGroup, - loadObjects, - domSettings, - granularProcessExportForm, - granularProcessExportWindow, - buttonCancel = new PMUI.ui.Button({ - id: 'cancelButton', - text: "Cancel".translate(), - buttonType: 'error', - handler: function (event) { - granularProcessExportWindow.close(); - } - }); - - buttonSave = new PMUI.ui.Button({ - id: 'saveButton', - text: "Export".translate(), - handler: function (event) { - var selectedObjects, - locationOrigin, - ws = enviromentVariables('WORKSPACE'), - formData = granularProcessExportForm.getData(); - selectedObjects = JSON.parse(formData.objectsGroup).map(function (n) { - return n; - }); - if (selectedObjects.length === 0) { - PMDesigner.msgFlash('At least one object should be selected in order to execute the action.'.translate(), document.body, 'error', 3000, 5); - return; - } - if (!window.location.origin) { - locationOrigin = window.location.protocol + "//" + window.location.hostname + - (window.location.port ? ':' + window.location.port : ''); - } else if (typeof HTTP_SERVER_HOSTNAME !== 'undefined') { - locationOrigin = HTTP_SERVER_HOSTNAME; - } else { - locationOrigin = window.location.origin; - } - location.href = locationOrigin + "/api/1.0/" + ws + "/project/" + PMDesigner.project.id + - "/export-granular?access_token=" + PMDesigner.project.keys.access_token + '&objects=' + - encodeURIComponent(JSON.stringify(selectedObjects)); - granularProcessExportWindow.close(); - }, - buttonType: 'success' - }); - - granularProcessExportWindow = new PMUI.ui.Window({ - id: "granularProcessExportWindow", - title: "Export Process Objects".translate(), - width: 350, - height: DEFAULT_WINDOW_HEIGHT, - footerItems: [ - buttonCancel, - buttonSave - ], - buttonPanelPosition: "bottom", - footerAling: "right", - onBeforeClose: function () { - granularProcessExportWindow.close(); - } - }); - - objectsGroup = new PMUI.field.CheckBoxGroupField({ - labelVisible: false, - id: 'objectsGroup', - controlPositioning: 'horizontal', - maxDirectionOptions: 1, - required: true, - options: [], - onChange: function (newVal, oldVal) { - if (totalObjects > JSON.parse(newVal).length) { - granularProcessExportForm.getField('checkAllId').setValue(0); - } - } - }); - - loadObjects = function () { - var objectsList, - restClient, - i; - restClient = new PMRestClient({ - endpoint: 'export/listObjects', - typeRequest: 'get', - functionSuccess: function (xhr, response) { - var arrayIds = [], - i; - objectsList = JSON.parse(response); - for (i in objectsList.data) { - objectsGroup.addOption({ - label: objectsList.data[i].OBJECT_NAME, - name: objectsList.data[i].OBJECT_NAME, - selected: false, - value: objectsList.data[i].OBJECT_ID - }); - arrayIds.push(objectsList.data[i].OBJECT_ID.toString()); - } - totalObjects = objectsList.data.length; - objectValues = objectsGroup.getValueFromControls(); - objectValues = JSON.parse(objectValues).length ? objectValues : JSON.stringify(arrayIds); - }, - functionFailure: function (xhr, response) { - PMDesigner.msgWinError(response.error.message); - PMDesigner.msgFlash('There are problems loading the process objects.'.translate(), document.body, 'error', 3000, 5); - } - }); - restClient.executeRestClient(); - }; - loadObjects(); - - granularProcessExportForm = new PMUI.form.Form({ - id: "granularProcessExportForm", - border: true, - visibleHeader: false, - width: '340px', - name: "granularProcessExportForm", - title: "", - items: [ - { - id: "panelDetailsCustom", - pmType: "panel", - layout: 'vbox', - fieldset: false, - height: '380px', - legend: "DETAILS".translate(), - items: [ - { - pmType: "checkbox", - id: "checkAllId", - labelVisible: false, - controlPositioning: 'vertical', - maxDirectionOptions: 2, - value: '', - options: [ - { - label: "Check All".translate(), - disabled: false, - value: '1', - selected: false - } - ], - onChange: function (newVal, oldVal) { - if (newVal[2] === "1") { - objectsGroup.setValueToControls(objectValues); - } else { - objectsGroup.setValueToControls(); - } - } - }, - objectsGroup - ] - } - ] - }); - - domSettings = function () { - $('#objectsGroup').find('label:eq(0)').remove(); - }; - - granularProcessExportWindow.addItem(granularProcessExportForm); - granularProcessExportWindow.open(); - granularProcessExportWindow.showFooter(); - domSettings(); - }; -}()); - +(function () { + PMDesigner.granularProcessExport = function () { + var totalObjects = 0, + objectValues, + buttonSave, + objectsGroup, + loadObjects, + domSettings, + granularProcessExportForm, + granularProcessExportWindow, + buttonCancel = new PMUI.ui.Button({ + id: 'cancelButton', + text: "Cancel".translate(), + buttonType: 'error', + handler: function (event) { + granularProcessExportWindow.close(); + } + }); + + buttonSave = new PMUI.ui.Button({ + id: 'saveButton', + text: "Export".translate(), + handler: function (event) { + var selectedObjects, + locationOrigin, + ws = enviromentVariables('WORKSPACE'), + formData = granularProcessExportForm.getData(); + selectedObjects = JSON.parse(formData.objectsGroup).map(function (n) { + return n; + }); + if (selectedObjects.length === 0) { + PMDesigner.msgFlash('At least one object should be selected in order to execute the action.'.translate(), document.body, 'error', 3000, 5); + return; + } + if (!window.location.origin) { + locationOrigin = window.location.protocol + "//" + window.location.hostname + + (window.location.port ? ':' + window.location.port : ''); + } else if (typeof HTTP_SERVER_HOSTNAME !== 'undefined') { + locationOrigin = HTTP_SERVER_HOSTNAME; + } else { + locationOrigin = window.location.origin; + } + location.href = locationOrigin + "/api/1.0/" + ws + "/project/" + PMDesigner.project.id + + "/export-granular?access_token=" + PMDesigner.project.keys.access_token + '&objects=' + + encodeURIComponent(JSON.stringify(selectedObjects)); + granularProcessExportWindow.close(); + }, + buttonType: 'success' + }); + + granularProcessExportWindow = new PMUI.ui.Window({ + id: "granularProcessExportWindow", + title: "Export Process Objects".translate(), + width: 350, + height: DEFAULT_WINDOW_HEIGHT, + footerItems: [ + buttonCancel, + buttonSave + ], + buttonPanelPosition: "bottom", + footerAling: "right", + onBeforeClose: function () { + granularProcessExportWindow.close(); + } + }); + + objectsGroup = new PMUI.field.CheckBoxGroupField({ + labelVisible: false, + id: 'objectsGroup', + controlPositioning: 'horizontal', + maxDirectionOptions: 1, + required: true, + options: [], + onChange: function (newVal, oldVal) { + if (totalObjects > JSON.parse(newVal).length) { + granularProcessExportForm.getField('checkAllId').setValue(0); + } + } + }); + + loadObjects = function () { + var objectsList, + restClient, + i; + restClient = new PMRestClient({ + endpoint: 'export/listObjects', + typeRequest: 'get', + functionSuccess: function (xhr, response) { + var arrayIds = [], + i; + objectsList = JSON.parse(response); + for (i in objectsList.data) { + objectsGroup.addOption({ + label: objectsList.data[i].OBJECT_NAME, + name: objectsList.data[i].OBJECT_NAME, + selected: false, + value: objectsList.data[i].OBJECT_ID + }); + arrayIds.push(objectsList.data[i].OBJECT_ID.toString()); + } + totalObjects = objectsList.data.length; + objectValues = objectsGroup.getValueFromControls(); + objectValues = JSON.parse(objectValues).length ? objectValues : JSON.stringify(arrayIds); + }, + functionFailure: function (xhr, response) { + PMDesigner.msgWinError(response.error.message); + PMDesigner.msgFlash('There are problems loading the process objects.'.translate(), document.body, 'error', 3000, 5); + } + }); + restClient.executeRestClient(); + }; + loadObjects(); + + granularProcessExportForm = new PMUI.form.Form({ + id: "granularProcessExportForm", + border: true, + visibleHeader: false, + width: '340px', + name: "granularProcessExportForm", + title: "", + items: [ + { + id: "panelDetailsCustom", + pmType: "panel", + layout: 'vbox', + fieldset: false, + height: '380px', + legend: "DETAILS".translate(), + items: [ + { + pmType: "checkbox", + id: "checkAllId", + labelVisible: false, + controlPositioning: 'vertical', + maxDirectionOptions: 2, + value: '', + options: [ + { + label: "Check All".translate(), + disabled: false, + value: '1', + selected: false + } + ], + onChange: function (newVal, oldVal) { + if (newVal[2] === "1") { + objectsGroup.setValueToControls(objectValues); + } else { + objectsGroup.setValueToControls(); + } + } + }, + objectsGroup + ] + } + ] + }); + + domSettings = function () { + $('#objectsGroup').find('label:eq(0)').remove(); + }; + + granularProcessExportWindow.addItem(granularProcessExportForm); + granularProcessExportWindow.open(); + granularProcessExportWindow.showFooter(); + domSettings(); + }; +}()); + diff --git a/vendor/colosa/MichelangeloFE/build/js/mafe.js b/vendor/colosa/MichelangeloFE/build/js/mafe.js index ad77cfc9e..065bfc654 100644 --- a/vendor/colosa/MichelangeloFE/build/js/mafe.js +++ b/vendor/colosa/MichelangeloFE/build/js/mafe.js @@ -6830,1415 +6830,1415 @@ var PMExtend = function (classObj, method, additionalFunc) { } }.call(this)); -// wrapper for non-node envs -;(function (sax) { - - sax.parser = function (strict, opt) { return new SAXParser(strict, opt) } - sax.SAXParser = SAXParser - sax.SAXStream = SAXStream - sax.createStream = createStream - -// When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns. -// When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)), -// since that's the earliest that a buffer overrun could occur. This way, checks are -// as rare as required, but as often as necessary to ensure never crossing this bound. -// Furthermore, buffers are only tested at most once per write(), so passing a very -// large string into write() might have undesirable effects, but this is manageable by -// the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme -// edge case, result in creating at most one complete copy of the string passed in. -// Set to Infinity to have unlimited buffers. - sax.MAX_BUFFER_LENGTH = 64 * 1024 - - var buffers = [ - "comment", "sgmlDecl", "textNode", "tagName", "doctype", - "procInstName", "procInstBody", "entity", "attribName", - "attribValue", "cdata", "script" - ] - - sax.EVENTS = // for discoverability. - [ "text" - , "processinginstruction" - , "sgmldeclaration" - , "doctype" - , "comment" - , "attribute" - , "opentag" - , "closetag" - , "opencdata" - , "cdata" - , "closecdata" - , "error" - , "end" - , "ready" - , "script" - , "opennamespace" - , "closenamespace" - ] - - function SAXParser (strict, opt) { - if (!(this instanceof SAXParser)) return new SAXParser(strict, opt) - - var parser = this - clearBuffers(parser) - parser.q = parser.c = "" - parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH - parser.opt = opt || {} - parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags - parser.looseCase = parser.opt.lowercase ? "toLowerCase" : "toUpperCase" - parser.tags = [] - parser.closed = parser.closedRoot = parser.sawRoot = false - parser.tag = parser.error = null - parser.strict = !!strict - parser.noscript = !!(strict || parser.opt.noscript) - parser.state = S.BEGIN - parser.ENTITIES = Object.create(sax.ENTITIES) - parser.attribList = [] - - // namespaces form a prototype chain. - // it always points at the current tag, - // which protos to its parent tag. - if (parser.opt.xmlns) parser.ns = Object.create(rootNS) - - // mostly just for error reporting - parser.trackPosition = parser.opt.position !== false - if (parser.trackPosition) { - parser.position = parser.line = parser.column = 0 - } - emit(parser, "onready") - } - - if (!Object.create) Object.create = function (o) { - function f () { this.__proto__ = o } - f.prototype = o - return new f - } - - if (!Object.getPrototypeOf) Object.getPrototypeOf = function (o) { - return o.__proto__ - } - - if (!Object.keys) Object.keys = function (o) { - var a = [] - for (var i in o) if (o.hasOwnProperty(i)) a.push(i) - return a - } - - function checkBufferLength (parser) { - var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10) - , maxActual = 0 - for (var i = 0, l = buffers.length; i < l; i ++) { - var len = parser[buffers[i]].length - if (len > maxAllowed) { - // Text/cdata nodes can get big, and since they're buffered, - // we can get here under normal conditions. - // Avoid issues by emitting the text node now, - // so at least it won't get any bigger. - switch (buffers[i]) { - case "textNode": - closeText(parser) - break - - case "cdata": - emitNode(parser, "oncdata", parser.cdata) - parser.cdata = "" - break - - case "script": - emitNode(parser, "onscript", parser.script) - parser.script = "" - break - - default: - error(parser, "Max buffer length exceeded: "+buffers[i]) - } - } - maxActual = Math.max(maxActual, len) - } - // schedule the next check for the earliest possible buffer overrun. - parser.bufferCheckPosition = (sax.MAX_BUFFER_LENGTH - maxActual) - + parser.position - } - - function clearBuffers (parser) { - for (var i = 0, l = buffers.length; i < l; i ++) { - parser[buffers[i]] = "" - } - } - - function flushBuffers (parser) { - closeText(parser) - if (parser.cdata !== "") { - emitNode(parser, "oncdata", parser.cdata) - parser.cdata = "" - } - if (parser.script !== "") { - emitNode(parser, "onscript", parser.script) - parser.script = "" - } - } - - SAXParser.prototype = - { end: function () { end(this) } - , write: write - , resume: function () { this.error = null; return this } - , close: function () { return this.write(null) } - , flush: function () { flushBuffers(this) } - } - - try { - var Stream = require("stream").Stream - } catch (ex) { - var Stream = function () {} - } - - - var streamWraps = sax.EVENTS.filter(function (ev) { - return ev !== "error" && ev !== "end" - }) - - function createStream (strict, opt) { - return new SAXStream(strict, opt) - } - - function SAXStream (strict, opt) { - if (!(this instanceof SAXStream)) return new SAXStream(strict, opt) - - Stream.apply(this) - - this._parser = new SAXParser(strict, opt) - this.writable = true - this.readable = true - - - var me = this - - this._parser.onend = function () { - me.emit("end") - } - - this._parser.onerror = function (er) { - me.emit("error", er) - - // if didn't throw, then means error was handled. - // go ahead and clear error, so we can write again. - me._parser.error = null - } - - this._decoder = null; - - streamWraps.forEach(function (ev) { - Object.defineProperty(me, "on" + ev, { - get: function () { return me._parser["on" + ev] }, - set: function (h) { - if (!h) { - me.removeAllListeners(ev) - return me._parser["on"+ev] = h - } - me.on(ev, h) - }, - enumerable: true, - configurable: false - }) - }) - } - - SAXStream.prototype = Object.create(Stream.prototype, - { constructor: { value: SAXStream } }) - - SAXStream.prototype.write = function (data) { - if (typeof Buffer === 'function' && - typeof Buffer.isBuffer === 'function' && - Buffer.isBuffer(data)) { - if (!this._decoder) { - var SD = require('string_decoder').StringDecoder - this._decoder = new SD('utf8') - } - data = this._decoder.write(data); - } - - this._parser.write(data.toString()) - this.emit("data", data) - return true - } - - SAXStream.prototype.end = function (chunk) { - if (chunk && chunk.length) this.write(chunk) - this._parser.end() - return true - } - - SAXStream.prototype.on = function (ev, handler) { - var me = this - if (!me._parser["on"+ev] && streamWraps.indexOf(ev) !== -1) { - me._parser["on"+ev] = function () { - var args = arguments.length === 1 ? [arguments[0]] - : Array.apply(null, arguments) - args.splice(0, 0, ev) - me.emit.apply(me, args) - } - } - - return Stream.prototype.on.call(me, ev, handler) - } - - - -// character classes and tokens - var whitespace = "\r\n\t " - // this really needs to be replaced with character classes. - // XML allows all manner of ridiculous numbers and digits. - , number = "0124356789" - , letter = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" - // (Letter | "_" | ":") - , quote = "'\"" - , entity = number+letter+"#" - , attribEnd = whitespace + ">" - , CDATA = "[CDATA[" - , DOCTYPE = "DOCTYPE" - , XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace" - , XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/" - , rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE } - -// turn all the string character sets into character class objects. - whitespace = charClass(whitespace) - number = charClass(number) - letter = charClass(letter) - -// http://www.w3.org/TR/REC-xml/#NT-NameStartChar -// This implementation works on strings, a single character at a time -// as such, it cannot ever support astral-plane characters (10000-EFFFF) -// without a significant breaking change to either this parser, or the -// JavaScript language. Implementation of an emoji-capable xml parser -// is left as an exercise for the reader. - var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/ - - var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040\.\d-]/ - - quote = charClass(quote) - entity = charClass(entity) - attribEnd = charClass(attribEnd) - - function charClass (str) { - return str.split("").reduce(function (s, c) { - s[c] = true - return s - }, {}) - } - - function isRegExp (c) { - return Object.prototype.toString.call(c) === '[object RegExp]' - } - - function is (charclass, c) { - return isRegExp(charclass) ? !!c.match(charclass) : charclass[c] - } - - function not (charclass, c) { - return !is(charclass, c) - } - - var S = 0 - sax.STATE = - { BEGIN : S++ - , TEXT : S++ // general stuff - , TEXT_ENTITY : S++ // & and such. - , OPEN_WAKA : S++ // < - , SGML_DECL : S++ // - , SCRIPT : S++ // ', $js_path) . "\n"; - $javascript_init = true; - } - $html .= '\n"; - } - - if ( ($parts & Securimage::HTML_ICON_REFRESH) > 0 && $show_refresh_btn) { - $icon_path = $securimage_path . '/images/refresh.png'; - if ($refresh_icon_url) { - $icon_path = $refresh_icon_url; - } - $img_tag = sprintf('%s', - $icon_size, $icon_size, htmlspecialchars($icon_path), htmlspecialchars($refresh_alt)); - - $html .= sprintf('%s
', - htmlspecialchars($refresh_title), - ($audio_obj) ? "if (typeof window.{$audio_obj} !== 'undefined') {$audio_obj}.refresh(); " : '', - $image_id, - $show_path, - $img_tag - ); - } - - if ($parts == Securimage::HTML_ALL) { - $html .= '
'; - } - - if ( ($parts & Securimage::HTML_INPUT_LABEL) > 0 && $show_input) { - $html .= sprintf(' ', - htmlspecialchars($input_id), - htmlspecialchars($input_text)); - - if (!empty($error_html)) { - $html .= $error_html; - } - } - - if ( ($parts & Securimage::HTML_INPUT) > 0 && $show_input) { - $input_attr = ''; - if (!is_array($input_attrs)) $input_attrs = array(); - $input_attrs['type'] = 'text'; - $input_attrs['name'] = $input_name; - $input_attrs['id'] = $input_id; - - foreach($input_attrs as $name => $val) { - $input_attr .= sprintf('%s="%s" ', $name, htmlspecialchars($val)); - } - - $html .= sprintf('', $input_attr); - } - - return $html; - } - - /** - * Get the time in seconds that it took to solve the captcha. - * - * @return int The time in seconds from when the code was created, to when it was solved - */ - public function getTimeToSolve() - { - return $this->_timeToSolve; - } - - /** - * Set the namespace for the captcha being stored in the session or database. - * - * Namespaces are useful when multiple captchas need to be displayed on a single page. - * - * @param string $namespace Namespace value, String consisting of characters "a-zA-Z0-9_-" - */ - public function setNamespace($namespace) - { - $namespace = preg_replace('/[^a-z0-9-_]/i', '', $namespace); - $namespace = substr($namespace, 0, 64); - - if (!empty($namespace)) { - $this->namespace = $namespace; - } else { - $this->namespace = 'default'; - } - } - - /** - * Generate an audible captcha in WAV format and send it to the browser with appropriate headers. - * Example: - * - * $img = new Securimage(); - * $img->outputAudioFile(); // outputs a wav file to the browser - * exit; - * - * @param string $format - */ - public function outputAudioFile($format = null) - { - $consthashFx = Bootstrap::hashFx; - set_error_handler(array(&$this, 'errorHandler')); - - if (isset($_SERVER['HTTP_RANGE'])) { - $range = true; - $rangeId = (isset($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) ? - 'ID' . $_SERVER['HTTP_X_PLAYBACK_SESSION_ID'] : - 'ID' . $consthashFx($_SERVER['REQUEST_URI']); - $uniq = $rangeId; - } else { - $uniq = $consthashFx(uniqid(microtime())); - } - - try { - if (!($audio = $this->getAudioData())) { - // if previously generated audio not found for current captcha - require_once dirname(__FILE__) . '/WavFile.php'; - $audio = $this->getAudibleCode(); - - if (strtolower($format) == 'mp3') { - $audio = $this->wavToMp3($audio); - } - - $this->saveAudioData($audio); - } - } catch (Exception $ex) { - if (($fp = @fopen(dirname(__FILE__) . '/si.error_log', 'a+')) !== false) { - fwrite($fp, date('Y-m-d H:i:s') . ': Securimage audio error "' . $ex->getMessage() . '"' . "\n"); - fclose($fp); - } - - $audio = $this->audioError(); - } - - if ($this->no_session != true) { - // close session to make it available to other requests in the event - // streaming the audio takes sevaral seconds or more - session_write_close(); - } - - if ($this->canSendHeaders() || $this->send_headers == false) { - if ($this->send_headers) { - if ($format == 'mp3') { - $ext = 'mp3'; - $type = 'audio/mpeg'; - } else { - $ext = 'wav'; - $type = 'audio/wav'; - } - - header('Accept-Ranges: bytes'); - header("Content-Disposition: attachment; filename=\"securimage_audio-{$uniq}.{$ext}\""); - header('Cache-Control: no-store, no-cache, must-revalidate'); - header('Expires: Sun, 1 Jan 2000 12:00:00 GMT'); - header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . 'GMT'); - header('Content-type: ' . $type); - } - - $this->rangeDownload($audio); - } else { - echo '
' - .'Failed to generate audio file, content has already been ' - .'output.
This is most likely due to misconfiguration or ' - .'a PHP error was sent to the browser.
'; - } - - restore_error_handler(); - - if (!$this->no_exit) exit; - } - - /** - * Output audio data with http range support. Typically this shouldn't be - * called directly unless being used with a custom implentation. Use - * Securimage::outputAudioFile instead. - * - * @param string $audio Raw wav or mp3 audio file content - */ - public function rangeDownload($audio) - { - /* Congratulations Firefox Android/Linux/Windows for being the most - * sensible browser of all when streaming HTML5 audio! - * - * Chrome on Android and iOS on iPad/iPhone both make extra HTTP requests - * for the audio whether on WiFi or the mobile network resulting in - * multiple downloads of the audio file and wasted bandwidth. - * - * If I'm doing something wrong in this code or anyone knows why, I'd - * love to hear from you. - */ - $audioLength = $size = strlen($audio); - - if (isset($_SERVER['HTTP_RANGE'])) { - list( , $range) = explode('=', $_SERVER['HTTP_RANGE']); // bytes=byte-range-set - $range = trim($range); - - if (strpos($range, ',') !== false) { - // eventually, we should handle requests with multiple ranges - // most likely these types of requests will never be sent - header('HTTP/1.1 416 Range Not Satisfiable'); - echo "

Range Not Satisfiable

"; - exit; - } else if (preg_match('/(\d+)-(\d+)/', $range, $match)) { - // bytes n - m - $range = array(intval($match[1]), intval($match[2])); - } else if (preg_match('/(\d+)-$/', $range, $match)) { - // bytes n - last byte of file - $range = array(intval($match[1]), null); - } else if (preg_match('/-(\d+)/', $range, $match)) { - // final n bytes of file - $range = array($size - intval($match[1]), $size - 1); - } - - if ($range[1] === null) $range[1] = $size - 1; - $length = $range[1] - $range[0] + 1; - $audio = substr($audio, $range[0], $length); - $audioLength = strlen($audio); - - header('HTTP/1.1 206 Partial Content'); - header("Content-Range: bytes {$range[0]}-{$range[1]}/{$size}"); - - if ($range[0] < 0 ||$range[1] >= $size || $range[0] >= $size || $range[0] > $range[1]) { - header('HTTP/1.1 416 Range Not Satisfiable'); - echo "

Range Not Satisfiable

"; - exit; - } - } - - header('Content-Length: ' . $audioLength); - - echo htmlentities($audio, ENT_QUOTES | ENT_HTML5, 'UTF-8'); - } - - /** - * Return the code from the session or database (if configured). If none exists or was found, an empty string is returned. - * - * @param bool $array true to receive an array containing the code and properties, false to receive just the code. - * @param bool $returnExisting If true, and the class property *code* is set, it will be returned instead of getting the code from the session or database. - * @return array|string Return is an array if $array = true, otherwise a string containing the code - */ - public function getCode($array = false, $returnExisting = false) - { - $code = array(); - $time = 0; - $disp = 'error'; - - if ($returnExisting && strlen($this->code) > 0) { - if ($array) { - return array( - 'code' => $this->code, - 'display' => $this->code_display, - 'code_display' => $this->code_display, - 'time' => 0); - } else { - return $this->code; - } - } - - if ($this->no_session != true) { - if (isset($_SESSION['securimage_code_value'][$this->namespace]) && - trim($_SESSION['securimage_code_value'][$this->namespace]) != '') { - if ($this->isCodeExpired( - $_SESSION['securimage_code_ctime'][$this->namespace]) == false) { - $code['code'] = $_SESSION['securimage_code_value'][$this->namespace]; - $code['time'] = $_SESSION['securimage_code_ctime'][$this->namespace]; - $code['display'] = $_SESSION['securimage_code_disp'] [$this->namespace]; - } - } - } - - if (empty($code) && $this->use_database) { - // no code in session - may mean user has cookies turned off - $this->openDatabase(); - $code = $this->getCodeFromDatabase(); - - if (!empty($code)) { - $code['display'] = $code['code_disp']; - unset($code['code_disp']); - } - } else { /* no code stored in session or sqlite database, validation will fail */ } - - if ($array == true) { - return $code; - } else { - return $code['code']; - } - } - - /** - * The main image drawing routing, responsible for constructing the entire image and serving it - */ - protected function doImage() - { - if( ($this->use_transparent_text == true || $this->bgimg != '') && function_exists('imagecreatetruecolor')) { - $imagecreate = 'imagecreatetruecolor'; - } else { - $imagecreate = 'imagecreate'; - } - - $this->im = $imagecreate($this->image_width, $this->image_height); - $this->tmpimg = $imagecreate($this->image_width * $this->iscale, $this->image_height * $this->iscale); - - $this->allocateColors(); - imagepalettecopy($this->tmpimg, $this->im); - - $this->setBackground(); - - $code = ''; - - if ($this->getCaptchaId(false) !== null) { - // a captcha Id was supplied - - // check to see if a display_value for the captcha image was set - if (is_string($this->display_value) && strlen($this->display_value) > 0) { - $this->code_display = $this->display_value; - $this->code = ($this->case_sensitive) ? - $this->display_value : - strtolower($this->display_value); - $code = $this->code; - } else if ($this->openDatabase()) { - // no display_value, check the database for existing captchaId - $code = $this->getCodeFromDatabase(); - - // got back a result from the database with a valid code for captchaId - if (is_array($code)) { - $this->code = $code['code']; - $this->code_display = $code['code_disp']; - $code = $code['code']; - } - } - } - - if ($code == '') { - // if the code was not set using display_value or was not found in - // the database, create a new code - $this->createCode(); - } - - if ($this->noise_level > 0) { - $this->drawNoise(); - } - - $this->drawWord(); - - if ($this->perturbation > 0 && is_readable($this->ttf_file)) { - $this->distortedCopy(); - } - - if ($this->num_lines > 0) { - $this->drawLines(); - } - - if (trim($this->image_signature) != '') { - $this->addSignature(); - } - - $this->output(); - } - - /** - * Allocate the colors to be used for the image - */ - protected function allocateColors() - { - // allocate bg color first for imagecreate - $this->gdbgcolor = imagecolorallocate($this->im, - $this->image_bg_color->r, - $this->image_bg_color->g, - $this->image_bg_color->b); - - $alpha = intval($this->text_transparency_percentage / 100 * 127); - - if ($this->use_transparent_text == true) { - $this->gdtextcolor = imagecolorallocatealpha($this->im, - $this->text_color->r, - $this->text_color->g, - $this->text_color->b, - $alpha); - $this->gdlinecolor = imagecolorallocatealpha($this->im, - $this->line_color->r, - $this->line_color->g, - $this->line_color->b, - $alpha); - $this->gdnoisecolor = imagecolorallocatealpha($this->im, - $this->noise_color->r, - $this->noise_color->g, - $this->noise_color->b, - $alpha); - } else { - $this->gdtextcolor = imagecolorallocate($this->im, - $this->text_color->r, - $this->text_color->g, - $this->text_color->b); - $this->gdlinecolor = imagecolorallocate($this->im, - $this->line_color->r, - $this->line_color->g, - $this->line_color->b); - $this->gdnoisecolor = imagecolorallocate($this->im, - $this->noise_color->r, - $this->noise_color->g, - $this->noise_color->b); - } - - $this->gdsignaturecolor = imagecolorallocate($this->im, - $this->signature_color->r, - $this->signature_color->g, - $this->signature_color->b); - - } - - /** - * The the background color, or background image to be used - */ - protected function setBackground() - { - // set background color of image by drawing a rectangle since imagecreatetruecolor doesn't set a bg color - imagefilledrectangle($this->im, 0, 0, - $this->image_width, $this->image_height, - $this->gdbgcolor); - imagefilledrectangle($this->tmpimg, 0, 0, - $this->image_width * $this->iscale, $this->image_height * $this->iscale, - $this->gdbgcolor); - - if ($this->bgimg == '') { - if ($this->background_directory != null && - is_dir($this->background_directory) && - is_readable($this->background_directory)) - { - $img = $this->getBackgroundFromDirectory(); - if ($img != false) { - $this->bgimg = $img; - } - } - } - - if ($this->bgimg == '') { - return; - } - - $dat = @getimagesize($this->bgimg); - if($dat == false) { - return; - } - - switch($dat[2]) { - case 1: $newim = @imagecreatefromgif($this->bgimg); break; - case 2: $newim = @imagecreatefromjpeg($this->bgimg); break; - case 3: $newim = @imagecreatefrompng($this->bgimg); break; - default: return; - } - - if(!$newim) return; - - imagecopyresized($this->im, $newim, 0, 0, 0, 0, - $this->image_width, $this->image_height, - imagesx($newim), imagesy($newim)); - } - - /** - * Scan the directory for a background image to use - * @return string|bool - */ - protected function getBackgroundFromDirectory() - { - $images = array(); - - if ( ($dh = opendir($this->background_directory)) !== false) { - while (($file = readdir($dh)) !== false) { - if (preg_match('/(jpg|gif|png)$/i', $file)) $images[] = $file; - } - - closedir($dh); - - if (sizeof($images) > 0) { - return rtrim($this->background_directory, '/') . '/' . $images[mt_rand(0, sizeof($images)-1)]; - } - } - - return false; - } - - /** - * This method generates a new captcha code. - * - * Generates a random captcha code based on *charset*, math problem, or captcha from the wordlist and saves the value to the session and/or database. - */ - public function createCode() - { - $this->code = false; - - switch($this->captcha_type) { - case self::SI_CAPTCHA_MATHEMATIC: - { - do { - $signs = array('+', '-', 'x'); - $left = mt_rand(1, 10); - $right = mt_rand(1, 5); - $sign = $signs[mt_rand(0, 2)]; - - switch($sign) { - case 'x': $c = $left * $right; break; - case '-': $c = $left - $right; break; - default: $c = $left + $right; break; - } - } while ($c <= 0); // no negative #'s or 0 - - $this->code = "$c"; - $this->code_display = "$left $sign $right"; - break; - } - - case self::SI_CAPTCHA_WORDS: - $words = $this->readCodeFromFile(2); - $this->code = implode(' ', $words); - $this->code_display = $this->code; - break; - - default: - { - if ($this->use_wordlist && is_readable($this->wordlist_file)) { - $this->code = $this->readCodeFromFile(); - } - - if ($this->code == false) { - $this->code = $this->generateCode($this->code_length); - } - - $this->code_display = $this->code; - $this->code = ($this->case_sensitive) ? $this->code : strtolower($this->code); - } // default - } - - $this->saveData(); - } - - /** - * Draws the captcha code on the image - */ - protected function drawWord() - { - $width2 = $this->image_width * $this->iscale; - $height2 = $this->image_height * $this->iscale; - $ratio = ($this->font_ratio) ? $this->font_ratio : 0.4; - - if ((float)$ratio < 0.1 || (float)$ratio >= 1) { - $ratio = 0.4; - } - - if (!is_readable($this->ttf_file)) { - imagestring($this->im, 4, 10, ($this->image_height / 2) - 5, 'Failed to load TTF font file!', $this->gdtextcolor); - } else { - if ($this->perturbation > 0) { - $font_size = $height2 * $ratio; - $bb = imageftbbox($font_size, 0, $this->ttf_file, $this->code_display); - $tx = $bb[4] - $bb[0]; - $ty = $bb[5] - $bb[1]; - $x = floor($width2 / 2 - $tx / 2 - $bb[0]); - $y = round($height2 / 2 - $ty / 2 - $bb[1]); - - imagettftext($this->tmpimg, $font_size, 0, (int)$x, (int)$y, $this->gdtextcolor, $this->ttf_file, $this->code_display); - } else { - $font_size = $this->image_height * $ratio; - $bb = imageftbbox($font_size, 0, $this->ttf_file, $this->code_display); - $tx = $bb[4] - $bb[0]; - $ty = $bb[5] - $bb[1]; - $x = floor($this->image_width / 2 - $tx / 2 - $bb[0]); - $y = round($this->image_height / 2 - $ty / 2 - $bb[1]); - - imagettftext($this->im, $font_size, 0, (int)$x, (int)$y, $this->gdtextcolor, $this->ttf_file, $this->code_display); - } - } - - // DEBUG - //$this->im = $this->tmpimg; - //$this->output(); - - } - - /** - * Copies the captcha image to the final image with distortion applied - */ - protected function distortedCopy() - { - $numpoles = 3; // distortion factor - // make array of poles AKA attractor points - for ($i = 0; $i < $numpoles; ++ $i) { - $px[$i] = mt_rand($this->image_width * 0.2, $this->image_width * 0.8); - $py[$i] = mt_rand($this->image_height * 0.2, $this->image_height * 0.8); - $rad[$i] = mt_rand($this->image_height * 0.2, $this->image_height * 0.8); - $tmp = ((- $this->frand()) * 0.15) - .15; - $amp[$i] = $this->perturbation * $tmp; - } - - $bgCol = imagecolorat($this->tmpimg, 0, 0); - $width2 = $this->iscale * $this->image_width; - $height2 = $this->iscale * $this->image_height; - imagepalettecopy($this->im, $this->tmpimg); // copy palette to final image so text colors come across - // loop over $img pixels, take pixels from $tmpimg with distortion field - for ($ix = 0; $ix < $this->image_width; ++ $ix) { - for ($iy = 0; $iy < $this->image_height; ++ $iy) { - $x = $ix; - $y = $iy; - for ($i = 0; $i < $numpoles; ++ $i) { - $dx = $ix - $px[$i]; - $dy = $iy - $py[$i]; - if ($dx == 0 && $dy == 0) { - continue; - } - $r = sqrt($dx * $dx + $dy * $dy); - if ($r > $rad[$i]) { - continue; - } - $rscale = $amp[$i] * sin(3.14 * $r / $rad[$i]); - $x += $dx * $rscale; - $y += $dy * $rscale; - } - $c = $bgCol; - $x *= $this->iscale; - $y *= $this->iscale; - if ($x >= 0 && $x < $width2 && $y >= 0 && $y < $height2) { - $c = imagecolorat($this->tmpimg, $x, $y); - } - if ($c != $bgCol) { // only copy pixels of letters to preserve any background image - imagesetpixel($this->im, $ix, $iy, $c); - } - } - } - } - - /** - * Draws distorted lines on the image - */ - protected function drawLines() - { - for ($line = 0; $line < $this->num_lines; ++ $line) { - $x = $this->image_width * (1 + $line) / ($this->num_lines + 1); - $x += (0.5 - $this->frand()) * $this->image_width / $this->num_lines; - $y = mt_rand($this->image_height * 0.1, $this->image_height * 0.9); - - $theta = ($this->frand() - 0.5) * M_PI * 0.7; - $w = $this->image_width; - $len = mt_rand($w * 0.4, $w * 0.7); - $lwid = mt_rand(0, 2); - - $k = $this->frand() * 0.6 + 0.2; - $k = $k * $k * 0.5; - $phi = $this->frand() * 6.28; - $step = 0.5; - $dx = $step * cos($theta); - $dy = $step * sin($theta); - $n = $len / $step; - $amp = 1.5 * $this->frand() / ($k + 5.0 / $len); - $x0 = $x - 0.5 * $len * cos($theta); - $y0 = $y - 0.5 * $len * sin($theta); - - $ldx = round(- $dy * $lwid); - $ldy = round($dx * $lwid); - - for ($i = 0; $i < $n; ++ $i) { - $x = $x0 + $i * $dx + $amp * $dy * sin($k * $i * $step + $phi); - $y = $y0 + $i * $dy - $amp * $dx * sin($k * $i * $step + $phi); - imagefilledrectangle($this->im, $x, $y, $x + $lwid, $y + $lwid, $this->gdlinecolor); - } - } - } - - /** - * Draws random noise on the image - */ - protected function drawNoise() - { - if ($this->noise_level > 10) { - $noise_level = 10; - } else { - $noise_level = $this->noise_level; - } - - $t0 = microtime(true); - - $noise_level *= 125; // an arbitrary number that works well on a 1-10 scale - - $points = $this->image_width * $this->image_height * $this->iscale; - $height = $this->image_height * $this->iscale; - $width = $this->image_width * $this->iscale; - for ($i = 0; $i < $noise_level; ++$i) { - $x = mt_rand(10, $width); - $y = mt_rand(10, $height); - $size = mt_rand(7, 10); - if ($x - $size <= 0 && $y - $size <= 0) continue; // dont cover 0,0 since it is used by imagedistortedcopy - imagefilledarc($this->tmpimg, $x, $y, $size, $size, 0, 360, $this->gdnoisecolor, IMG_ARC_PIE); - } - - $t1 = microtime(true); - - $t = $t1 - $t0; - - /* - // DEBUG - imagestring($this->tmpimg, 5, 25, 30, "$t", $this->gdnoisecolor); - header('content-type: image/png'); - imagepng($this->tmpimg); - exit; - */ - } - - /** - * Print signature text on image - */ - protected function addSignature() - { - $bbox = imagettfbbox(10, 0, $this->signature_font, $this->image_signature); - $textlen = $bbox[2] - $bbox[0]; - $x = $this->image_width - $textlen - 5; - $y = $this->image_height - 3; - - imagettftext($this->im, 10, 0, $x, $y, $this->gdsignaturecolor, $this->signature_font, $this->image_signature); - } - - /** - * Sends the appropriate image and cache headers and outputs image to the browser - */ - protected function output() - { - if ($this->canSendHeaders() || $this->send_headers == false) { - if ($this->send_headers) { - // only send the content-type headers if no headers have been output - // this will ease debugging on misconfigured servers where warnings - // may have been output which break the image and prevent easily viewing - // source to see the error. - header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); - header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT"); - header("Cache-Control: no-store, no-cache, must-revalidate"); - header("Cache-Control: post-check=0, pre-check=0", false); - header("Pragma: no-cache"); - } - - switch ($this->image_type) { - case self::SI_IMAGE_JPEG: - if ($this->send_headers) header("Content-Type: image/jpeg"); - imagejpeg($this->im, null, 90); - break; - case self::SI_IMAGE_GIF: - if ($this->send_headers) header("Content-Type: image/gif"); - imagegif($this->im); - break; - default: - if ($this->send_headers) header("Content-Type: image/png"); - imagepng($this->im); - break; - } - } else { - echo '
' - .'Failed to generate captcha image, content has already been ' - .'output.
This is most likely due to misconfiguration or ' - .'a PHP error was sent to the browser.
'; - } - - imagedestroy($this->im); - restore_error_handler(); - - if (!$this->no_exit) exit; - } - - /** - * Generates an audio captcha in WAV format - * - * @return string The audio representation of the captcha in Wav format - */ - protected function getAudibleCode() - { - $letters = array(); - $code = $this->getCode(true, true); - - if (empty($code) || $code['code'] == '') { - if (strlen($this->display_value) > 0) { - $code = array('code' => $this->display_value, 'display' => $this->display_value); - } else { - $this->createCode(); - $code = $this->getCode(true); - } - } - - if (empty($code)) { - $error = 'Failed to get audible code (are database settings correct?). Check the error log for details'; - trigger_error($error, E_USER_WARNING); - throw new Exception($error); - } - - if (preg_match('/(\d+) (\+|-|x) (\d+)/i', $code['display'], $eq)) { - $math = true; - - $left = $eq[1]; - $sign = str_replace(array('+', '-', 'x'), array('plus', 'minus', 'times'), $eq[2]); - $right = $eq[3]; - - $letters = array($left, $sign, $right); - } else { - $math = false; - - $length = strlen($code['display']); - - for($i = 0; $i < $length; ++$i) { - $letter = $code['display']{$i}; - $letters[] = $letter; - } - } - - try { - return $this->generateWAV($letters); - } catch(Exception $ex) { - throw $ex; - } - } - - /** - * Gets a captcha code from a file containing a list of words. - * - * Seek to a random offset in the file and reads a block of data and returns a line from the file. - * - * @param int $numWords Number of words (lines) to read from the file - * @return string|array|bool Returns a string if only one word is to be read, or an array of words - */ - protected function readCodeFromFile($numWords = 1) - { - $strpos_func = 'strpos'; - $strlen_func = 'strlen'; - $substr_func = 'substr'; - $strtolower_func = 'strtolower'; - $mb_support = false; - - if (!empty($this->wordlist_file_encoding)) { - if (!extension_loaded('mbstring')) { - trigger_error("wordlist_file_encoding option set, but PHP does not have mbstring support", E_USER_WARNING); - return false; - } - - // emits PHP warning if not supported - $mb_support = mb_internal_encoding($this->wordlist_file_encoding); - - if (!$mb_support) { - return false; - } - - $strpos_func = 'mb_strpos'; - $strlen_func = 'mb_strlen'; - $substr_func = 'mb_substr'; - $strtolower_func = 'mb_strtolower'; - } - - $fp = fopen($this->wordlist_file, 'rb'); - if (!$fp) return false; - - $fsize = filesize($this->wordlist_file); - if ($fsize < 128) return false; // too small of a list to be effective - - if ((int)$numWords < 1 || (int)$numWords > 5) $numWords = 1; - - $words = array(); - $i = 0; - do { - fseek($fp, mt_rand(0, $fsize - 128), SEEK_SET); // seek to a random position of file from 0 to filesize-128 - $data = fread($fp, 128); // read a chunk from our random position - - if ($mb_support !== false) { - $data = mb_ereg_replace("\r?\n", "\n", $data); - } else { - $data = preg_replace("/\r?\n/", "\n", $data); - } - - $start = @$strpos_func($data, "\n", mt_rand(0, 56)) + 1; // random start position - $end = @$strpos_func($data, "\n", $start); // find end of word - - if ($start === false) { - // picked start position at end of file - continue; - } else if ($end === false) { - $end = $strlen_func($data); - } - - $word = $strtolower_func($substr_func($data, $start, $end - $start)); // return a line of the file - - if ($mb_support) { - // convert to UTF-8 for imagettftext - $word = mb_convert_encoding($word, 'UTF-8', $this->wordlist_file_encoding); - } - - $words[] = $word; - } while (++$i < $numWords); - - fclose($fp); - - if ($numWords < 2) { - return $words[0]; - } else { - return $words; - } - } - - /** - * Generates a random captcha code from the set character set - * - * @see Securimage::$charset Charset option - * @return string A randomly generated CAPTCHA code - */ - protected function generateCode() - { - $code = ''; - - if (function_exists('mb_strlen')) { - for($i = 1, $cslen = mb_strlen($this->charset, 'UTF-8'); $i <= $this->code_length; ++$i) { - $code .= mb_substr($this->charset, mt_rand(0, $cslen - 1), 1, 'UTF-8'); - } - } else { - for($i = 1, $cslen = strlen($this->charset); $i <= $this->code_length; ++$i) { - $code .= substr($this->charset, mt_rand(0, $cslen - 1), 1); - } - } - - return $code; - } - - /** - * Validate a code supplied by the user - * - * Checks the entered code against the value stored in the session and/or database (if configured). Handles case sensitivity. - * Also removes the code from session/database if the code was entered correctly to prevent re-use attack. - * - * This function does not return a value. - * - * @see Securimage::$correct_code 'correct_code' property - */ - protected function validate() - { - if (!is_string($this->code) || strlen($this->code) == 0) { - $code = $this->getCode(true); - // returns stored code, or an empty string if no stored code was found - // checks the session and database if enabled - } else { - $code = $this->code; - } - - if (is_array($code)) { - if (!empty($code)) { - $ctime = $code['time']; - $code = $code['code']; - - $this->_timeToSolve = time() - $ctime; - } else { - $code = ''; - } - } - - if ($this->case_sensitive == false && preg_match('/[A-Z]/', $code)) { - // case sensitive was set from securimage_show.php but not in class - // the code saved in the session has capitals so set case sensitive to true - $this->case_sensitive = true; - } - - $code_entered = trim( (($this->case_sensitive) ? $this->code_entered - : strtolower($this->code_entered)) - ); - $this->correct_code = false; - - if ($code != '') { - if (strpos($code, ' ') !== false) { - // for multi word captchas, remove more than once space from input - $code_entered = preg_replace('/\s+/', ' ', $code_entered); - $code_entered = strtolower($code_entered); - } - - if ((string)$code === (string)$code_entered) { - $this->correct_code = true; - if ($this->no_session != true) { - $_SESSION['securimage_code_disp'] [$this->namespace] = ''; - $_SESSION['securimage_code_value'][$this->namespace] = ''; - $_SESSION['securimage_code_ctime'][$this->namespace] = ''; - $_SESSION['securimage_code_audio'][$this->namespace] = ''; - } - $this->clearCodeFromDatabase(); - } - } - } - - /** - * Save CAPTCHA data to session and database (if configured) - */ - protected function saveData() - { - if ($this->no_session != true) { - if (isset($_SESSION['securimage_code_value']) && is_scalar($_SESSION['securimage_code_value'])) { - // fix for migration from v2 - v3 - unset($_SESSION['securimage_code_value']); - unset($_SESSION['securimage_code_ctime']); - } - - $_SESSION['securimage_code_disp'] [$this->namespace] = $this->code_display; - $_SESSION['securimage_code_value'][$this->namespace] = $this->code; - $_SESSION['securimage_code_ctime'][$this->namespace] = time(); - $_SESSION['securimage_code_audio'][$this->namespace] = null; // clear previous audio, if set - } - - if ($this->use_database) { - $this->saveCodeToDatabase(); - } - } - - /** - * Save audio data to session and/or the configured database - * - * @param string $data The CAPTCHA audio data - */ - protected function saveAudioData($data) - { - if ($this->no_session != true) { - $_SESSION['securimage_code_audio'][$this->namespace] = $data; - } - - if ($this->use_database) { - $this->saveAudioToDatabase($data); - } - } - - /** - * Gets audio file contents from the session or database - * - * @return string|boolean Audio contents on success, or false if no audio found in session or DB - */ - protected function getAudioData() - { - if ($this->no_session != true) { - if (isset($_SESSION['securimage_code_audio'][$this->namespace])) { - return $_SESSION['securimage_code_audio'][$this->namespace]; - } - } - - if ($this->use_database) { - $this->openDatabase(); - $code = $this->getCodeFromDatabase(); - - if (!empty($code['audio_data'])) { - return $code['audio_data']; - } - } - - return false; - } - - /** - * Saves the CAPTCHA data to the configured database. - */ - protected function saveCodeToDatabase() - { - $success = false; - $this->openDatabase(); - - if ($this->use_database && $this->pdo_conn) { - $id = $this->getCaptchaId(false); - $ip = $_SERVER['REMOTE_ADDR']; - - if (empty($id)) { - $id = $ip; - } - - $time = time(); - $code = $this->code; - $code_disp = $this->code_display; - - // This is somewhat expensive in PDO Sqlite3 (when there is something to delete) - // Clears previous captcha for this client from database so we can do a straight insert - // without having to do INSERT ... ON DUPLICATE KEY or a find/update - $this->clearCodeFromDatabase(); - - $query = "INSERT INTO {$this->database_table} (" - ."id, code, code_display, namespace, created) " - ."VALUES(?, ?, ?, ?, ?)"; - - $stmt = $this->pdo_conn->prepare($query); - $success = $stmt->execute(array($id, $code, $code_disp, $this->namespace, $time)); - - if (!$success) { - $err = $stmt->errorInfo(); - $error = "Failed to insert code into database. {$err[1]}: {$err[2]}."; - - if ($this->database_driver == self::SI_DRIVER_SQLITE3) { - $err14 = ($err[1] == 14); - if ($err14) $error .= sprintf(" Ensure database directory and file are writeable by user '%s' (%d).", - get_current_user(), getmyuid()); - } - - trigger_error($error, E_USER_WARNING); - } - } - - return $success !== false; - } - - /** - * Saves CAPTCHA audio to the configured database - * - * @param string $data Audio data - * @return boolean true on success, false on failure - */ - protected function saveAudioToDatabase($data) - { - $success = false; - $this->openDatabase(); - - if ($this->use_database && $this->pdo_conn) { - $id = $this->getCaptchaId(false); - $ip = $_SERVER['REMOTE_ADDR']; - $ns = $this->namespace; - - if (empty($id)) { - $id = $ip; - } - - $query = "UPDATE {$this->database_table} SET audio_data = :audioData WHERE id = :id AND namespace = :namespace"; - $stmt = $this->pdo_conn->prepare($query); - $stmt->bindParam(':audioData', $data, PDO::PARAM_LOB); - $stmt->bindParam(':id', $id); - $stmt->bindParam(':namespace', $ns); - $success = $stmt->execute(); - } - - return $success !== false; - } - - /** - * Opens a connection to the configured database. - * - * @see Securimage::$use_database Use database - * @see Securimage::$database_driver Database driver - * @see Securimage::$pdo_conn pdo_conn - * @return bool true if the database connection was successful, false if not - */ - protected function openDatabase() - { - $this->pdo_conn = false; - - if ($this->use_database) { - $pdo_extension = 'PDO_' . strtoupper($this->database_driver); - - if (!extension_loaded($pdo_extension)) { - trigger_error("Database support is turned on in Securimage, but the chosen extension $pdo_extension is not loaded in PHP.", E_USER_WARNING); - return false; - } - } - - if ($this->database_driver == self::SI_DRIVER_SQLITE3) { - if (!file_exists($this->database_file)) { - $fp = fopen($this->database_file, 'w+'); - if (!$fp) { - $err = error_get_last(); - trigger_error("Securimage failed to create SQLite3 database file '{$this->database_file}'. Reason: {$err['message']}", E_USER_WARNING); - return false; - } - fclose($fp); - chmod($this->database_file, 0666); - } else if (!is_writeable($this->database_file)) { - trigger_error("Securimage does not have read/write access to database file '{$this->database_file}. Make sure permissions are 0666 and writeable by user '" . get_current_user() . "'", E_USER_WARNING); - return false; - } - } - - try { - $dsn = $this->getDsn(); - - $options = array(); - $this->pdo_conn = new PDO($dsn, $this->database_user, $this->database_pass, $options); - } catch (PDOException $pdoex) { - trigger_error("Database connection failed: " . $pdoex->getMessage(), E_USER_WARNING); - return false; - } catch (Exception $ex) { - trigger_error($ex->getMessage(), E_USER_WARNING); - return false; - } - - try { - if (!$this->skip_table_check && !$this->checkTablesExist()) { - // create tables... - $this->createDatabaseTables(); - } - } catch (Exception $ex) { - trigger_error($ex->getMessage(), E_USER_WARNING); - $this->pdo_conn = false; - return false; - } - - if (mt_rand(0, 100) / 100.0 == 1.0) { - $this->purgeOldCodesFromDatabase(); - } - - return $this->pdo_conn; - } - - /** - * Get the PDO DSN string for connecting to the database - * - * @see Securimage::$database_driver Database driver - * @throws Exception If database specific options are not configured - * @return string The DSN for connecting to the database - */ - protected function getDsn() - { - $dsn = sprintf('%s:', $this->database_driver); - - switch($this->database_driver) { - case self::SI_DRIVER_SQLITE3: - $dsn .= $this->database_file; - break; - - case self::SI_DRIVER_MYSQL: - case self::SI_DRIVER_PGSQL: - if (empty($this->database_host)) { - throw new Exception('Securimage::database_host is not set'); - } else if (empty($this->database_name)) { - throw new Exception('Securimage::database_name is not set'); - } - - $dsn .= sprintf('host=%s;dbname=%s', - $this->database_host, - $this->database_name); - break; - - } - - return $dsn; - } - - /** - * Checks if the necessary database tables for storing captcha codes exist - * - * @throws Exception If the table check failed for some reason - * @return boolean true if the database do exist, false if not - */ - protected function checkTablesExist() - { - $table = $this->pdo_conn->quote($this->database_table); - - switch($this->database_driver) { - case self::SI_DRIVER_SQLITE3: - // query row count for sqlite, PRAGMA queries seem to return no - // rowCount using PDO even if there are rows returned - $query = "SELECT COUNT(id) FROM $table"; - break; - - case self::SI_DRIVER_MYSQL: - $query = "SHOW TABLES LIKE $table"; - break; - - case self::SI_DRIVER_PGSQL: - $query = "SELECT * FROM information_schema.columns WHERE table_name = $table;"; - break; - } - - $result = $this->pdo_conn->query($query); - - if (!$result) { - $err = $this->pdo_conn->errorInfo(); - - if ($this->database_driver == self::SI_DRIVER_SQLITE3 && - $err[1] === 1 && strpos($err[2], 'no such table') !== false) - { - return false; - } - - throw new Exception("Failed to check tables: {$err[0]} - {$err[1]}: {$err[2]}"); - } else if ($this->database_driver == self::SI_DRIVER_SQLITE3) { - // successful here regardless of row count for sqlite - return true; - } else if ($result->rowCount() == 0) { - return false; - } else { - return true; - } - } - - /** - * Create the necessary databaes table for storing captcha codes. - * - * Based on the database adapter used, the tables will created in the existing connection. - * - * @see Securimage::$database_driver Database driver - * @return boolean true if the tables were created, false if not - */ - protected function createDatabaseTables() - { - $queries = array(); - - switch($this->database_driver) { - case self::SI_DRIVER_SQLITE3: - $queries[] = "CREATE TABLE \"{$this->database_table}\" ( - id VARCHAR(40), - namespace VARCHAR(32) NOT NULL, - code VARCHAR(32) NOT NULL, - code_display VARCHAR(32) NOT NULL, - created INTEGER NOT NULL, - audio_data BLOB NULL, - PRIMARY KEY(id, namespace) - )"; - - $queries[] = "CREATE INDEX ndx_created ON {$this->database_table} (created)"; - break; - - case self::SI_DRIVER_MYSQL: - $queries[] = "CREATE TABLE `{$this->database_table}` ( - `id` VARCHAR(40) NOT NULL, - `namespace` VARCHAR(32) NOT NULL, - `code` VARCHAR(32) NOT NULL, - `code_display` VARCHAR(32) NOT NULL, - `created` INT NOT NULL, - `audio_data` MEDIUMBLOB NULL, - PRIMARY KEY(id, namespace), - INDEX(created) - )"; - break; - - case self::SI_DRIVER_PGSQL: - $queries[] = "CREATE TABLE {$this->database_table} ( - id character varying(40) NOT NULL, - namespace character varying(32) NOT NULL, - code character varying(32) NOT NULL, - code_display character varying(32) NOT NULL, - created integer NOT NULL, - audio_data bytea NULL, - CONSTRAINT pkey_id_namespace PRIMARY KEY (id, namespace) - )"; - - $queries[] = "CREATE INDEX ndx_created ON {$this->database_table} (created);"; - break; - } - - $this->pdo_conn->beginTransaction(); - - foreach($queries as $query) { - $result = $this->pdo_conn->query($query); - - if (!$result) { - $err = $this->pdo_conn->errorInfo(); - trigger_error("Failed to create table. {$err[1]}: {$err[2]}", E_USER_WARNING); - $this->pdo_conn->rollBack(); - $this->pdo_conn = false; - return false; - } - } - - $this->pdo_conn->commit(); - - return true; - } - - /** - * Retrieves a stored code from the database for based on the captchaId or - * IP address if captcha ID not used. - * - * @return string|array Empty string if no code was found or has expired, - * otherwise returns array of code information. - */ - protected function getCodeFromDatabase() - { - $code = ''; - - if ($this->use_database == true && $this->pdo_conn) { - if (Securimage::$_captchaId !== null) { - $query = "SELECT * FROM {$this->database_table} WHERE id = ?"; - $stmt = $this->pdo_conn->prepare($query); - $result = $stmt->execute(array(Securimage::$_captchaId)); - } else { - $ip = $_SERVER['REMOTE_ADDR']; - $ns = $this->namespace; - - // ip is stored in id column when no captchaId - $query = "SELECT * FROM {$this->database_table} WHERE id = ? AND namespace = ?"; - $stmt = $this->pdo_conn->prepare($query); - $result = $stmt->execute(array($ip, $ns)); - } - - if (!$result) { - $err = $this->pdo_conn->errorInfo(); - trigger_error("Failed to select code from database. {$err[0]}: {$err[1]}", E_USER_WARNING); - } else { - if ( ($row = $stmt->fetch()) !== false ) { - if (false == $this->isCodeExpired($row['created'])) { - if ($this->database_driver == self::SI_DRIVER_PGSQL && is_resource($row['audio_data'])) { - // pg bytea data returned as stream resource - $data = ''; - while (!feof($row['audio_data'])) { - $data .= fgets($row['audio_data']); - } - $row['audio_data'] = $data; - } - $code = array( - 'code' => $row['code'], - 'code_disp' => $row['code_display'], - 'time' => $row['created'], - 'audio_data' => $row['audio_data'], - ); - } - } - } - } - - return $code; - } - - /** - * Remove a stored code from the database based on captchaId or IP address. - */ - protected function clearCodeFromDatabase() - { - if ($this->pdo_conn) { - $ip = $_SERVER['REMOTE_ADDR']; - $ns = $this->pdo_conn->quote($this->namespace); - $id = Securimage::$_captchaId; - - if (empty($id)) { - $id = $ip; // if no captchaId set, IP address is captchaId. - } - - $id = $this->pdo_conn->quote($id); - - $query = sprintf("DELETE FROM %s WHERE id = %s AND namespace = %s", - $this->database_table, $id, $ns); - - $result = $this->pdo_conn->query($query); - if (!$result) { - trigger_error("Failed to delete code from database.", E_USER_WARNING); - } - } - } - - /** - * Deletes old (expired) codes from the database - */ - protected function purgeOldCodesFromDatabase() - { - if ($this->use_database && $this->pdo_conn) { - $now = time(); - $limit = (!is_numeric($this->expiry_time) || $this->expiry_time < 1) ? 86400 : $this->expiry_time; - - $query = sprintf("DELETE FROM %s WHERE %s - created > %s", - $this->database_table, - $now, - $this->pdo_conn->quote("$limit", PDO::PARAM_INT)); - - $result = $this->pdo_conn->query($query); - } - } - - /** - * Checks to see if the captcha code has expired and can no longer be used. - * - * @see Securimage::$expiry_time expiry_time - * @param int $creation_time The Unix timestamp of when the captcha code was created - * @return bool true if the code is expired, false if it is still valid - */ - protected function isCodeExpired($creation_time) - { - $expired = true; - - if (!is_numeric($this->expiry_time) || $this->expiry_time < 1) { - $expired = false; - } else if (time() - $creation_time < $this->expiry_time) { - $expired = false; - } - - return $expired; - } - - /** - * Generate a wav file given the $letters in the code - * - * @param array $letters The letters making up the captcha - * @return string The audio content in WAV format - */ - protected function generateWAV($letters) - { - $wavCaptcha = new WavFile(); - $first = true; // reading first wav file - - if ($this->audio_use_sox && !is_executable($this->sox_binary_path)) { - throw new Exception("Path to SoX binary is incorrect or not executable"); - } - - foreach ($letters as $letter) { - $letter = strtoupper($letter); - - try { - $letter_file = realpath($this->audio_path) . DIRECTORY_SEPARATOR . $letter . '.wav'; - - if ($this->audio_use_sox) { - $sox_cmd = sprintf("%s %s -t wav - %s", - $this->sox_binary_path, - $letter_file, - $this->getSoxEffectChain()); - - $data = `$sox_cmd`; - - $l = new WavFile(); - $l->setIgnoreChunkSizes(true); - $l->setWavData($data); - } else { - $l = new WavFile($letter_file); - } - - if ($first) { - // set sample rate, bits/sample, and # of channels for file based on first letter - $wavCaptcha->setSampleRate($l->getSampleRate()) - ->setBitsPerSample($l->getBitsPerSample()) - ->setNumChannels($l->getNumChannels()); - $first = false; - } - - // append letter to the captcha audio - $wavCaptcha->appendWav($l); - - // random length of silence between $audio_gap_min and $audio_gap_max - if ($this->audio_gap_max > 0 && $this->audio_gap_max > $this->audio_gap_min) { - $wavCaptcha->insertSilence( mt_rand($this->audio_gap_min, $this->audio_gap_max) / 1000.0 ); - } - } catch (Exception $ex) { - // failed to open file, or the wav file is broken or not supported - // 2 wav files were not compatible, different # channels, bits/sample, or sample rate - throw new Exception("Error generating audio captcha on letter '$letter': " . $ex->getMessage()); - } - } - - /********* Set up audio filters *****************************/ - $filters = array(); - - if ($this->audio_use_noise == true) { - // use background audio - find random file - $wavNoise = false; - $randOffset = 0; - - /* - // uncomment to try experimental SoX noise generation. - // warning: sounds may be considered annoying - if ($this->audio_use_sox) { - $duration = $wavCaptcha->getDataSize() / ($wavCaptcha->getBitsPerSample() / 8) / - $wavCaptcha->getNumChannels() / $wavCaptcha->getSampleRate(); - $duration = round($duration, 2); - $wavNoise = new WavFile(); - $wavNoise->setIgnoreChunkSizes(true); - $noiseData = $this->getSoxNoiseData($duration, - $wavCaptcha->getNumChannels(), - $wavCaptcha->getSampleRate(), - $wavCaptcha->getBitsPerSample()); - $wavNoise->setWavData($noiseData, true); - - } else - */ - if ( ($noiseFile = $this->getRandomNoiseFile()) !== false) { - try { - $wavNoise = new WavFile($noiseFile, false); - } catch(Exception $ex) { - throw $ex; - } - - // start at a random offset from the beginning of the wavfile - // in order to add more randomness - - $randOffset = 0; - - if ($wavNoise->getNumBlocks() > 2 * $wavCaptcha->getNumBlocks()) { - $randBlock = mt_rand(0, $wavNoise->getNumBlocks() - $wavCaptcha->getNumBlocks()); - $wavNoise->readWavData($randBlock * $wavNoise->getBlockAlign(), $wavCaptcha->getNumBlocks() * $wavNoise->getBlockAlign()); - } else { - $wavNoise->readWavData(); - $randOffset = mt_rand(0, $wavNoise->getNumBlocks() - 1); - } - } - - if ($wavNoise !== false) { - $mixOpts = array('wav' => $wavNoise, - 'loop' => true, - 'blockOffset' => $randOffset); - - $filters[WavFile::FILTER_MIX] = $mixOpts; - $filters[WavFile::FILTER_NORMALIZE] = $this->audio_mix_normalization; - } - } - - if ($this->degrade_audio == true) { - // add random noise. - // any noise level below 95% is intensely distorted and not pleasant to the ear - $filters[WavFile::FILTER_DEGRADE] = mt_rand(95, 98) / 100.0; - } - - if (!empty($filters)) { - $wavCaptcha->filter($filters); // apply filters to captcha audio - } - - return $wavCaptcha->__toString(); - } - - /** - * Gets and returns the path to a random noise file from the audio noise directory. - * - * @return bool|string false if a file could not be found, or a string containing the path to the file. - */ - public function getRandomNoiseFile() - { - $return = false; - - if ( ($dh = opendir($this->audio_noise_path)) !== false ) { - $list = array(); - - while ( ($file = readdir($dh)) !== false ) { - if ($file == '.' || $file == '..') continue; - if (strtolower(substr($file, -4)) != '.wav') continue; - - $list[] = $file; - } - - closedir($dh); - - if (sizeof($list) > 0) { - $file = $list[array_rand($list, 1)]; - $return = $this->audio_noise_path . DIRECTORY_SEPARATOR . $file; - - if (!is_readable($return)) $return = false; - } - } - - return $return; - } - - /** - * Get a random effect or chain of effects to apply to a segment of the - * audio file. - * - * These effects should increase the randomness of the audio for - * a particular letter/number by modulating the signal. The SoX effects - * used are *bend*, *chorus*, *overdrive*, *pitch*, *reverb*, *tempo*, and - * *tremolo*. - * - * For each effect selected, random parameters are supplied to the effect. - * - * @param int $numEffects How many effects to chain together - * @return string A string of valid SoX effects and their respective options. - */ - protected function getSoxEffectChain($numEffects = 2) - { - $effectsList = array('bend', 'chorus', 'overdrive', 'pitch', 'reverb', 'tempo', 'tremolo'); - $effects = array_rand($effectsList, $numEffects); - $outEffects = array(); - - if (!is_array($effects)) $effects = array($effects); - - foreach($effects as $effect) { - $effect = $effectsList[$effect]; - - switch($effect) - { - case 'bend': - $delay = mt_rand(0, 15) / 100.0; - $cents = mt_rand(-120, 120); - $dur = mt_rand(75, 400) / 100.0; - $outEffects[] = "$effect $delay,$cents,$dur"; - break; - - case 'chorus': - $gainIn = mt_rand(75, 90) / 100.0; - $gainOut = mt_rand(70, 95) / 100.0; - $chorStr = "$effect $gainIn $gainOut"; - - for ($i = 0; $i < mt_rand(2, 3); ++$i) { - $delay = mt_rand(20, 100); - $decay = mt_rand(10, 100) / 100.0; - $speed = mt_rand(20, 50) / 100.0; - $depth = mt_rand(150, 250) / 100.0; - - $chorStr .= " $delay $decay $speed $depth -s"; - } - - $outEffects[] = $chorStr; - break; - - case 'overdrive': - $gain = mt_rand(5, 25); - $color = mt_rand(20, 70); - $outEffects[] = "$effect $gain $color"; - break; - - case 'pitch': - $cents = mt_rand(-300, 300); - $outEffects[] = "$effect $cents"; - break; - - case 'reverb': - $reverberance = mt_rand(20, 80); - $damping = mt_rand(10, 80); - $scale = mt_rand(85, 100); - $depth = mt_rand(90, 100); - $predelay = mt_rand(0, 5); - $outEffects[] = "$effect $reverberance $damping $scale $depth $predelay"; - break; - - case 'tempo': - $factor = mt_rand(65, 135) / 100.0; - $outEffects[] = "$effect -s $factor"; - break; - - case 'tremolo': - $hz = mt_rand(10, 30); - $depth = mt_rand(40, 85); - $outEffects[] = "$effect $hz $depth"; - break; - } - } - - return implode(' ', $outEffects); - } - - /** - * This function is not yet used. - * - * Generate random background noise from sweeping oscillators - * - * @param float $duration How long in seconds the generated sound will be - * @param int $numChannels Number of channels in output wav - * @param int $sampleRate Sample rate of output wav - * @param int $bitRate Bits per sample (8, 16, 24) - * @return string Audio data in wav format - */ - protected function getSoxNoiseData($duration, $numChannels, $sampleRate, $bitRate) - { - $shapes = array('sine', 'square', 'triangle', 'sawtooth', 'trapezium'); - $steps = array(':', '+', '/', '-'); - $selShapes = array_rand($shapes, 2); - $selSteps = array_rand($steps, 2); - $sweep0 = array(); - $sweep0[0] = mt_rand(100, 700); - $sweep0[1] = mt_rand(1500, 2500); - $sweep1 = array(); - $sweep1[0] = mt_rand(500, 1000); - $sweep1[1] = mt_rand(1200, 2000); - - if (mt_rand(0, 10) % 2 == 0) - $sweep0 = array_reverse($sweep0); - - if (mt_rand(0, 10) % 2 == 0) - $sweep1 = array_reverse($sweep1); - - $cmd = sprintf("%s -c %d -r %d -b %d -n -t wav - synth noise create vol 0.3 synth %.2f %s mix %d%s%d vol 0.3 synth %.2f %s fmod %d%s%d vol 0.3", - $this->sox_binary_path, - $numChannels, - $sampleRate, - $bitRate, - $duration, - $shapes[$selShapes[0]], - $sweep0[0], - $steps[$selSteps[0]], - $sweep0[1], - $duration, - $shapes[$selShapes[1]], - $sweep1[0], - $steps[$selSteps[1]], - $sweep1[1] - ); - $data = `$cmd`; - - return $data; - } - - /** - * Convert WAV data to MP3 using the Lame MP3 encoder binary - * - * @param string $data Contents of the WAV file to convert - * @return string MP3 file data - */ - protected function wavToMp3($data) - { - if (!file_exists(self::$lame_binary_path) || !is_executable(self::$lame_binary_path)) { - throw new Exception('Lame binary "' . $this->lame_binary_path . '" does not exist or is not executable'); - } - - // size of wav data input - $size = strlen($data); - - // file descriptors for reading and writing to the Lame process - $descriptors = array( - 0 => array('pipe', 'r'), // stdin - 1 => array('pipe', 'w'), // stdout - 2 => array('pipe', 'a'), // stderr - ); - - if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { - // workaround for Windows conversion - // writing to STDIN seems to hang indefinitely after writing approximately 0xC400 bytes - $wavinput = tempnam(sys_get_temp_dir(), 'wav'); - if (!$wavinput) { - throw new Exception('Failed to create temporary file for WAV to MP3 conversion'); - } - file_put_contents($wavinput, $data); - $size = 0; - } else { - $wavinput = '-'; // stdin - } - - // Mono, variable bit rate, 32 kHz sampling rate, read WAV from stdin, write MP3 to stdout - $cmd = sprintf("%s -m m -v -b 32 %s -", self::$lame_binary_path, $wavinput); - $proc = proc_open($cmd, $descriptors, $pipes); - - if (!is_resource($proc)) { - throw new Exception('Failed to open process for MP3 encoding'); - } - - stream_set_blocking($pipes[0], 0); // set stdin to be non-blocking - - for ($written = 0; $written < $size; $written += $len) { - // write to stdin until all WAV data is written - $len = fwrite($pipes[0], substr($data, $written, 0x20000)); - - if ($len === 0) { - // fwrite wrote no data, make sure process is still alive, otherwise wait for it to process - $status = proc_get_status($proc); - if ($status['running'] === false) break; - usleep(25000); - } else if ($written < $size) { - // couldn't write all data, small pause and try again - usleep(10000); - } else if ($len === false) { - // fwrite failed, should not happen - break; - } - } - - fclose($pipes[0]); - - $data = stream_get_contents($pipes[1]); - $err = trim(stream_get_contents($pipes[2])); - - fclose($pipes[1]); - fclose($pipes[2]); - - $return = proc_close($proc); - - if ($wavinput != '-') unlink($wavinput); // delete temp file on Windows - - if ($return !== 0) { - throw new Exception("Failed to convert WAV to MP3. Shell returned ({$return}): {$err}"); - } else if ($written < $size) { - throw new Exception('Failed to convert WAV to MP3. Failed to write all data to encoder'); - } - - return $data; - } - - /** - * Return a wav file saying there was an error generating file - * - * @return string The binary audio contents - */ - protected function audioError() - { - return @file_get_contents(dirname(__FILE__) . '/audio/en/error.wav'); - } - - /** - * Checks to see if headers can be sent and if any error has been output - * to the browser - * - * @return bool true if it is safe to send headers, false if not - */ - protected function canSendHeaders() - { - if (headers_sent()) { - // output has been flushed and headers have already been sent - return false; - } else if (strlen((string)ob_get_contents()) > 0) { - // headers haven't been sent, but there is data in the buffer that will break image and audio data - return false; - } - - return true; - } - - /** - * Return a random float between 0 and 0.9999 - * - * @return float Random float between 0 and 0.9999 - */ - function frand() - { - return 0.0001 * mt_rand(0,9999); - } - - /** - * Convert an html color code to a Securimage_Color - * @param string $color - * @param Securimage_Color|string $default The defalt color to use if $color is invalid - */ - protected function initColor($color, $default) - { - if ($color == null) { - return new Securimage_Color($default); - } else if (is_string($color)) { - try { - return new Securimage_Color($color); - } catch(Exception $e) { - return new Securimage_Color($default); - } - } else if (is_array($color) && sizeof($color) == 3) { - return new Securimage_Color($color[0], $color[1], $color[2]); - } else { - return new Securimage_Color($default); - } - } - - /** - * The error handling function used when outputting captcha image or audio. - * - * This error handler helps determine if any errors raised would - * prevent captcha image or audio from displaying. If they have - * no effect on the output buffer or headers, true is returned so - * the script can continue processing. - * - * See https://github.com/dapphp/securimage/issues/15 - * - * @param int $errno PHP error number - * @param string $errstr String description of the error - * @param string $errfile File error occurred in - * @param int $errline Line the error occurred on in file - * @param array $errcontext Additional context information - * @return boolean true if the error was handled, false if PHP should handle the error - */ - public function errorHandler($errno, $errstr, $errfile = '', $errline = 0, $errcontext = array()) - { - // get the current error reporting level - $level = error_reporting(); - - // if error was supressed or $errno not set in current error level - if ($level == 0 || ($level & $errno) == 0) { - return true; - } - - return false; - } -} - - -/** - * Color object for Securimage CAPTCHA - * - * @version 3.0 - * @since 2.0 - * @package Securimage - * @subpackage classes - * - */ -class Securimage_Color -{ - /** - * Red value (0-255) - * @var int - */ - public $r; - - /** - * Gree value (0-255) - * @var int - */ - public $g; - - /** - * Blue value (0-255) - * @var int - */ - public $b; - - /** - * Create a new Securimage_Color object. - * - * Constructor expects 1 or 3 arguments. - * - * When passing a single argument, specify the color using HTML hex format. - * - * When passing 3 arguments, specify each RGB component (from 0-255) - * individually. - * - * Examples: - * - * $color = new Securimage_Color('#0080FF'); - * $color = new Securimage_Color(0, 128, 255); - * - * @param string $color The html color code to use - * @throws Exception If any color value is not valid - */ - public function __construct($color = '#ffffff') - { - $args = func_get_args(); - - if (sizeof($args) == 0) { - $this->r = 255; - $this->g = 255; - $this->b = 255; - } else if (sizeof($args) == 1) { - // set based on html code - if (substr($color, 0, 1) == '#') { - $color = substr($color, 1); - } - - if (strlen($color) != 3 && strlen($color) != 6) { - throw new InvalidArgumentException( - 'Invalid HTML color code passed to Securimage_Color' - ); - } - - $this->constructHTML($color); - } else if (sizeof($args) == 3) { - $this->constructRGB($args[0], $args[1], $args[2]); - } else { - throw new InvalidArgumentException( - 'Securimage_Color constructor expects 0, 1 or 3 arguments; ' . sizeof($args) . ' given' - ); - } - } - - /** - * Construct from an rgb triplet - * - * @param int $red The red component, 0-255 - * @param int $green The green component, 0-255 - * @param int $blue The blue component, 0-255 - */ - protected function constructRGB($red, $green, $blue) - { - if ($red < 0) $red = 0; - if ($red > 255) $red = 255; - if ($green < 0) $green = 0; - if ($green > 255) $green = 255; - if ($blue < 0) $blue = 0; - if ($blue > 255) $blue = 255; - - $this->r = $red; - $this->g = $green; - $this->b = $blue; - } - - /** - * Construct from an html hex color code - * - * @param string $color - */ - protected function constructHTML($color) - { - if (strlen($color) == 3) { - $red = str_repeat(substr($color, 0, 1), 2); - $green = str_repeat(substr($color, 1, 1), 2); - $blue = str_repeat(substr($color, 2, 1), 2); - } else { - $red = substr($color, 0, 2); - $green = substr($color, 2, 2); - $blue = substr($color, 4, 2); - } - - $this->r = hexdec($red); - $this->g = hexdec($green); - $this->b = hexdec($blue); - } -} + + * @version 3.6.4 (Mar 3, 2016) + * @package Securimage + * + */ + +/** + + ChangeLog + 3.6.4 + - Fix XSS vulnerability in example_form.ajax.php (Discovered by RedTeam. advisory rt-sa-2016-002) + - Update example_form.ajax.php to use Securimage::getCaptchaHtml() + + 3.6.3 + - Add support for multibyte wordlist files + - Fix code generation issues with UTF-8 charsets + - Add parameter to getCaptchaHtml() method to control display components of captcha HTML + - Fix database audio storage issue with multiple namespaces + + 3.6.2 + - Support HTTP range requests with audio playback (iOS requirement) + - Add optional config.inc.php for storing global configuration settings + + 3.6.1 + - Fix copyElement bug in securimage.js for IE Flash fallback + + 3.6 + - Implement CAPTCHA audio using HTML5