Liferay.Loader.define("app-builder-workflow-web@1.0.40/js/pages/entry/EditEntry.es", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/button', '@frontend-taglib-clay$clayui/tooltip', 'app-builder-web/js/AppContext.es', 'app-builder-web/js/components/control-menu/ControlMenu.es', 'app-builder-web/js/components/loading/Loading.es', 'app-builder-web/js/hooks/useDataDefinition.es', 'app-builder-web/js/utils/client.es', 'app-builder-web/js/utils/lang.es', 'app-builder-web/js/utils/toast.es', 'frontend-js-react-web', 'frontend-js-web', 'frontend-js-react-web$react', 'frontend-js-react-web$react-dom', '../../components/workflow-info-bar/WorkflowInfoBar.es', '../../hooks/useAppWorkflow.es', '../../hooks/useDDMForms.es', '../../hooks/useDataLayouts.es', '../../hooks/useDataRecordApps.es', './ReassignEntryModal.es'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    function _typeof(obj) {
      "@babel/helpers - typeof";
      if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
        _typeof = function _typeof(obj) {
          return typeof obj;
        };
      } else {
        _typeof = function _typeof(obj) {
          return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
      }return _typeof(obj);
    }

    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.default = EditEntry;

    var _button = _interopRequireWildcard(require("@frontend-taglib-clay$clayui/button"));

    var _tooltip = require("@frontend-taglib-clay$clayui/tooltip");

    var _AppContext = require("app-builder-web/js/AppContext.es");

    var _ControlMenu = require("app-builder-web/js/components/control-menu/ControlMenu.es");

    var _Loading = require("app-builder-web/js/components/loading/Loading.es");

    var _useDataDefinition2 = _interopRequireDefault(require("app-builder-web/js/hooks/useDataDefinition.es"));

    var _client = require("app-builder-web/js/utils/client.es");

    var _lang = require("app-builder-web/js/utils/lang.es");

    var _toast = require("app-builder-web/js/utils/toast.es");

    var _frontendJsReactWeb = require("frontend-js-react-web");

    var _frontendJsWeb = require("frontend-js-web");

    var _react = _interopRequireWildcard(require("frontend-js-react-web$react"));

    var _reactDom = require("frontend-js-react-web$react-dom");

    var _WorkflowInfoBar = _interopRequireDefault(require("../../components/workflow-info-bar/WorkflowInfoBar.es"));

    var _useAppWorkflow = _interopRequireDefault(require("../../hooks/useAppWorkflow.es"));

    var _useDDMForms = _interopRequireWildcard(require("../../hooks/useDDMForms.es"));

    var _useDataLayouts = _interopRequireDefault(require("../../hooks/useDataLayouts.es"));

    var _useDataRecordApps = _interopRequireDefault(require("../../hooks/useDataRecordApps.es"));

    var _ReassignEntryModal = _interopRequireDefault(require("./ReassignEntryModal.es"));

    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { default: obj };
    }

    function _getRequireWildcardCache() {
      if (typeof WeakMap !== "function") return null;var cache = new WeakMap();_getRequireWildcardCache = function _getRequireWildcardCache() {
        return cache;
      };return cache;
    }

    function _interopRequireWildcard(obj) {
      if (obj && obj.__esModule) {
        return obj;
      }if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
        return { default: obj };
      }var cache = _getRequireWildcardCache();if (cache && cache.has(obj)) {
        return cache.get(obj);
      }var newObj = {};var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;if (desc && (desc.get || desc.set)) {
            Object.defineProperty(newObj, key, desc);
          } else {
            newObj[key] = obj[key];
          }
        }
      }newObj.default = obj;if (cache) {
        cache.set(obj, newObj);
      }return newObj;
    }

    function _extends() {
      _extends = Object.assign || function (target) {
        for (var i = 1; i < arguments.length; i++) {
          var source = arguments[i];for (var key in source) {
            if (Object.prototype.hasOwnProperty.call(source, key)) {
              target[key] = source[key];
            }
          }
        }return target;
      };return _extends.apply(this, arguments);
    }

    function ownKeys(object, enumerableOnly) {
      var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);if (enumerableOnly) symbols = symbols.filter(function (sym) {
          return Object.getOwnPropertyDescriptor(object, sym).enumerable;
        });keys.push.apply(keys, symbols);
      }return keys;
    }

    function _objectSpread(target) {
      for (var i = 1; i < arguments.length; i++) {
        var source = arguments[i] != null ? arguments[i] : {};if (i % 2) {
          ownKeys(Object(source), true).forEach(function (key) {
            _defineProperty(target, key, source[key]);
          });
        } else if (Object.getOwnPropertyDescriptors) {
          Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
        } else {
          ownKeys(Object(source)).forEach(function (key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
          });
        }
      }return target;
    }

    function _defineProperty(obj, key, value) {
      if (key in obj) {
        Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true });
      } else {
        obj[key] = value;
      }return obj;
    }

    function _objectWithoutProperties(source, excluded) {
      if (source == null) return {};var target = _objectWithoutPropertiesLoose(source, excluded);var key, i;if (Object.getOwnPropertySymbols) {
        var sourceSymbolKeys = Object.getOwnPropertySymbols(source);for (i = 0; i < sourceSymbolKeys.length; i++) {
          key = sourceSymbolKeys[i];if (excluded.indexOf(key) >= 0) continue;if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;target[key] = source[key];
        }
      }return target;
    }

    function _objectWithoutPropertiesLoose(source, excluded) {
      if (source == null) return {};var target = {};var sourceKeys = Object.keys(source);var key, i;for (i = 0; i < sourceKeys.length; i++) {
        key = sourceKeys[i];if (excluded.indexOf(key) >= 0) continue;target[key] = source[key];
      }return target;
    }

    function _slicedToArray(arr, i) {
      return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
    }

    function _nonIterableRest() {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }

    function _iterableToArrayLimit(arr, i) {
      if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
        return;
      }var _arr = [];var _n = true;var _d = false;var _e = undefined;try {
        for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
          _arr.push(_s.value);if (i && _arr.length === i) break;
        }
      } catch (err) {
        _d = true;_e = err;
      } finally {
        try {
          if (!_n && _i["return"] != null) _i["return"]();
        } finally {
          if (_d) throw _e;
        }
      }return _arr;
    }

    function _arrayWithHoles(arr) {
      if (Array.isArray(arr)) return arr;
    }

    var WorkflowInfoPortal = function WorkflowInfoPortal(_ref) {
      var _portalElement;

      var children = _ref.children;
      var portalElementId = 'workflowInfoBar';
      var targetElement = document.getElementById('edit-app-content');
      var portalElement = document.getElementById(portalElementId);
      var portalContainer = (_portalElement = portalElement) === null || _portalElement === void 0 ? void 0 : _portalElement.parentNode;

      if (portalContainer) {
        portalContainer.removeChild(portalElement);
      } else {
        portalContainer = targetElement === null || targetElement === void 0 ? void 0 : targetElement.parentNode;
      }

      portalElement = document.createElement('div');
      portalElement.id = portalElementId;
      portalContainer.insertBefore(portalElement, targetElement);
      return (/*#__PURE__*/(0, _reactDom.createPortal)(children, portalElement)
      );
    };

    function EditEntry(_ref2) {
      var _dataRecordApps$dataR;

      var dataDefinitionId = _ref2.dataDefinitionId,
          dataRecordId = _ref2.dataRecordId,
          redirect = _ref2.redirect,
          userLanguageId = _ref2.userLanguageId;

      var _useContext = (0, _react.useContext)(_AppContext.AppContext),
          appId = _useContext.appId,
          basePortletURL = _useContext.basePortletURL,
          baseResourceURL = _useContext.baseResourceURL,
          dataLayoutIds = _useContext.dataLayoutIds,
          namespace = _useContext.namespace;

      var _useDataDefinition = (0, _useDataDefinition2.default)(dataDefinitionId),
          availableLanguageIds = _useDataDefinition.availableLanguageIds,
          defaultLanguageId = _useDataDefinition.defaultLanguageId;

      var dataLayouts = (0, _useDataLayouts.default)(dataLayoutIds);
      var dataRecordApps = (0, _useDataRecordApps.default)(appId, (0, _react.useMemo)(function () {
        return [dataRecordId];
      }, [dataRecordId]));
      var delay = (0, _frontendJsReactWeb.useTimeout)();
      var appWorkflow = (0, _useAppWorkflow.default)(appId);

      var _ref3 = (_dataRecordApps$dataR = dataRecordApps[dataRecordId]) !== null && _dataRecordApps$dataR !== void 0 ? _dataRecordApps$dataR : appWorkflow,
          appVersion = _ref3.appVersion,
          appWorkflowDefinitionId = _ref3.appWorkflowDefinitionId,
          _ref3$appWorkflowStat = _ref3.appWorkflowStates;

      _ref3$appWorkflowStat = _ref3$appWorkflowStat === void 0 ? [] : _ref3$appWorkflowStat;

      var _ref3$appWorkflowStat2 = _slicedToArray(_ref3$appWorkflowStat, 1),
          _ref3$appWorkflowStat3 = _ref3$appWorkflowStat2[0],
          initialState = _ref3$appWorkflowStat3 === void 0 ? {} : _ref3$appWorkflowStat3,
          appWorkflowTasks = _ref3.appWorkflowTasks;

      var _initialState$appWork = initialState.appWorkflowTransitions;
      _initialState$appWork = _initialState$appWork === void 0 ? [] : _initialState$appWork;

      var _initialState$appWork2 = _slicedToArray(_initialState$appWork, 1),
          _initialState$appWork3 = _initialState$appWork2[0],
          transition = _initialState$appWork3 === void 0 ? {} : _initialState$appWork3;

      var _useState = (0, _react.useState)(true),
          _useState2 = _slicedToArray(_useState, 2),
          isLoading = _useState2[0],
          setLoading = _useState2[1];

      var _useState3 = (0, _react.useState)(false),
          _useState4 = _slicedToArray(_useState3, 2),
          isModalVisible = _useState4[0],
          setModalVisible = _useState4[1];

      var _useState5 = (0, _react.useState)(false),
          _useState6 = _slicedToArray(_useState5, 2),
          transitioning = _useState6[0],
          setTransitioning = _useState6[1];

      var _useState7 = (0, _react.useState)(),
          _useState8 = _slicedToArray(_useState7, 2),
          workflowInfo = _useState8[0],
          setWorkflowInfo = _useState8[1];

      var actionButtons = [];
      var isEdit = dataRecordId !== '0';
      var pageTitle = dataRecordId !== '0' ? Liferay.Language.get('edit-entry') : Liferay.Language.get('add-entry');
      var ddmForms = (0, _useDDMForms.default)(dataLayoutIds.map(function (dataLayoutId) {
        return "".concat(namespace, "container").concat(dataLayoutId);
      }));
      var doFetch = (0, _react.useCallback)(function () {
        var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
            newAssignee = _ref4.newAssignee;

        setLoading(true);

        if (appWorkflowDefinitionId) {
          if (isEdit) {
            var getWorkflowInfo = function getWorkflowInfo() {
              (0, _client.getItem)("/o/portal-workflow-metrics/v1.0/processes/".concat(appWorkflowDefinitionId, "/instances"), {
                classPKs: [dataRecordId]
              }).then(function (_ref5) {
                var items = _ref5.items;
                var retryCount = 0;

                if (items.length) {
                  var _items$pop = items.pop(),
                      id = _items$pop.id,
                      instance = _objectWithoutProperties(_items$pop, ["id"]);

                  var _ref6 = instance.assignees || [],
                      _ref7 = _slicedToArray(_ref6, 1),
                      assignee = _ref7[0];

                  if (newAssignee && newAssignee.id !== (assignee === null || assignee === void 0 ? void 0 : assignee.id) && retryCount <= 5) {
                    retryCount++;
                    return delay(getWorkflowInfo, 1000);
                  }

                  var assignedToUser = Number(themeDisplay.getUserId()) === (assignee === null || assignee === void 0 ? void 0 : assignee.id);
                  setLoading(false);
                  setWorkflowInfo(_objectSpread(_objectSpread({}, instance), {}, {
                    appVersion: appVersion,
                    canReassign: assignedToUser || (assignee === null || assignee === void 0 ? void 0 : assignee.reviewer),
                    instanceId: id,
                    tasks: appWorkflowTasks
                  }));
                } else {
                  setLoading(false);
                }
              });
            };

            getWorkflowInfo();
          } else {
            setLoading(false);
          }
        }
      }, // eslint-disable-next-line react-hooks/exhaustive-deps
      [appWorkflowDefinitionId, dataRecordId, isEdit]);
      var onCancel = (0, _react.useCallback)(function () {
        if (redirect) {
          Liferay.Util.navigate(redirect);
        } else {
          Liferay.Util.navigate(basePortletURL);
        }
      }, [basePortletURL, redirect]);
      var saveDataRecord = (0, _react.useCallback)(function (_ref8, dataRecord) {
        var transitionName = _ref8.transitionName;
        var params = {
          appBuilderAppId: appId,
          dataRecord: JSON.stringify(dataRecord),
          dataRecordId: dataRecordId
        };
        var resource = "".concat(isEdit ? 'update' : 'add', "_data_record");

        if (workflowInfo) {
          var instanceId = workflowInfo.instanceId,
              _workflowInfo$tasks = workflowInfo.tasks,
              tasks = _workflowInfo$tasks === void 0 ? [] : _workflowInfo$tasks,
              _workflowInfo$taskNam = _slicedToArray(workflowInfo.taskNames, 1),
              taskName = _workflowInfo$taskNam[0]; //avoids enter submission putting primary action


          var _ref9 = tasks.find(function (_ref10) {
            var name = _ref10.name;
            return name === taskName;
          }) || {},
              _ref9$appWorkflowTran = _ref9.appWorkflowTransitions,
              transitions = _ref9$appWorkflowTran === void 0 ? [] : _ref9$appWorkflowTran;

          var action = transitions.find(function (_ref11) {
            var primary = _ref11.primary;
            return primary;
          });
          params.taskName = taskName;
          params.transitionName = transitionName !== null && transitionName !== void 0 ? transitionName : action.name;
          params.workflowInstanceId = instanceId;
        }

        (0, _frontendJsWeb.fetch)((0, _frontendJsWeb.createResourceURL)(baseResourceURL, {
          p_p_resource_id: "/app_builder/".concat(resource)
        }), {
          body: new URLSearchParams(Liferay.Util.ns(namespace, params)),
          method: 'POST'
        }).then(function () {
          (0, _toast.successToast)(isEdit ? Liferay.Language.get('an-entry-was-updated') : Liferay.Language.get('an-entry-was-added'));
          onCancel();
        }).catch(function () {
          (0, _toast.errorToast)();
          setTransitioning(false);
        });
      }, [appId, baseResourceURL, dataRecordId, isEdit, namespace, onCancel, workflowInfo]);
      var validateForms = (0, _useDDMForms.useDDMFormsValidation)(ddmForms, defaultLanguageId, availableLanguageIds);
      var onSubmit = (0, _react.useCallback)(function (event) {
        setTransitioning(true);
        validateForms(event).then(function (dataRecord) {
          return saveDataRecord(event, dataRecord);
        }).catch(function () {
          return setTransitioning(false);
        });
      }, [saveDataRecord, validateForms]);
      (0, _useDDMForms.useDDMFormsSubmit)(ddmForms, onSubmit);
      (0, _react.useEffect)(function () {
        if (dataLayoutIds.length === ddmForms.length) {
          ddmForms.forEach(function (ddmForm) {
            var ddmReactForm = ddmForm.reactComponentRef.current;
            ddmReactForm.updateEditingLanguageId({
              editingLanguageId: userLanguageId,
              preserveValue: true
            });
          });
        } // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [ddmForms.length, userLanguageId]);
      (0, _react.useEffect)(function () {
        if (dataLayoutIds.length === dataLayouts.length) {
          dataLayouts.forEach(function (_ref12) {
            var id = _ref12.id,
                name = _ref12.name;
            var formName = document.getElementById("".concat(id, "_name"));

            if (formName) {
              formName.innerText = (0, _lang.getLocalizedUserPreferenceValue)(name, userLanguageId, defaultLanguageId);
            }
          });
        } // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [dataLayouts.length, userLanguageId]);
      (0, _react.useEffect)(function () {
        doFetch();
      }, [doFetch]);

      if (workflowInfo) {
        var _workflowInfo$assigne = workflowInfo.assignees,
            assignees = _workflowInfo$assigne === void 0 ? [] : _workflowInfo$assigne,
            completed = workflowInfo.completed,
            _workflowInfo$tasks2 = workflowInfo.tasks,
            tasks = _workflowInfo$tasks2 === void 0 ? [] : _workflowInfo$tasks2,
            _workflowInfo$taskNam2 = workflowInfo.taskNames,
            taskNames = _workflowInfo$taskNam2 === void 0 ? [] : _workflowInfo$taskNam2;

        if (!completed) {
          var stepName = taskNames[0];
          pageTitle = "".concat(stepName);

          var _ref13 = tasks.find(function (_ref14) {
            var name = _ref14.name;
            return name === stepName;
          }) || {},
              _ref13$appWorkflowTra = _ref13.appWorkflowTransitions,
              appWorkflowTransitions = _ref13$appWorkflowTra === void 0 ? [] : _ref13$appWorkflowTra;

          var userId = Number(themeDisplay.getUserId());
          var assigned = assignees.findIndex(function (_ref15) {
            var id = _ref15.id;
            return id === userId;
          }) > -1;

          if (assigned) {
            appWorkflowTransitions.sort(function (actionA, actionB) {
              return actionB.primary - actionA.primary;
            });
            appWorkflowTransitions.forEach(function (_ref16, index) {
              var name = _ref16.name,
                  primary = _ref16.primary;
              actionButtons[index] = /*#__PURE__*/_react.default.createElement(_button.default, {
                disabled: transitioning,
                displayType: primary ? 'primary' : 'secondary',
                key: index,
                onClick: function onClick() {
                  return onSubmit({
                    transitionName: name
                  });
                }
              }, name);
            });
          }
        }
      } else {
        actionButtons.push( /*#__PURE__*/_react.default.createElement(_button.default, {
          disabled: transitioning,
          displayType: "primary",
          key: 0,
          onClick: function onClick() {
            return onSubmit({
              transitionName: name
            });
          }
        }, transition.name || Liferay.Language.get('submit')));
      }

      return (/*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_ControlMenu.ControlMenuBase, {
          backURL: redirect ? redirect : "".concat(basePortletURL, "/#/"),
          title: pageTitle,
          url: location.href
        }), /*#__PURE__*/_react.default.createElement(_Loading.Loading, {
          isLoading: isLoading
        }, workflowInfo && /*#__PURE__*/_react.default.createElement(WorkflowInfoPortal, null, /*#__PURE__*/_react.default.createElement("div", {
          className: "d-flex justify-content-center mt-4"
        }, /*#__PURE__*/_react.default.createElement(_WorkflowInfoBar.default, _extends({
          className: "bar-sm"
        }, workflowInfo, {
          hideColumns: ['step']
        })), (workflowInfo === null || workflowInfo === void 0 ? void 0 : workflowInfo.canReassign) && /*#__PURE__*/_react.default.createElement(_tooltip.ClayTooltipProvider, null, /*#__PURE__*/_react.default.createElement(_button.ClayButtonWithIcon, {
          className: "ml-2",
          "data-tooltip-align": "bottom",
          "data-tooltip-delay": "200",
          displayType: "secondary",
          onClick: function onClick() {
            return setModalVisible(true);
          },
          small: true,
          symbol: "change",
          title: Liferay.Language.get('assign-to')
        })))), /*#__PURE__*/_react.default.createElement(_button.default.Group, {
          className: "app-builder-form-buttons",
          spaced: true
        }, actionButtons, /*#__PURE__*/_react.default.createElement(_button.default, {
          disabled: transitioning,
          displayType: "secondary",
          onClick: onCancel
        }, Liferay.Language.get('cancel')))), isModalVisible && /*#__PURE__*/_react.default.createElement(_ReassignEntryModal.default, {
          entry: workflowInfo,
          onCloseModal: function onCloseModal() {
            return setModalVisible(false);
          },
          refetch: doFetch
        }))
      );
    }
    //# sourceMappingURL=EditEntry.es.js.map
  }
});
//# sourceMappingURL=EditEntry.es.js.map