Liferay.Loader.define("app-builder-workflow-web@1.0.42/js/pages/entry/ListEntries.es", ['module', 'exports', 'require', '@frontend-taglib-clay$clayui/label', 'app-builder-web/js/AppContext.es', 'app-builder-web/js/components/button/Button.es', 'app-builder-web/js/components/empty-state/NoPermissionState.es', 'app-builder-web/js/components/loading/Loading.es', 'app-builder-web/js/components/management-toolbar/ManagementToolbar.es', 'app-builder-web/js/components/management-toolbar/ManagementToolbarResultsBar.es', 'app-builder-web/js/components/management-toolbar/SearchContext.es', 'app-builder-web/js/components/table/TableWithPagination.es', 'app-builder-web/js/hooks/useDataListView.es', 'app-builder-web/js/hooks/useEntriesActions.es', 'app-builder-web/js/hooks/usePermissions.es', 'app-builder-web/js/hooks/useQuery.es', 'app-builder-web/js/pages/entry/utils.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', '../../hooks/useAppWorkflow.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 = ListEntries;

    var _label = _interopRequireDefault(require("@frontend-taglib-clay$clayui/label"));

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

    var _Button = _interopRequireDefault(require("app-builder-web/js/components/button/Button.es"));

    var _NoPermissionState = _interopRequireDefault(require("app-builder-web/js/components/empty-state/NoPermissionState.es"));

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

    var _ManagementToolbar = _interopRequireDefault(require("app-builder-web/js/components/management-toolbar/ManagementToolbar.es"));

    var _ManagementToolbarResultsBar = _interopRequireDefault(require("app-builder-web/js/components/management-toolbar/ManagementToolbarResultsBar.es"));

    var _SearchContext = _interopRequireWildcard(require("app-builder-web/js/components/management-toolbar/SearchContext.es"));

    var _TableWithPagination = _interopRequireDefault(require("app-builder-web/js/components/table/TableWithPagination.es"));

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

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

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

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

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

    var _useDataRecordApps = _interopRequireDefault(require("../../hooks/useDataRecordApps.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 _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 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 _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 WORKFLOW_COLUMNS = [{
      key: 'status',
      value: Liferay.Language.get('status')
    }, {
      key: 'taskNames',
      value: Liferay.Language.get('step')
    }, {
      key: 'assignee',
      value: Liferay.Language.get('assignee')
    }];

    function ListEntries(_ref) {
      var history = _ref.history;

      var _useContext = (0, _react.useContext)(_AppContext.AppContext),
          appId = _useContext.appId,
          basePortletURL = _useContext.basePortletURL,
          dataDefinitionId = _useContext.dataDefinitionId,
          dataListViewId = _useContext.dataListViewId,
          _useContext$defaultDe = _useContext.defaultDelta,
          defaultDelta = _useContext$defaultDe === void 0 ? 20 : _useContext$defaultDe,
          showFormView = _useContext.showFormView,
          userLanguageId = _useContext.userLanguageId;

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

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

      var _useState5 = (0, _react.useState)(),
          _useState6 = _slicedToArray(_useState5, 2),
          selectedEntry = _useState6[0],
          setSelectedEntry = _useState6[1];

      var _useAppWorkflow = (0, _useAppWorkflow2.default)(appId),
          appWorkflowDefinitionId = _useAppWorkflow.appWorkflowDefinitionId;

      var dataRecordApps = (0, _useDataRecordApps.default)(appId, dataRecordIds);
      var delay = (0, _frontendJsReactWeb.useTimeout)();
      var permissions = (0, _usePermissions.default)();

      var _useDataListView = (0, _useDataListView2.default)(dataListViewId, dataDefinitionId, permissions.view),
          columns = _useDataListView.columns,
          dataDefinition = _useDataListView.dataDefinition,
          fieldNames = _useDataListView.dataListView.fieldNames,
          isLoading = _useDataListView.isLoading;

      var _useState7 = (0, _react.useState)({
        isFetching: true,
        items: [],
        totalCount: 0
      }),
          _useState8 = _slicedToArray(_useState7, 2),
          _useState8$ = _useState8[0],
          isFetching = _useState8$.isFetching,
          items = _useState8$.items,
          totalCount = _useState8$.totalCount,
          setFetchState = _useState8[1];

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

      var dispatch = (0, _react.useCallback)(function (action) {
        return setQuery((0, _SearchContext.reducer)(query, action));
      }, [query, setQuery]);
      var previousQuery = (0, _frontendJsReactWeb.usePrevious)(query);

      var doFetch = function doFetch(_ref2) {
        var entryInstanceId = _ref2.entryInstanceId,
            newAssignee = _ref2.newAssignee,
            query = _ref2.query,
            workflowDefinitionId = _ref2.workflowDefinitionId;

        if (workflowDefinitionId) {
          setFetchState(function (prevState) {
            return _objectSpread(_objectSpread({}, prevState), {}, {
              isFetching: true
            });
          });
          (0, _client.getItem)("/o/data-engine/v2.0/data-definitions/".concat(dataDefinitionId, "/data-records"), query).then(function (response) {
            setFetchState(_objectSpread({
              isFetching: response.items.length !== 0
            }, response));

            if (response.items.length) {
              var classPKs = response.items.map(function (_ref3) {
                var id = _ref3.id;
                return id;
              });
              setDataRecordIds(classPKs);

              var getWorkflowInfo = function getWorkflowInfo() {
                (0, _client.getItem)("/o/portal-workflow-metrics/v1.0/processes/".concat(workflowDefinitionId, "/instances"), {
                  classPKs: classPKs,
                  page: 1,
                  pageSize: response.items.length
                }).then(function (workflowResponse) {
                  var items = response.items;
                  var retryCount = 0;

                  if (entryInstanceId) {
                    var _assignees$;

                    var _workflowResponse$ite = workflowResponse.items.find(function (_ref4) {
                      var id = _ref4.id;
                      return id === entryInstanceId;
                    }),
                        assignees = _workflowResponse$ite.assignees;

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

                  if (workflowResponse.totalCount > 0) {
                    items = response.items.map(function (item) {
                      var _ref5 = workflowResponse.items.find(function (_ref6) {
                        var classPK = _ref6.classPK;
                        return classPK === item.id;
                      }) || {},
                          assignees = _ref5.assignees,
                          completed = _ref5.completed,
                          instanceId = _ref5.id,
                          taskNames = _ref5.taskNames;

                      return _objectSpread(_objectSpread({}, item), {}, {
                        assignees: assignees,
                        completed: completed,
                        instanceId: instanceId,
                        taskNames: taskNames
                      });
                    });
                  }

                  setFetchState(function (prevState) {
                    return _objectSpread(_objectSpread({}, prevState), {}, {
                      isFetching: false,
                      items: items
                    });
                  });
                });
              };

              getWorkflowInfo();
            }
          }).catch(function () {
            (0, _toast.errorToast)();
            setDataRecordIds([]);
            setFetchState(function (prevState) {
              return _objectSpread(_objectSpread({}, prevState), {}, {
                isFetching: false
              });
            });
          });
        }
      };

      var onClickAddButton = function onClickAddButton() {
        return (0, _utils.navigateToEditPage)(basePortletURL, {
          languageId: userLanguageId
        });
      };

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

        return doFetch({
          entryInstanceId: entryInstanceId,
          newAssignee: newAssignee,
          query: query,
          workflowDefinitionId: appWorkflowDefinitionId
        });
      };

      (0, _react.useEffect)(function () {
        if (!(0, _utils2.isEqualObjects)(query, previousQuery)) {
          refetch();
        } // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [query]);
      (0, _react.useEffect)(function () {
        doFetch({
          query: query,
          workflowDefinitionId: appWorkflowDefinitionId
        }); // eslint-disable-next-line react-hooks/exhaustive-deps
      }, [appWorkflowDefinitionId]);
      var ACTIONS = [{
        action: function action(entry) {
          setSelectedEntry(entry);
          setModalVisible(true);
          return Promise.resolve(false);
        },
        name: Liferay.Language.get('assign-to'),
        show: function show(_ref14) {
          var canReassign = _ref14.canReassign;
          return canReassign;
        }
      }].concat(_toConsumableArray((0, _useEntriesActions.default)({
        update: function update(_ref15) {
          var _assignees$2;

          var assignees = _ref15.assignees,
              completed = _ref15.completed;
          return completed === false && (assignees === null || assignees === void 0 ? void 0 : (_assignees$2 = assignees[0]) === null || _assignees$2 === void 0 ? void 0 : _assignees$2.id) === Number(themeDisplay.getUserId());
        }
      })));
      var COLUMNS = [].concat(_toConsumableArray(columns.map(function (_ref16) {
        var value = _ref16.value,
            column = _objectWithoutProperties(_ref16, ["value"]);

        return _objectSpread(_objectSpread({}, column), {}, {
          value: (0, _lang.getLocalizedUserPreferenceValue)(value, userLanguageId, dataDefinition.defaultLanguageId)
        });
      })), WORKFLOW_COLUMNS);
      var isEmpty = items.length === 0;
      var showAddButton = showFormView && permissions.add;
      var refetchActions = ACTIONS.map(function () {
        var _action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

        return _objectSpread(_objectSpread({}, _action), {}, {
          action: function action(entry) {
            return _action === null || _action === void 0 ? void 0 : _action.action(entry).then(function (isRefetch) {
              if (isRefetch) {
                refetch();
              }
            });
          }
        });
      });

      if (!permissions.view) {
        return (/*#__PURE__*/_react.default.createElement(_NoPermissionState.default, null)
        );
      }

      return (/*#__PURE__*/_react.default.createElement(_Loading.Loading, {
          isLoading: isLoading
        }, /*#__PURE__*/_react.default.createElement(_SearchContext.default.Provider, {
          value: [query, dispatch]
        }, /*#__PURE__*/_react.default.createElement(_ManagementToolbar.default, {
          addButton: function addButton() {
            return showAddButton && /*#__PURE__*/_react.default.createElement(_Button.default, {
              className: "nav-btn nav-btn-monospaced",
              onClick: onClickAddButton,
              symbol: "plus",
              tooltip: Liferay.Language.get('new-entry')
            });
          },
          columns: COLUMNS,
          disabled: !query.keywords && isEmpty,
          totalCount: totalCount
        }), /*#__PURE__*/_react.default.createElement(_ManagementToolbarResultsBar.default, {
          isLoading: isFetching,
          totalCount: totalCount
        }), /*#__PURE__*/_react.default.createElement(_TableWithPagination.default, {
          actions: refetchActions,
          columns: COLUMNS,
          emptyState: {
            button: function button() {
              return showAddButton && /*#__PURE__*/_react.default.createElement(_Button.default, {
                displayType: "secondary",
                onClick: onClickAddButton
              }, Liferay.Language.get('new-entry'));
            },
            title: Liferay.Language.get('there-are-no-entries-yet')
          },
          isEmpty: isEmpty,
          isLoading: isFetching,
          items: function buildWorkflowItems(items) {
            return items.map((0, _utils.buildEntries)({
              dataDefinition: dataDefinition,
              fieldNames: fieldNames,
              permissions: permissions,
              query: query
            })).map(function (entry) {
              var workflowValues = {};
              var emptyValue = '--';
              WORKFLOW_COLUMNS.forEach(function (_ref8) {
                var key = _ref8.key;

                switch (key) {
                  case 'assignee':
                    {
                      var _entry$assignees = entry.assignees,
                          assignees = _entry$assignees === void 0 ? [] : _entry$assignees,
                          _entry$taskNames = entry.taskNames,
                          taskNames = _entry$taskNames === void 0 ? [] : _entry$taskNames;

                      var _ref9 = assignees[0] || {},
                          _ref9$id = _ref9.id,
                          id = _ref9$id === void 0 ? -1 : _ref9$id,
                          _ref9$name = _ref9.name,
                          name = _ref9$name === void 0 ? emptyValue : _ref9$name,
                          reviewer = _ref9.reviewer;

                      if (id === -1) {
                        var _ref10 = dataRecordApps[entry.id] || {},
                            _ref10$appWorkflowTas = _ref10.appWorkflowTasks,
                            appWorkflowTasks = _ref10$appWorkflowTas === void 0 ? [] : _ref10$appWorkflowTas;

                        var _ref11 = appWorkflowTasks.find(function (_ref12) {
                          var name = _ref12.name;
                          return name === taskNames[0];
                        }) || {},
                            _ref11$appWorkflowRol = _ref11.appWorkflowRoleAssignments,
                            appWorkflowRoleAssignments = _ref11$appWorkflowRol === void 0 ? [] : _ref11$appWorkflowRol;

                        var roleNames = appWorkflowRoleAssignments.map(function (_ref13) {
                          var roleName = _ref13.roleName;
                          return roleName;
                        });
                        workflowValues.canReassign = reviewer;
                        workflowValues[key] = roleNames.length ? (0, _utils2.concatValues)(roleNames) : emptyValue;
                      } else {
                        workflowValues.canReassign = Number(themeDisplay.getUserId()) === id;
                        workflowValues[key] = name;
                      }

                      break;
                    }

                  case 'status':
                    {
                      if (typeof entry.completed === 'boolean') {
                        workflowValues[key] = entry.completed ? /*#__PURE__*/_react.default.createElement(_label.default, {
                          displayType: "success"
                        }, Liferay.Language.get('completed')) : /*#__PURE__*/_react.default.createElement(_label.default, {
                          displayType: "info"
                        }, Liferay.Language.get('pending'));
                      } else {
                        workflowValues[key] = emptyValue;
                      }

                      break;
                    }

                  case 'taskNames':
                    {
                      var _entry$taskNames2 = entry.taskNames,
                          _taskNames = _entry$taskNames2 === void 0 ? [emptyValue] : _entry$taskNames2;

                      workflowValues[key] = _taskNames[0];
                      break;
                    }

                  default:
                    {
                      workflowValues[key] = entry[key] || emptyValue;
                    }
                }
              });
              return _objectSpread(_objectSpread({}, entry), workflowValues);
            });
          }(items),
          keywords: query.keywords,
          noActionsMessage: Liferay.Language.get('you-do-not-have-the-permission-to-manage-this-entry'),
          totalCount: totalCount
        })), isModalVisible && /*#__PURE__*/_react.default.createElement(_ReassignEntryModal.default, {
          entry: selectedEntry,
          onCloseModal: function onCloseModal() {
            setModalVisible(false);
            setSelectedEntry();
          },
          refetch: refetch
        }))
      );
    }
    //# sourceMappingURL=ListEntries.es.js.map
  }
});
//# sourceMappingURL=ListEntries.es.js.map