Liferay.Loader.define("app-builder-workflow-web@1.0.42/js/pages/entry/ViewEntry.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/hooks/useQuery.es', 'app-builder-web/js/pages/entry/ViewEntry.es', 'app-builder-web/js/pages/entry/ViewEntryUpperToolbar.es', 'app-builder-web/js/utils/client.es', 'app-builder-web/js/utils/lang.es', 'app-builder-web/js/utils/toast.es', 'app-builder-web/js/utils/utils.es', 'frontend-js-react-web', 'frontend-js-react-web$react', '../../components/workflow-info-bar/WorkflowInfoBar.es', '../../hooks/useDataLayouts.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 = ViewEntry;

    var _button = 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 = _interopRequireDefault(require("app-builder-web/js/components/control-menu/ControlMenu.es"));

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

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

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

    var _ViewEntry = require("app-builder-web/js/pages/entry/ViewEntry.es");

    var _ViewEntryUpperToolbar = _interopRequireDefault(require("app-builder-web/js/pages/entry/ViewEntryUpperToolbar.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 _utils = require("app-builder-web/js/utils/utils.es");

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

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

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

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

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

    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 _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { default: 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 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 _toConsumableArray(arr) {
      return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
    }

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

    function _iterableToArray(iter) {
      if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
    }

    function _arrayWithoutHoles(arr) {
      if (Array.isArray(arr)) {
        for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
          arr2[i] = arr[i];
        }return arr2;
      }
    }

    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;
    }

    function ViewEntry(_ref) {
      var _workflowInfo$assigne, _workflowInfo$assigne2;

      var history = _ref.history,
          entryIndex = _ref.match.params.entryIndex;

      var _useContext = (0, _react.useContext)(_AppContext.AppContext),
          appId = _useContext.appId,
          dataDefinitionId = _useContext.dataDefinitionId,
          dataLayoutId = _useContext.dataLayoutId,
          dataListViewId = _useContext.dataListViewId,
          userLanguageId = _useContext.userLanguageId;

      var _useState = (0, _react.useState)([]),
          _useState2 = _slicedToArray(_useState, 2),
          dataLayoutIds = _useState2[0],
          setDataLayoutIds = _useState2[1];

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

      var getDataLayoutIds = function getDataLayoutIds(_ref2) {
        var completed = _ref2.completed,
            _ref2$taskNames = _ref2.taskNames,
            taskNames = _ref2$taskNames === void 0 ? [] : _ref2$taskNames,
            tasks = _ref2.tasks;
        var initialIds = [];

        if (!completed) {
          tasks = tasks.filter(function (_ref3) {
            var name = _ref3.name;
            return taskNames.includes(name);
          });
        } else {
          initialIds.push(Number(dataLayoutId));
        }

        return tasks.reduce(function (dataLayoutIds, _ref4) {
          var appWorkflowDataLayoutLinks = _ref4.appWorkflowDataLayoutLinks;
          return [].concat(_toConsumableArray(dataLayoutIds), _toConsumableArray(appWorkflowDataLayoutLinks === null || appWorkflowDataLayoutLinks === void 0 ? void 0 : appWorkflowDataLayoutLinks.reduce(function (stepDataLayoutIds, _ref5) {
            var dataLayoutId = _ref5.dataLayoutId;
            return dataLayoutIds.includes(dataLayoutId) ? stepDataLayoutIds : [].concat(_toConsumableArray(stepDataLayoutIds), [dataLayoutId]);
          }, [])));
        }, initialIds);
      };

      var dataDefinition = (0, _useDataDefinition.default)(dataDefinitionId);
      var dataLayouts = (0, _useDataLayouts.default)(dataLayoutIds);
      var delay = (0, _frontendJsReactWeb.useTimeout)();

      var _useState5 = (0, _react.useState)({
        dataRecord: {},
        isFetching: true,
        page: 1,
        totalCount: 0,
        workflowInfo: null
      }),
          _useState6 = _slicedToArray(_useState5, 2),
          _useState6$ = _useState6[0],
          dataRecord = _useState6$.dataRecord,
          isFetching = _useState6$.isFetching,
          page = _useState6$.page,
          totalCount = _useState6$.totalCount,
          workflowInfo = _useState6$.workflowInfo,
          setState = _useState6[1];

      var _dataRecord$dataRecor = dataRecord.dataRecordValues,
          dataRecordValues = _dataRecord$dataRecor === void 0 ? {} : _dataRecord$dataRecor,
          dataRecordId = dataRecord.id;

      var _useQuery = (0, _useQuery3.default)(history, {
        keywords: '',
        page: 1,
        sort: ''
      }),
          _useQuery2 = _slicedToArray(_useQuery, 1),
          query = _useQuery2[0];

      var previousQuery = (0, _frontendJsReactWeb.usePrevious)(query);
      var previousIndex = (0, _frontendJsReactWeb.usePrevious)(entryIndex);

      var doFetch = function doFetch() {
        var _ref6 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
            newAssignee = _ref6.newAssignee;

        setState({
          dataRecord: {},
          isFetching: true,
          page: 1,
          totalCount: 0,
          workflowInfo: null
        });
        (0, _client.getItem)("/o/data-engine/v2.0/data-definitions/".concat(dataDefinitionId, "/data-records"), _objectSpread(_objectSpread({}, query), {}, {
          dataListViewId: dataListViewId,
          page: entryIndex,
          pageSize: 1
        })).then(function (_ref7) {
          var _ref7$items = _ref7.items,
              items = _ref7$items === void 0 ? [] : _ref7$items,
              response = _objectWithoutProperties(_ref7, ["items"]);

          if (items.length) {
            var state = _objectSpread({
              dataRecord: items.pop(),
              isFetching: false,
              workflowInfo: null
            }, response);

            var dataRecordIds = [state.dataRecord.id];
            (0, _client.addItem)("/o/app-builder-workflow/v1.0/apps/".concat(appId, "/app-workflows/data-record-links"), {
              dataRecordIds: dataRecordIds
            }).then(function (_ref8) {
              var items = _ref8.items;

              if (items.length) {
                var _items$pop = items.pop(),
                    _items$pop$appWorkflo = _items$pop.appWorkflow,
                    appVersion = _items$pop$appWorkflo.appVersion,
                    appWorkflowDefinitionId = _items$pop$appWorkflo.appWorkflowDefinitionId,
                    tasks = _items$pop$appWorkflo.appWorkflowTasks;

                var retryCount = 0;

                var getWorkflowInfo = function getWorkflowInfo() {
                  (0, _client.getItem)("/o/portal-workflow-metrics/v1.0/processes/".concat(appWorkflowDefinitionId, "/instances"), {
                    classPKs: dataRecordIds
                  }).then(function (_ref9) {
                    var items = _ref9.items;

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

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

                      if (newAssignee && (newAssignee === null || newAssignee === void 0 ? void 0 : 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);
                      state.workflowInfo = _objectSpread(_objectSpread({}, instance), {}, {
                        appVersion: appVersion,
                        assignees: [newAssignee || assignee],
                        canReassign: assignedToUser || (assignee === null || assignee === void 0 ? void 0 : assignee.reviewer),
                        instanceId: id,
                        tasks: tasks
                      });
                      setDataLayoutIds(getDataLayoutIds(state.workflowInfo));
                    }

                    setState(function (prevState) {
                      return _objectSpread(_objectSpread({}, prevState), state);
                    });
                  });
                };

                getWorkflowInfo();
              } else {
                setDataLayoutIds([Number(dataLayoutId)]);
                setState(function (prevState) {
                  return _objectSpread(_objectSpread({}, prevState), state);
                });
              }
            }).catch(function () {
              setState(function (prevState) {
                return _objectSpread(_objectSpread({}, prevState), state);
              });
            });
          }
        }).catch(function () {
          setState(function (prevState) {
            return _objectSpread(_objectSpread({}, prevState), {}, {
              isFetching: false
            });
          });
          (0, _toast.errorToast)();
        });
      };

      (0, _react.useEffect)(function () {
        if (!(0, _utils.isEqualObjects)(query, previousQuery) || !previousIndex) {
          doFetch();
        } // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [entryIndex, query]);
      var showButtons = {
        update: (workflowInfo === null || workflowInfo === void 0 ? void 0 : workflowInfo.completed) === false && (workflowInfo === null || workflowInfo === void 0 ? void 0 : (_workflowInfo$assigne = workflowInfo.assignees) === null || _workflowInfo$assigne === void 0 ? void 0 : (_workflowInfo$assigne2 = _workflowInfo$assigne[0]) === null || _workflowInfo$assigne2 === void 0 ? void 0 : _workflowInfo$assigne2.id) === Number(themeDisplay.getUserId())
      };
      return (/*#__PURE__*/_react.default.createElement("div", {
          className: "view-entry"
        }, /*#__PURE__*/_react.default.createElement(_ControlMenu.default, {
          backURL: "../../",
          title: Liferay.Language.get('details-view')
        }), /*#__PURE__*/_react.default.createElement(_ViewEntryUpperToolbar.default, {
          additionalButtons: (workflowInfo === null || workflowInfo === void 0 ? void 0 : workflowInfo.canReassign) && /*#__PURE__*/_react.default.createElement(_tooltip.ClayTooltipProvider, null, /*#__PURE__*/_react.default.createElement(_button.ClayButtonWithIcon, {
            className: "mr-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')
          })),
          dataRecordId: dataRecordId,
          page: page,
          showButtons: showButtons,
          totalCount: totalCount
        }, workflowInfo && /*#__PURE__*/_react.default.createElement(_WorkflowInfoBar.default, workflowInfo)), /*#__PURE__*/_react.default.createElement(_Loading.Loading, {
          isLoading: isFetching
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "container"
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "justify-content-center row"
        }, /*#__PURE__*/_react.default.createElement("div", {
          className: "col-lg-8"
        }, dataRecordValues && dataLayouts.map(function (_ref12) {
          var _ref12$dataLayoutPage = _ref12.dataLayoutPages,
              dataLayoutPages = _ref12$dataLayoutPage === void 0 ? [] : _ref12$dataLayoutPage,
              dataLayout = _objectWithoutProperties(_ref12, ["dataLayoutPages"]);

          return (/*#__PURE__*/_react.default.createElement("div", {
              key: dataLayout.id
            }, /*#__PURE__*/_react.default.createElement("h3", null, (0, _lang.getLocalizedUserPreferenceValue)(dataLayout.name, userLanguageId, dataDefinition.defaultLanguageId)), dataLayoutPages.map(function (dataLayoutPage, index) {
              return (/*#__PURE__*/_react.default.createElement("div", {
                  className: "sheet",
                  key: index
                }, /*#__PURE__*/_react.default.createElement(_ViewEntry.ViewDataLayoutPageValues, {
                  dataDefinition: dataDefinition,
                  dataLayoutPage: dataLayoutPage,
                  dataRecordValues: dataRecordValues,
                  key: index
                }))
              );
            }))
          );
        }))))), isModalVisible && /*#__PURE__*/_react.default.createElement(_ReassignEntryModal.default, {
          entry: workflowInfo,
          onCloseModal: function onCloseModal() {
            return setModalVisible(false);
          },
          refetch: doFetch
        }))
      );
    }
    //# sourceMappingURL=ViewEntry.es.js.map
  }
});
//# sourceMappingURL=ViewEntry.es.js.map