<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import {
  isEmpty,
  get,
} from 'lodash';

import { Callout } from '@folio/stripes/components';
import SafeHTMLMessage from '@folio/react-intl-safe-html';

import BulkRenewalDialog from '../BulkRenewalDialog';
import isOverridePossible from '../Loans/OpenLoans/helpers/isOverridePossible';

// HOC used to manage renew
const withRenew = WrappedComponent => class WithRenewComponent extends React.Component {
  static propTypes = {
    loans: PropTypes.arrayOf(PropTypes.object),
    patronBlocks: PropTypes.arrayOf(PropTypes.object),
    mutator: PropTypes.shape({
      loanPolicies: PropTypes.shape({
        GET: PropTypes.func.isRequired,
        reset: PropTypes.func.isRequired,
      }),
      renew: PropTypes.shape({
        POST: PropTypes.func.isRequired,
      }),
      requests: PropTypes.shape({
        GET: PropTypes.func.isRequired,
        reset: PropTypes.func.isRequired,
      }),
    }),
    stripes: PropTypes.shape({
      connect: PropTypes.func.isRequired,
    }),
    user: PropTypes.object,
  };

  static defaultProps = {
    loans: [],
  };

  constructor(props) {
    super(props);

    this.connectedBulkRenewalDialog = props.stripes.connect(BulkRenewalDialog);
    this.state = {
      loans: [],
      errors: [],
      bulkRenewal: false,
      bulkRenewalDialogOpen: false,
      renewSuccess: [],
      renewFailure: [],
      errorMsg: {},
      requestCounts: {},
      loanPolicies: {},
    };
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    const { loans } = nextProps;

    if (prevState.loans.length < nextProps.loans.length) {
      return { loans };
    }

    return null;
  }

  componentDidMount() {
    this._isMounted = true;
    const { loans } = this.state;

    if (loans.length > 0) {
      this.fetchLoanPolicyNames();
      this.getOpenRequestsCount();
    }
  }

  componentDidUpdate(prevProps, prevState) {
    const { loans } = this.state;

    if (loans.length > prevState.loans.length) {
      this.fetchLoanPolicyNames();
      this.getOpenRequestsCount();
    }
  }

  componentWillUnmount() {
    this._isMounted = false;
  }

  // fetchLoanPolicyNames and getOpenRequestsCount both execute XHRs that resolve
  // asynchronously and save their results in state. This causes a memory leak if
  // the component is unmounted before the promise resolves as state will not be
  // available at that point. By setting _isMounted in cDM/cWU, we can use it in a
  // condition in those methods to determine whether it is safe to update state.
  _isMounted = false;

  renewItem = (loan, patron, bulkRenewal) => {
    this.setState({ bulkRenewal });
    const params = {
      itemBarcode: loan.item.barcode,
      userBarcode: patron.barcode,
    };

    return new Promise((resolve, reject) => {
      this.props.mutator.renew.POST(params)
        .then(resolve)
        .catch(resp => {
          const contentType = resp.headers.get('Content-Type');

          if (contentType && contentType.startsWith('application/json')) {
            resp.json()
              .then((error) => {
                const errors = this.handleErrors(error);

                reject(this.getMessage(errors));
              });
          } else {
            resp.text()
              .then(reject);
          }
        });
    });
  };

  renew = async (loans, patron) => {
    const { patronBlocks } = this.props;
    const renewSuccess = [];
    const renewFailure = [];
    const errorMsg = {};
    const countRenew = patronBlocks.filter(p => p.renewals);
    const bulkRenewal = (loans.length > 1);

    if (!isEmpty(countRenew)) {
      return this.setState({ patronBlockedModal: true });
    }

    for (const loan of loans) {
      try {
        // We actually want to execute it in a sequence so turning off eslint warning
        // https://issues.folio.org/browse/UIU-1299
        // eslint-disable-next-line no-await-in-loop
        renewSuccess.push(await this.renewItem(loan, patron, bulkRenewal));
      } catch (error) {<commit_msg>UIU-1299: Pass silent during bulk renew (#1189)<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import {
  isEmpty,
  get,
} from 'lodash';

import { Callout } from '@folio/stripes/components';
import SafeHTMLMessage from '@folio/react-intl-safe-html';

import BulkRenewalDialog from '../BulkRenewalDialog';
import isOverridePossible from '../Loans/OpenLoans/helpers/isOverridePossible';

// HOC used to manage renew
const withRenew = WrappedComponent => class WithRenewComponent extends React.Component {
  static propTypes = {
    loans: PropTypes.arrayOf(PropTypes.object),
    patronBlocks: PropTypes.arrayOf(PropTypes.object),
    mutator: PropTypes.shape({
      loanPolicies: PropTypes.shape({
        GET: PropTypes.func.isRequired,
        reset: PropTypes.func.isRequired,
      }),
      renew: PropTypes.shape({
        POST: PropTypes.func.isRequired,
      }),
      requests: PropTypes.shape({
        GET: PropTypes.func.isRequired,
        reset: PropTypes.func.isRequired,
      }),
    }),
    stripes: PropTypes.shape({
      connect: PropTypes.func.isRequired,
    }),
    user: PropTypes.object,
  };

  static defaultProps = {
    loans: [],
  };

  constructor(props) {
    super(props);

    this.connectedBulkRenewalDialog = props.stripes.connect(BulkRenewalDialog);
    this.state = {
      loans: [],
      errors: [],
      bulkRenewal: false,
      bulkRenewalDialogOpen: false,
      renewSuccess: [],
      renewFailure: [],
      errorMsg: {},
      requestCounts: {},
      loanPolicies: {},
    };
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    const { loans } = nextProps;

    if (prevState.loans.length < nextProps.loans.length) {
      return { loans };
    }

    return null;
  }

  componentDidMount() {
    this._isMounted = true;
    const { loans } = this.state;

    if (loans.length > 0) {
      this.fetchLoanPolicyNames();
      this.getOpenRequestsCount();
    }
  }

  componentDidUpdate(prevProps, prevState) {
    const { loans } = this.state;

    if (loans.length > prevState.loans.length) {
      this.fetchLoanPolicyNames();
      this.getOpenRequestsCount();
    }
  }

  componentWillUnmount() {
    this._isMounted = false;
  }

  // fetchLoanPolicyNames and getOpenRequestsCount both execute XHRs that resolve
  // asynchronously and save their results in state. This causes a memory leak if
  // the component is unmounted before the promise resolves as state will not be
  // available at that point. By setting _isMounted in cDM/cWU, we can use it in a
  // condition in those methods to determine whether it is safe to update state.
  _isMounted = false;

  renewItem = (loan, patron, bulkRenewal, silent) => {
    this.setState({ bulkRenewal });
    const params = {
      itemBarcode: loan.item.barcode,
      userBarcode: patron.barcode,
    };

    return new Promise((resolve, reject) => {
      this.props.mutator.renew.POST(params, { silent })
        .then(resolve)
        .catch(resp => {
          const contentType = resp.headers.get('Content-Type');

          if (contentType && contentType.startsWith('application/json')) {
            resp.json()
              .then((error) => {
                const errors = this.handleErrors(error);

                reject(this.getMessage(errors));
              });
          } else {
            resp.text()
              .then(reject);
          }
        });
    });
  };

  renew = async (loans, patron) => {
    const { patronBlocks } = this.props;
    const renewSuccess = [];
    const renewFailure = [];
    const errorMsg = {};
    const countRenew = patronBlocks.filter(p => p.renewals);
    const loansSize = loans.length;
    const bulkRenewal = (loansSize > 1);

    if (!isEmpty(countRenew)) {
      return this.setState({ patronBlockedModal: true });
    }

    for (const [index, loan] of loans.entries()) {
      try {
        // We actually want to execute it in a sequence so turning off eslint warning
        // https://issues.folio.org/browse/UIU-1299
        // eslint-disable-next-line no-await-in-loop
        renewSuccess.push(await this.renewItem(loan, patron, bulkRenewal, index !== loansSize - 1));
      } catch (error) {
{'fraction_non_alphanumeric': 0.11998571598619212, 'fraction_numerical': 0.0024997024163790024, 'mean_word_length': 2.6153184165232357, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 23, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6702687', 'n_tokens_mistral': 2556, 'n_tokens_neox': 2512, 'n_words': 585}