<commit_before>import { Alert, Linking } from 'react-native';
import { GoogleSignin } from 'react-native-google-signin';

import {
    LOGIN_REQUEST,
    UPDATE_HISTORY_FILTER,
    ATTEMPT_EXPORTING_CSV,
    EXPORTING_CSV,
    CANCEL_LOGOUT,
} from 'app/ActionTypes';
import * as AuthActionCreators from 'app/redux/shared_actions/AuthActionCreators';
import * as GoogleDriveUploader from 'app/services/GoogleDriveUploader';
import * as CSVConverter from 'app/utility/transforms/CSVConverter';
import * as SetsSelectors from 'app/redux/selectors/SetsSelectors';
import * as SettingsSelectors from 'app/redux/selectors/SettingsSelectors';
import * as DurationCalculator from 'app/utility/transforms/DurationCalculator';
import * as Analytics from 'app/services/Analytics';

export const signIn = () => (dispatch, getState) => {
    const state = getState();
    logTapGoogleSignInAnalytics(state);

    dispatch({
        type: LOGIN_REQUEST
    });
};

export const signOut = () => (dispatch, getState) => {
    const state = getState();
    logAttemptLogoutAnalytics(state);

    dispatch(AuthActionCreators.logout());
};

export const cancelSignOut = () => (dispatch, getState) => {
    const state = getState();
    logLogoutCancelledAnalytics(state);

    dispatch({
        type: CANCEL_LOGOUT
    });
};

export const showRemovedData = () => ({
    type: UPDATE_HISTORY_FILTER,
    showRemoved: true
});

export const hideRemovedData = () => ({
    type: UPDATE_HISTORY_FILTER,
    showRemoved: false
});

// TODO: refactor this into a saga
export const exportCSV = () => (dispatch, getState) => {
    // logged in check
    let state = getState();
    if (state.auth.email === null) {
        Alert.alert('Sign in Required', 'Please sign in via Settings to use this feature.');
        return;
    }

    GoogleSignin.currentUserAsync().then(async (user) => {
        if (user === null) {
            dispatch({ type: EXPORTING_CSV_ERROR });
            Alert.alert('Error Exporting CSV', 'Tip: Is your internet connection working?\n\nTip: Try Logging out then logging in again as this feature requires additional Google Drive permissions.');
        } else {
            //ATTEMPT
            logAttemptCSVAnalytics(state);
            dispatch(updateIsExportingCSV(true));
            try {
                let date = new Date();
                let name = 'OpenBarbell Data -- Exported on ' + date.toLocaleString() + '.csv';
                // TODO: use a more efficient method of generating the name, perhaps an actual date format
                name = name.split('/').join('-');
                name = name.split(',').join('');
                name = name.split(':').join('.');
                let state = getState();
                let sets = SetsSelectors.getHistorySetsChronological(state);
                let csv = CSVConverter.convert(sets);
                console.tron.log("google access token " + user.accessToken);
                await GoogleDriveUploader.upload(user.accessToken, name, csv, (fileID) => {
                    dispatch(updateIsExportingCSV(false));
                    Linking.openURL('https://drive.google.com/open?id=' + fileID).catch(err => {
                        Alert.alert('Upload Succeeded', 'CSV uploaded to your Google Drive!');
                    });
                    logExportCSVAnalytics(state);
                });
            } catch(err) {
                console.tron.log("Error uploading csv file " + typeof err + " " + err);
                if (err.message == 'Insufficient Permission') { // TODO: should do typeof check but it's not working
                    Alert.alert('Google Drive Permissions Error', 'Please log out and log in again. This feature requires additional Google Drive permissions.');
                } else {
                    Alert.alert('Error exporting CSV', 'Please try again later.\n\nTip: Is your internet connection working?');
                }
                dispatch(updateIsExportingCSV(false));
                let state = getState();
                logExportCSVErrorAnalytics(state);
            }
        }
    })
    .catch((err) => {
        // error here
        console.tron.log("EXPORT HISTORY ERROR " + err);
    })
    .done();
};

const updateIsExportingCSV = (isExportingCSV) => ({ type: EXPORTING_CSV, isExportingCSV: isExportingCSV });

const getTimeSinceLastExport = (state) => {
    const startDate = SettingsSelectors.getLastExportCSVDate(state);
    if (Boolean(startDate)) {
        return Date.parse(new Date()) - Date.parse(startDate);
    } else {
        return 0;
    }
};

// ANALYTICS

const logTapGoogleSignInAnalytics = (state) => {
    Analytics.logEventWithAppState('tap_google_sign_in', {
    }, state);
};

const logAttemptCSVAnalytics = (state) => {
    const num_sets = SetsSelectors.getNumHistorySets(state);
    const num_reps = SetsSelectors.getNumHistoryReps(state);
    const num_workouts = SetsSelectors.getNumHistoryWorkouts(state);
    const time_since_last_export = getTimeSinceLastExport(state);
    const time_since_last_workout = SetsSelectors.getTimeSinceLastWorkout(state);

    Analytics.logEventWithAppState('attempt_export_csv', {
        value: time_since_last_export,
        num_sets: num_sets,
        num_reps: num_reps,
        num_workouts: num_workouts,
        time_since_last_workout: time_since_last_workout,
        time_since_last_export: time_since_last_export,
    }, state);
};

const logExportCSVAnalytics = (state) => {
    const num_sets = SetsSelectors.getNumHistorySets(state);
    const num_reps = SetsSelectors.getNumHistoryReps(state);
    const num_workouts = SetsSelectors.getNumHistoryWorkouts(state);
    const time_since_last_export = getTimeSinceLastExport(state);
    const time_since_last_workout = SetsSelectors.getTimeSinceLastWorkout(state);

    Analytics.logEventWithAppState('export_csv', {
        value: time_since_last_export,
        num_sets: num_sets,
        num_reps: num_reps,
        num_workouts: num_workouts,
        time_since_last_workout: time_since_last_workout,
        time_since_last_export: time_since_last_export,
    }, state);
};

const logExportCSVErrorAnalytics = (state) => {
    const num_sets = SetsSelectors.getNumHistorySets(state);
    const num_reps = SetsSelectors.getNumHistoryReps(state);
    const num_workouts = SetsSelectors.getNumHistoryWorkouts(state);
    const time_since_last_export = getTimeSinceLastExport(state);
    const time_since_last_workout = SetsSelectors.getTimeSinceLastWorkout(state);

    Analytics.logEventWithAppState('export_csv_error', {
        num_sets: num_sets,
        num_reps: num_reps,
        num_workouts: num_workouts,
        time_since_last_workout: time_since_last_workout,
        time_since_last_export: time_since_last_export,
    }, state);
};

const logAttemptLogoutAnalytics = (state) => {
    Analytics.logEventWithAppState('attempt_logout', {
    }, state);
};

const logLogoutCancelledAnalytics = (state) => {
    Analytics.logEventWithAppState('logout_cancelled', {
    }, state);
};
<commit_msg>Show and Hide deleted analytics<commit_after>import { Alert, Linking } from 'react-native';
import { GoogleSignin } from 'react-native-google-signin';

import {
    LOGIN_REQUEST,
    UPDATE_HISTORY_FILTER,
    ATTEMPT_EXPORTING_CSV,
    EXPORTING_CSV,
    CANCEL_LOGOUT,
} from 'app/ActionTypes';
import * as AuthActionCreators from 'app/redux/shared_actions/AuthActionCreators';
import * as GoogleDriveUploader from 'app/services/GoogleDriveUploader';
import * as CSVConverter from 'app/utility/transforms/CSVConverter';
import * as SetsSelectors from 'app/redux/selectors/SetsSelectors';
import * as SettingsSelectors from 'app/redux/selectors/SettingsSelectors';
import * as DurationCalculator from 'app/utility/transforms/DurationCalculator';
import * as Analytics from 'app/services/Analytics';

export const signIn = () => (dispatch, getState) => {
    const state = getState();
    logTapGoogleSignInAnalytics(state);

    dispatch({
        type: LOGIN_REQUEST
    });
};

export const signOut = () => (dispatch, getState) => {
    const state = getState();
    logAttemptLogoutAnalytics(state);

    dispatch(AuthActionCreators.logout());
};

export const cancelSignOut = () => (dispatch, getState) => {
    const state = getState();
    logLogoutCancelledAnalytics(state);

    dispatch({
        type: CANCEL_LOGOUT
    });
};

export const showRemovedData = () => (dispatch, getState) => {
    const state = getState();
    logShowDeletedAnalytics(state);

    dispatch({
        type: UPDATE_HISTORY_FILTER,
        showRemoved: true,
    });
};

export const hideRemovedData = () => (dispatch, getState) => {
    const state = getState();
    logHideDeletedAnalytics(state);

    dispatch({
        type: UPDATE_HISTORY_FILTER,
        showRemoved: false
    });
};

// TODO: refactor this into a saga
export const exportCSV = () => (dispatch, getState) => {
    // logged in check
    let state = getState();
    if (state.auth.email === null) {
        Alert.alert('Sign in Required', 'Please sign in via Settings to use this feature.');
        return;
    }

    GoogleSignin.currentUserAsync().then(async (user) => {
        if (user === null) {
            dispatch({ type: EXPORTING_CSV_ERROR });
            Alert.alert('Error Exporting CSV', 'Tip: Is your internet connection working?\n\nTip: Try Logging out then logging in again as this feature requires additional Google Drive permissions.');
        } else {
            //ATTEMPT
            logAttemptCSVAnalytics(state);
            dispatch(updateIsExportingCSV(true));
            try {
                let date = new Date();
                let name = 'OpenBarbell Data -- Exported on ' + date.toLocaleString() + '.csv';
                // TODO: use a more efficient method of generating the name, perhaps an actual date format
                name = name.split('/').join('-');
                name = name.split(',').join('');
                name = name.split(':').join('.');
                let state = getState();
                let sets = SetsSelectors.getHistorySetsChronological(state);
                let csv = CSVConverter.convert(sets);
                console.tron.log("google access token " + user.accessToken);
                await GoogleDriveUploader.upload(user.accessToken, name, csv, (fileID) => {
                    dispatch(updateIsExportingCSV(false));
                    Linking.openURL('https://drive.google.com/open?id=' + fileID).catch(err => {
                        Alert.alert('Upload Succeeded', 'CSV uploaded to your Google Drive!');
                    });
                    logExportCSVAnalytics(state);
                });
            } catch(err) {
                console.tron.log("Error uploading csv file " + typeof err + " " + err);
                if (err.message == 'Insufficient Permission') { // TODO: should do typeof check but it's not working
                    Alert.alert('Google Drive Permissions Error', 'Please log out and log in again. This feature requires additional Google Drive permissions.');
                } else {
                    Alert.alert('Error exporting CSV', 'Please try again later.\n\nTip: Is your internet connection working?');
                }
                dispatch(updateIsExportingCSV(false));
                let state = getState();
                logExportCSVErrorAnalytics(state);
            }
        }
    })
    .catch((err) => {
        // error here
        console.tron.log("EXPORT HISTORY ERROR " + err);
    })
    .done();
};

const updateIsExportingCSV = (isExportingCSV) => ({ type: EXPORTING_CSV, isExportingCSV: isExportingCSV });

const getTimeSinceLastExport = (state) => {
    const startDate = SettingsSelectors.getLastExportCSVDate(state);
    if (Boolean(startDate)) {
        return Date.parse(new Date()) - Date.parse(startDate);
    } else {
        return 0;
    }
};

// ANALYTICS

const logTapGoogleSignInAnalytics = (state) => {
    Analytics.logEventWithAppState('tap_google_sign_in', {
    }, state);
};

const logAttemptCSVAnalytics = (state) => {
    const num_sets = SetsSelectors.getNumHistorySets(state);
    const num_reps = SetsSelectors.getNumHistoryReps(state);
    const num_workouts = SetsSelectors.getNumHistoryWorkouts(state);
    const time_since_last_export = getTimeSinceLastExport(state);
    const time_since_last_workout = SetsSelectors.getTimeSinceLastWorkout(state);

    Analytics.logEventWithAppState('attempt_export_csv', {
        value: time_since_last_export,
        num_sets: num_sets,
        num_reps: num_reps,
        num_workouts: num_workouts,
        time_since_last_workout: time_since_last_workout,
        time_since_last_export: time_since_last_export,
    }, state);
};

const logExportCSVAnalytics = (state) => {
    const num_sets = SetsSelectors.getNumHistorySets(state);
    const num_reps = SetsSelectors.getNumHistoryReps(state);
    const num_workouts = SetsSelectors.getNumHistoryWorkouts(state);
    const time_since_last_export = getTimeSinceLastExport(state);
    const time_since_last_workout = SetsSelectors.getTimeSinceLastWorkout(state);

    Analytics.logEventWithAppState('export_csv', {
        value: time_since_last_export,
        num_sets: num_sets,
        num_reps: num_reps,
        num_workouts: num_workouts,
        time_since_last_workout: time_since_last_workout,
        time_since_last_export: time_since_last_export,
    }, state);
};

const logExportCSVErrorAnalytics = (state) => {
    const num_sets = SetsSelectors.getNumHistorySets(state);
    const num_reps = SetsSelectors.getNumHistoryReps(state);
    const num_workouts = SetsSelectors.getNumHistoryWorkouts(state);
    const time_since_last_export = getTimeSinceLastExport(state);
    const time_since_last_workout = SetsSelectors.getTimeSinceLastWorkout(state);

    Analytics.logEventWithAppState('export_csv_error', {
        num_sets: num_sets,
        num_reps: num_reps,
        num_workouts: num_workouts,
        time_since_last_workout: time_since_last_workout,
        time_since_last_export: time_since_last_export,
    }, state);
};

const logAttemptLogoutAnalytics = (state) => {
    Analytics.logEventWithAppState('attempt_logout', {
    }, state);
};

const logLogoutCancelledAnalytics = (state) => {
    Analytics.logEventWithAppState('logout_cancelled', {
    }, state);
};

const logShowDeletedAnalytics = (state) => {
    Analytics.logEventWithAppState('show_deleted', {
    }, state);
};

const logHideDeletedAnalytics = (state) => {
    Analytics.logEventWithAppState('hide_deleted', {
    }, state);
};
<|endoftext|>


<commit_before>import axios from '~/helpers/axios'

const actions = {
  submit ({ commit }, email) {
    commit('SET_LOADING_IS_ACTIVE', true)
    axios.post('newsletter/subscribe', { email: email })
      .then((response) => {
        commit('SUBMIT')
      })
      .catch(() => {
        alert('There was an error subscribing. Make sure you have entered a valid email address and try again. If this error persists, please let us know: support@stateofthedapps.com')
      })
      .finally(() => {
        commit('SET_LOADING_IS_ACTIVE', false)
      })
  },
  toggleDropdown ({ commit }) {
    commit('TOGGLE_DROPDOWN')
  },
  setEmail ({ commit }, value) {
    commit('SET_EMAIL', value)
  },
  setEmailIsValid ({ commit }, status) {
    commit('SET_EMAIL_VALID_STATUS', status)
  }
}

const getters = {
  confirmation: state => {
    return state.confirmation
  },
  isLoading: state => {
    return state.isLoading
  },
  email: state => {
    return state.email
  },
  emailIsValid: state => {
    return state.emailIsValid
  },
  dropdownIsActive: state => {
    return state.dropdownIsActive
  }
}

const mutations = {
  SET_LOADING_IS_ACTIVE (state, status) {
    state.isLoading = status
  },
  SUBMIT (state) {
    state.confirmation = true
  },
  TOGGLE_DROPDOWN (state) {
    state.dropdownIsActive = !state.dropdownIsActive
    var newState = {
      confirmation: false,
      email: '',
      emailIsValid: false
    }
    Object.assign(state, newState)
  },
  SET_EMAIL (state, value) {
    state.email = value
  },
  SET_EMAIL_VALID_STATUS (state, status) {
    state.emailIsValid = status
  }
}

const state = {
  dropdownIsActive: false,
  confirmation: false,
  email: '',
  emailIsValid: false,
  isLoading: false
}

export default {
  actions,
  getters,
  mutations,
  namespaced: true,
  state
}
<commit_msg>Remove finally from axios calls (#154)<commit_after>import axios from '~/helpers/axios'

const actions = {
  submit ({ commit }, email) {
    commit('SET_LOADING_IS_ACTIVE', true)
    axios.post('newsletter/subscribe', { email: email })
      .then((response) => {
        commit('SUBMIT')
        commit('SET_LOADING_IS_ACTIVE', false)
      })
      .catch(() => {
        commit('SET_LOADING_IS_ACTIVE', false)
        alert('There was an error subscribing. Make sure you have entered a valid email address and try again. If this error persists, please let us know: support@stateofthedapps.com')
      })
  },
  toggleDropdown ({ commit }) {
    commit('TOGGLE_DROPDOWN')
  },
  setEmail ({ commit }, value) {
    commit('SET_EMAIL', value)
  },
  setEmailIsValid ({ commit }, status) {
    commit('SET_EMAIL_VALID_STATUS', status)
  }
}

const getters = {
  confirmation: state => {
    return state.confirmation
  },
  isLoading: state => {
    return state.isLoading
  },
  email: state => {
    return state.email
  },
  emailIsValid: state => {
    return state.emailIsValid
  },
  dropdownIsActive: state => {
    return state.dropdownIsActive
  }
}

const mutations = {
  SET_LOADING_IS_ACTIVE (state, status) {
    state.isLoading = status
  },
  SUBMIT (state) {
    state.confirmation = true
  },
  TOGGLE_DROPDOWN (state) {
    state.dropdownIsActive = !state.dropdownIsActive
    var newState = {
      confirmation: false,
      email: '',
      emailIsValid: false
    }
    Object.assign(state, newState)
  },
  SET_EMAIL (state, value) {
    state.email = value
  },
  SET_EMAIL_VALID_STATUS (state, status) {
    state.emailIsValid = status
  }
}

const state = {
  dropdownIsActive: false,
  confirmation: false,
  email: '',
  emailIsValid: false,
  isLoading: false
}

export default {
  actions,
  getters,
  mutations,
  namespaced: true,
  state
}
<|endoftext|>


<commit_before>import _ from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import {
  injectIntl,
  intlShape,
  FormattedMessage,
} from 'react-intl';
import { Field } from 'redux-form';
import { MultiSelection } from '@folio/stripes/components';
import { ControlledVocab } from '@folio/stripes/smart-components';
import { stripesConnect, withStripes } from '@folio/stripes/core';

import { validate } from '../util';

class OwnerSettings extends React.Component {
  static manifest = Object.freeze({
    ownerServicePoints: {
      type: 'okapi',
      resource: 'service-points',
      path: 'service-points',
    },
    owners: {
      type: 'okapi',
      records: 'owners',
      path: 'owners',
      GET: {
        path: 'owners?query=cql.allRecords=1 sortby owner&limit=500'
      }
    },
  });

  static propTypes = {
    stripes: PropTypes.shape({
      connect: PropTypes.func.isRequired,
    }).isRequired,
    intl: intlShape.isRequired,
  };

  constructor(props) {
    super(props);

    this.connectedControlledVocab = props.stripes.connect(ControlledVocab);
  }

  validate = (item, index, items) => {
    const { intl: { formatMessage } } = this.props;
    const label = formatMessage({ id: 'ui-users.owners.singular' });
    const itemErrors = validate(item, index, items, 'owner', label);
    if (item.owner === 'Shared' && item.servicePointOwner.length > 0) {
      itemErrors.owner = formatMessage({ id: 'ui-users.owners.noServicePoints' });
    }
    return itemErrors;
  }

  warn = ({ items }) => {
    const servicePoints = _.get(this.props.resources, ['ownerServicePoints', 'records', 0, 'servicepoints'], []);
    const none = servicePoints.find(s => s.name === 'None') || {};

    const warnings = [];
    if (Array.isArray(items)) {
      items.forEach((item, index) => {
        const itemWarning = {};

        const asp = item.servicePointOwner || [];

        asp.forEach(s => {
          if (s.value === none.id) {
            itemWarning.servicePointOwner = <FormattedMessage id="ui-users.owners.warning" />;
          }
        });

        if (Object.keys(itemWarning).length) {
          warnings[index] = itemWarning;
        }
      });
    }
    return { items: warnings };
  }

  render() {
    const {
      intl: { formatMessage },
      resources
    } = this.props;
    const label = formatMessage({ id: 'ui-users.owners.singular' });

    const rows = _.get(resources, ['owners', 'records'], []);
    const servicePoints = _.get(resources, ['ownerServicePoints', 'records', 0, 'servicepoints'], []);
    const serviceOwners = [];
    rows.forEach(o => {
      const asp = o.servicePointOwner || [];
      asp.forEach(s => {
        if (!serviceOwners.includes(s.value)) {
          serviceOwners.push(s.value);
        }
      });
    });
    const options = [];
    servicePoints.forEach(s => {
      if (!serviceOwners.includes(s.id) || s.name === 'None') {
        options.push({ value: s.id, label: s.name });
      }
    });

    const fieldComponents = {
      'servicePointOwner': ({ fieldProps }) => (
        <Field
          {...fieldProps}
          id="owner-service-point"
          component={MultiSelection}
          onChange={this.onChangeSelection}
          dataOptions={options}
          renderToOverlay
          marginBottom0
          validationEnabled
          onBlur={e => { e.preventDefault(); }}
        />
      )
    };

    const formatter = {
      'servicePointOwner': (value) => {
        const asp = value.servicePointOwner || [];
        const items = asp.map(a =>
{a.label}
);
        return
{items}
;
      }
    };

    return (
      <this.connectedControlledVocab
        {...this.props}
        baseUrl="owners"
        columnMapping={{
          'owner': formatMessage({ id: 'ui-users.owners.columns.owner' }),
          'desc': formatMessage({ id: 'ui-users.owners.columns.desc' }),
          'servicePointOwner': formatMessage({ id: 'ui-users.owners.columns.asp' }),
        }}
        fieldComponents={fieldComponents}
        formatter={formatter}
        hiddenFields={['lastUpdated', 'numberOfObjects']}
        id="settings-owners"
        label={formatMessage({ id: 'ui-users.owners.label' })}
        labelSingular={label}
        nameKey="owner"
        objectLabel=""
        records="owners"
        sortby="owner"
        validate={this.validate}
        visibleFields={['owner', 'desc', 'servicePointOwner']}
        warn={this.warn}
      />
    );
  }
}

export default injectIntl(withStripes(stripesConnect(OwnerSettings)));
<commit_msg>Rename function<commit_after>import _ from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import {
  injectIntl,
  intlShape,
  FormattedMessage,
} from 'react-intl';
import { Field } from 'redux-form';
import { MultiSelection } from '@folio/stripes/components';
import { ControlledVocab } from '@folio/stripes/smart-components';
import { stripesConnect, withStripes } from '@folio/stripes/core';

import { validate } from '../util';

class OwnerSettings extends React.Component {
  static manifest = Object.freeze({
    ownerServicePoints: {
      type: 'okapi',
      resource: 'service-points',
      path: 'service-points',
    },
    owners: {
      type: 'okapi',
      records: 'owners',
      path: 'owners',
      GET: {
        path: 'owners?query=cql.allRecords=1 sortby owner&limit=500'
      }
    },
  });

  static propTypes = {
    stripes: PropTypes.shape({
      connect: PropTypes.func.isRequired,
    }).isRequired,
    intl: intlShape.isRequired,
  };

  constructor(props) {
    super(props);

    this.connectedControlledVocab = props.stripes.connect(ControlledVocab);
  }

  validateItem = (item, index, items) => {
    const { intl: { formatMessage } } = this.props;
    const label = formatMessage({ id: 'ui-users.owners.singular' });
    const itemErrors = validate(item, index, items, 'owner', label);
    if (item.owner === 'Shared' && item.servicePointOwner) {
      itemErrors.owner = formatMessage({ id: 'ui-users.owners.noServicePoints' });
    }
    return itemErrors;
  }

  warn = ({ items }) => {
    const servicePoints = _.get(this.props.resources, ['ownerServicePoints', 'records', 0, 'servicepoints'], []);
    const none = servicePoints.find(s => s.name === 'None') || {};

    const warnings = [];
    if (Array.isArray(items)) {
      items.forEach((item, index) => {
        const itemWarning = {};

        const asp = item.servicePointOwner || [];

        asp.forEach(s => {
          if (s.value === none.id) {
            itemWarning.servicePointOwner = <FormattedMessage id="ui-users.owners.warning" />;
          }
        });

        if (Object.keys(itemWarning).length) {
          warnings[index] = itemWarning;
        }
      });
    }
    return { items: warnings };
  }

  render() {
    const {
      intl: { formatMessage },
      resources
    } = this.props;
    const label = formatMessage({ id: 'ui-users.owners.singular' });

    const rows = _.get(resources, ['owners', 'records'], []);
    const servicePoints = _.get(resources, ['ownerServicePoints', 'records', 0, 'servicepoints'], []);
    const serviceOwners = [];
    rows.forEach(o => {
      const asp = o.servicePointOwner || [];
      asp.forEach(s => {
        if (!serviceOwners.includes(s.value)) {
          serviceOwners.push(s.value);
        }
      });
    });
    const options = [];
    servicePoints.forEach(s => {
      if (!serviceOwners.includes(s.id) || s.name === 'None') {
        options.push({ value: s.id, label: s.name });
      }
    });

    const fieldComponents = {
      'servicePointOwner': ({ fieldProps }) => (
        <Field
          {...fieldProps}
          id="owner-service-point"
          component={MultiSelection}
          onChange={this.onChangeSelection}
          dataOptions={options}
          renderToOverlay
          marginBottom0
          validationEnabled
          onBlur={e => { e.preventDefault(); }}
        />
      )
    };

    const formatter = {
      'servicePointOwner': (value) => {
        const asp = value.servicePointOwner || [];
        const items = asp.map(a =>
{a.label}
);
        return
{items}
;
      }
    };

    return (
      <this.connectedControlledVocab
        {...this.props}
        baseUrl="owners"
        columnMapping={{
          'owner': formatMessage({ id: 'ui-users.owners.columns.owner' }),
          'desc': formatMessage({ id: 'ui-users.owners.columns.desc' }),
          'servicePointOwner': formatMessage({ id: 'ui-users.owners.columns.asp' }),
        }}
        fieldComponents={fieldComponents}
        formatter={formatter}
        hiddenFields={['lastUpdated', 'numberOfObjects']}
        id="settings-owners"
        label={formatMessage({ id: 'ui-users.owners.label' })}
        labelSingular={label}
        nameKey="owner"
        objectLabel=""
        records="owners"
        sortby="owner"
        validate={this.validateItem}
        visibleFields={['owner', 'desc', 'servicePointOwner']}
        warn={this.warn}
      />
    );
  }
}

export default injectIntl(withStripes(stripesConnect(OwnerSettings)));
<|endoftext|>


<commit_before>var TCM = TCM || {};

(function($) {

    var autoFocus = function(trigger) {
        $(trigger).click(function() {
            if ($(this).parent().hasClass('open')) {
                $(this).parent().find('textarea').focus();
            }
        });
    };

    var testCaseButtons = function(context) {
        $(context).find("button").click(
            function(event) {
                event.preventDefault();
                event.stopPropagation();
                var button = $(this),
                    testcase = button.closest(context),
                    container = button.closest("div.form"),
                    data = {
                        action: button.attr("data-action")
                    },
                    inputs = container.find("input"),
                    post = true;
                container.find("textarea").add(inputs).each(
                    function() {
                        var val = $(this).val();
                        if (val) {
                            data[$(this).attr("name")] = val;
                        } else {
                            $(this).siblings("ul.errorlist").remove();
                            $(this).before(
                                "

" +
                                    "This field is required." +
                                    "

"
                            );
                            $('.loadingCSS').detach();
                            $('.loading').removeClass("loading");
                            post = false;
                        }
                    }
                );
                if ( post ) {
                    $.post(
                        testcase.attr("data-action-url"),
                        data,
                        function(data) {
                            var id = testcase.attr("id");
                            testcase.replaceWith(data);
                            var newCase = "#" + id;
                            $(newCase).find('details').andSelf().html5accordion('summary');
                            testCaseButtons(newCase);
                            TCM.addLoading('button, a', testcase);
                            $('.loadingCSS').detach();
                            autoFocus('details.stepfail > summary');
                            autoFocus('details.testinvalid > summary');
                        }
                    );
                }
            }
        );
    };

    var selectRuns = function(context) {
        var context = $(context),
            environments = $('#environment').hide(),
            products = context.find('input[name="product"]'),
            cycles = context.find('input[name="cycle"]'),
            runs = context.find('input[name="run"]'),
            headers = context.find('h3 > a').click(function() {
                context.find('section').removeClass('focus');
                $(this).closest('section').addClass('focus');
            });
            context.find('header').each(function() {
                var scrollbarWidth = $(this).closest('section').css('width') - $(this).children('li').css('width');
                $(this).css('right', scrollbarWidth);
            });
        products.live('click', function() {
            var productName = $(this).data('id'),
                fakeAjaxCall = function(productName, callback) {
                    var response =
                        '
' +
                            '
' +
                                '<input type="radio" name="cycle" value="" id="' + productName + '_cycle_name_01" data-product="' + productName + '" data-cycle="01">' +
                                '' +
                                    '75%' +
                                    '' + productName + ' cycle name 01' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="cycle" value="" id="' + productName + '_cycle_name_02" data-product="' + productName + '" data-cycle="02">' +
                                '' +
                                    '100%' +
                                    '' + productName + ' cycle name 02' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="cycle" value="" id="' + productName + '_cycle_name_03" data-product="' + productName + '" data-cycle="03">' +
                                '' +
                                    '25%' +
                                    '' + productName + ' cycle name 03' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="cycle" value="" id="' + productName + '_cycle_name_04" data-product="' + productName + '" data-cycle="04">' +
                                '' +
                                    '17%' +
                                    '' + productName + ' cycle name 04' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="cycle" value="" id="' + productName + '_cycle_name_05" data-product="' + productName + '" data-cycle="05">' +
                                '' +
                                    '50%' +
                                    '' + productName + ' cycle name 05' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="cycle" value="" id="' + productName + '_cycle_name_06" data-product="' + productName + '" data-cycle="06">' +
                                '' +
                                    '83%' +
                                    '' + productName + ' cycle name 06' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                        '
';
                    if (productName === 'tcm') {
                        var response =
                            '
' +
                                '
' +
                                    '<input type="radio" name="cycle" value="" id="' + productName + '_cycle_name_01" data-product="' + productName + '" data-cycle="01">' +
                                    '' +
                                        '75%' +
                                        '' + productName + ' cycle name 01' +
                                        '<time class="start">01/07/2011</time>' +
                                        '<time class="end">11/10/2011</time>' +
                                    '' +
                                '
' +
                                '
' +
                                    '<input type="radio" name="cycle" value="" id="' + productName + '_cycle_name_02" data-product="' + productName + '" data-cycle="02">' +
                                    '' +
                                        '100%' +
                                        '' + productName + ' cycle name 02' +
                                        '<time class="start">01/07/2011</time>' +
                                        '<time class="end">11/10/2011</time>' +
                                    '' +
                                '
' +
                                '
' +
                                    '<input type="radio" name="cycle" value="" id="' + productName + '_cycle_name_03" data-product="' + productName + '" data-cycle="03">' +
                                    '' +
                                        '25%' +
                                        '' + productName + ' cycle name 03' +
                                        '<time class="start">01/07/2011</time>' +
                                        '<time class="end">11/10/2011</time>' +
                                    '' +
                                '
' +
                            '
';
                    }
                    callback(response);
                };
            fakeAjaxCall(
                productName,
                function(data) {
                    $('section.cycles ul').remove();
                    $('section.cycles').append(data);
                    $('section.runs ul').remove();
                }
            );
            $(this).closest('section.products').removeClass('focus');
            context.find('section.runs').removeClass('focus');
            context.find('section.cycles').addClass('focus');
            environments.slideUp();
            context.find('input:checked').addClass('selected');
            context.find('input:not(:checked)').removeClass('selected');
        });
        cycles.live('click', function() {
            var productName = $(this).data('product'),
                cycleNumber = $(this).data('cycle'),
                fakeAjaxCall = function(productName, cycleNumber, callback) {
                    var response =
                        '
' +
                            '
' +
                                '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_01">' +
                                '' +
                                    '' + productName + ' run 0' + cycleNumber + '-01' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_02">' +
                                '' +
                                    '' + productName + ' run 0' + cycleNumber + '-02' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_03">' +
                                '' +
                                    '' + productName + ' run 0' + cycleNumber + '-03' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_04">' +
                                '' +
                                    '' + productName + ' run 0' + cycleNumber + '-04' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_05">' +
                                '' +
                                    '' + productName + ' run 0' + cycleNumber + '-05' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_06">' +
                                '' +
                                    '' + productName + ' run 0' + cycleNumber + '-06' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                        '
';
                    if (cycleNumber === 1) {
                        var response =
                            '
' +
                                '
' +
                                    '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_01">' +
                                    '' +
                                        '' + productName + ' run 0' + cycleNumber + '-01' +
                                        '<time class="start">01/07/2011</time>' +
                                        '<time class="end">11/10/2011</time>' +
                                    '' +
                                '
' +
                                '
' +
                                    '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_02">' +
                                    '' +
                                        '' + productName + ' run 0' + cycleNumber + '-02' +
                                        '<time class="start">01/07/2011</time>' +
                                        '<time class="end">11/10/2011</time>' +
                                    '' +
                                '
' +
                                '
' +
                                    '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_03">' +
                                    '' +
                                        '' + productName + ' run 0' + cycleNumber + '-03' +
                                        '<time class="start">01/07/2011</time>' +
                                        '<time class="end">11/10/2011</time>' +
                                    '' +
                                '
' +
                                '
' +
                                    '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_04">' +
                                    '' +
                                        '' + productName + ' run 0' + cycleNumber + '-04' +
                                        '<time class="start">01/07/2011</time>' +
                                        '<time class="end">11/10/2011</time>' +
                                    '' +
                                '
' +
                            '
';
                    }
                    callback(response);
                };
            fakeAjaxCall(
                productName,
                cycleNumber,
                function(data) {
                    $('section.runs ul').remove();
                    $('section.runs').append(data);
                }
            );
            $(this).closest('section.cycles').removeClass('focus');
            context.find('section.products').removeClass('focus');
            context.find('section.runs').addClass('focus');
            environments.slideUp();
            context.find('input:checked').addClass('selected');
            context.find('input:not(:checked)').removeClass('selected');
        });
        runs.live('click', function() {
            environments.slideDown();
            context.find('input:checked').addClass('selected');
            context.find('input:not(:checked)').removeClass('selected');
        });
        $('input.selected').live('click', function() {
            context.find('section').removeClass('focus');
            $(this).closest('section').addClass('focus');
        });
    };

    $(function() {
        autoFocus('details.stepfail > summary');
        autoFocus('details.testinvalid > summary');
        testCaseButtons("details.test");
        $("div[role=main]").ajaxError(
            function(event, request, settings) {
                $(this).prepend(
                    '' + request.responseText + ''
                );
                $('.loadingCSS').detach();
                $('.loading').removeClass("loading");
            }
        );
        selectRuns('#selectruns');
    });

})(jQuery);<commit_msg>js selectRuns added
s back to html<commit_after>var TCM = TCM || {};

(function($) {

    var autoFocus = function(trigger) {
        $(trigger).click(function() {
            if ($(this).parent().hasClass('open')) {
                $(this).parent().find('textarea').focus();
            }
        });
    };

    var testCaseButtons = function(context) {
        $(context).find("button").click(
            function(event) {
                event.preventDefault();
                event.stopPropagation();
                var button = $(this),
                    testcase = button.closest(context),
                    container = button.closest("div.form"),
                    data = {
                        action: button.attr("data-action")
                    },
                    inputs = container.find("input"),
                    post = true;
                container.find("textarea").add(inputs).each(
                    function() {
                        var val = $(this).val();
                        if (val) {
                            data[$(this).attr("name")] = val;
                        } else {
                            $(this).siblings("ul.errorlist").remove();
                            $(this).before(
                                "

" +
                                    "This field is required." +
                                    "

"
                            );
                            $('.loadingCSS').detach();
                            $('.loading').removeClass("loading");
                            post = false;
                        }
                    }
                );
                if ( post ) {
                    $.post(
                        testcase.attr("data-action-url"),
                        data,
                        function(data) {
                            var id = testcase.attr("id");
                            testcase.replaceWith(data);
                            var newCase = "#" + id;
                            $(newCase).find('details').andSelf().html5accordion('summary');
                            testCaseButtons(newCase);
                            TCM.addLoading('button, a', testcase);
                            $('.loadingCSS').detach();
                            autoFocus('details.stepfail > summary');
                            autoFocus('details.testinvalid > summary');
                        }
                    );
                }
            }
        );
    };

    var selectRuns = function(context) {
        var context = $(context),
            environments = $('#environment').hide(),
            products = context.find('input[name="product"]'),
            cycles = context.find('input[name="cycle"]'),
            runs = context.find('input[name="run"]'),
            headers = context.find('h3 > a').click(function() {
                context.find('section').removeClass('focus');
                $(this).closest('section').addClass('focus');
            });
            context.find('header').each(function() {
                var scrollbarWidth = $(this).closest('section').css('width') - $(this).children('li').css('width');
                $(this).css('right', scrollbarWidth);
            });
        products.live('click', function() {
            var productName = $(this).data('id'),
                fakeAjaxCall = function(productName, callback) {
                    var response =
                        '
' +
                            '
' +
                                '<input type="radio" name="cycle" value="" id="' + productName + '_cycle_name_01" data-product="' + productName + '" data-cycle="01">' +
                                '' +
                                    '75%' +
                                    '' + productName + ' cycle name 01' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="cycle" value="" id="' + productName + '_cycle_name_02" data-product="' + productName + '" data-cycle="02">' +
                                '' +
                                    '100%' +
                                    '' + productName + ' cycle name 02' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="cycle" value="" id="' + productName + '_cycle_name_03" data-product="' + productName + '" data-cycle="03">' +
                                '' +
                                    '25%' +
                                    '' + productName + ' cycle name 03' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="cycle" value="" id="' + productName + '_cycle_name_04" data-product="' + productName + '" data-cycle="04">' +
                                '' +
                                    '17%' +
                                    '' + productName + ' cycle name 04' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="cycle" value="" id="' + productName + '_cycle_name_05" data-product="' + productName + '" data-cycle="05">' +
                                '' +
                                    '50%' +
                                    '' + productName + ' cycle name 05' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="cycle" value="" id="' + productName + '_cycle_name_06" data-product="' + productName + '" data-cycle="06">' +
                                '' +
                                    '83%' +
                                    '' + productName + ' cycle name 06' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                        '
';
                    if (productName === 'tcm') {
                        var response =
                            '
' +
                                '
' +
                                    '<input type="radio" name="cycle" value="" id="' + productName + '_cycle_name_01" data-product="' + productName + '" data-cycle="01">' +
                                    '' +
                                        '75%' +
                                        '' + productName + ' cycle name 01' +
                                        '<time class="start">01/07/2011</time>' +
                                        '<time class="end">11/10/2011</time>' +
                                    '' +
                                '
' +
                                '
' +
                                    '<input type="radio" name="cycle" value="" id="' + productName + '_cycle_name_02" data-product="' + productName + '" data-cycle="02">' +
                                    '' +
                                        '100%' +
                                        '' + productName + ' cycle name 02' +
                                        '<time class="start">01/07/2011</time>' +
                                        '<time class="end">11/10/2011</time>' +
                                    '' +
                                '
' +
                                '
' +
                                    '<input type="radio" name="cycle" value="" id="' + productName + '_cycle_name_03" data-product="' + productName + '" data-cycle="03">' +
                                    '' +
                                        '25%' +
                                        '' + productName + ' cycle name 03' +
                                        '<time class="start">01/07/2011</time>' +
                                        '<time class="end">11/10/2011</time>' +
                                    '' +
                                '
' +
                            '
';
                    }
                    callback(response);
                };
            fakeAjaxCall(
                productName,
                function(data) {
                    $('section.cycles ul').html(data);
                    $('section.runs ul').empty();
                }
            );
            $(this).closest('section.products').removeClass('focus');
            context.find('section.runs').removeClass('focus');
            context.find('section.cycles').addClass('focus');
            environments.slideUp();
            context.find('input:checked').addClass('selected');
            context.find('input:not(:checked)').removeClass('selected');
        });
        cycles.live('click', function() {
            var productName = $(this).data('product'),
                cycleNumber = $(this).data('cycle'),
                fakeAjaxCall = function(productName, cycleNumber, callback) {
                    var response =
                        '
' +
                            '
' +
                                '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_01">' +
                                '' +
                                    '' + productName + ' run 0' + cycleNumber + '-01' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_02">' +
                                '' +
                                    '' + productName + ' run 0' + cycleNumber + '-02' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_03">' +
                                '' +
                                    '' + productName + ' run 0' + cycleNumber + '-03' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_04">' +
                                '' +
                                    '' + productName + ' run 0' + cycleNumber + '-04' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_05">' +
                                '' +
                                    '' + productName + ' run 0' + cycleNumber + '-05' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                            '
' +
                                '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_06">' +
                                '' +
                                    '' + productName + ' run 0' + cycleNumber + '-06' +
                                    '<time class="start">01/07/2011</time>' +
                                    '<time class="end">11/10/2011</time>' +
                                '' +
                            '
' +
                        '
';
                    if (cycleNumber === 1) {
                        var response =
                            '
' +
                                '
' +
                                    '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_01">' +
                                    '' +
                                        '' + productName + ' run 0' + cycleNumber + '-01' +
                                        '<time class="start">01/07/2011</time>' +
                                        '<time class="end">11/10/2011</time>' +
                                    '' +
                                '
' +
                                '
' +
                                    '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_02">' +
                                    '' +
                                        '' + productName + ' run 0' + cycleNumber + '-02' +
                                        '<time class="start">01/07/2011</time>' +
                                        '<time class="end">11/10/2011</time>' +
                                    '' +
                                '
' +
                                '
' +
                                    '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_03">' +
                                    '' +
                                        '' + productName + ' run 0' + cycleNumber + '-03' +
                                        '<time class="start">01/07/2011</time>' +
                                        '<time class="end">11/10/2011</time>' +
                                    '' +
                                '
' +
                                '
' +
                                    '<input type="radio" name="run" value="" id="' + productName + '_run_0' + cycleNumber + '_04">' +
                                    '' +
                                        '' + productName + ' run 0' + cycleNumber + '-04' +
                                        '<time class="start">01/07/2011</time>' +
                                        '<time class="end">11/10/2011</time>' +
                                    '' +
                                '
' +
                            '
';
                    }
                    callback(response);
                };
            fakeAjaxCall(
                productName,
                cycleNumber,
                function(data) {
                    $('section.runs ul').html(data);
                }
            );
            $(this).closest('section.cycles').removeClass('focus');
            context.find('section.products').removeClass('focus');
            context.find('section.runs').addClass('focus');
            environments.slideUp();
            context.find('input:checked').addClass('selected');
            context.find('input:not(:checked)').removeClass('selected');
        });
        runs.live('click', function() {
            environments.slideDown();
            context.find('input:checked').addClass('selected');
            context.find('input:not(:checked)').removeClass('selected');
        });
        $('input.selected').live('click', function() {
            context.find('section').removeClass('focus');
            $(this).closest('section').addClass('focus');
        });
    };

    $(function() {
        autoFocus('details.stepfail > summary');
        autoFocus('details.testinvalid > summary');
        testCaseButtons("details.test");
        $("div[role=main]").ajaxError(
            function(event, request, settings) {
                $(this).prepend(
                    '' + request.responseText + ''
                );
                $('.loadingCSS').detach();
                $('.loading').removeClass("loading");
            }
        );
        selectRuns('#selectruns');
    });

})(jQuery);<|endoftext|>


<commit_before>/* global XMLHttpRequest */
import React from 'react'
import PropTypes from 'prop-types'
import Autosuggest from 'react-autosuggest'
import match from 'autosuggest-highlight/match'
import parse from 'autosuggest-highlight/parse'
import Paper from '@material-ui/core/Paper'
import MenuItem from '@material-ui/core/MenuItem'
import { withStyles } from '@material-ui/core/styles'
import ChipInput from '../../src/ChipInput'

const suggestions = [
  { name: 'Afghanistan' },
  { name: 'Aland Islands' },
  { name: 'Albania' },
  { name: 'Algeria' },
  { name: 'American Samoa' },
  { name: 'Andorra' },
  { name: 'Angola' },
  { name: 'Anguilla' },
  { name: 'Antarctica' },
  { name: 'Antigua and Barbuda' },
  { name: 'Argentina' },
  { name: 'Armenia' },
  { name: 'Aruba' },
  { name: 'Australia' },
  { name: 'Austria' },
  { name: 'Azerbaijan' },
  { name: 'Bahamas' },
  { name: 'Bahrain' },
  { name: 'Bangladesh' },
  { name: 'Barbados' },
  { name: 'Belarus' },
  { name: 'Belgium' },
  { name: 'Belize' },
  { name: 'Benin' },
  { name: 'Bermuda' },
  { name: 'Bhutan' },
  { name: 'Bolivia, Plurinational State of' },
  { name: 'Bonaire, Sint Eustatius and Saba' },
  { name: 'Bosnia and Herzegovina' },
  { name: 'Botswana' },
  { name: 'Bouvet Island' },
  { name: 'Brazil' },
  { name: 'British Indian Ocean Territory' },
  { name: 'Brunei Darussalam' }
]

function renderInput (inputProps) {
  const { classes, autoFocus, value, onChange, onAdd, onDelete, chips, ref, ...other } = inputProps

  return (
    <ChipInput
      clearInputValueOnChange
      onUpdateInput={onChange}
      onAdd={onAdd}
      onDelete={onDelete}
      value={chips}
      inputRef={ref}
      {...other}
    />
  )
}

function renderSuggestion (suggestion, { query, isHighlighted }) {
  const matches = match(suggestion.name, query)
  const parts = parse(suggestion.name, matches)

  return (
    <MenuItem
      selected={isHighlighted}
      component='div'
      onMouseDown={(e) => e.preventDefault()} // prevent the click causing the input to be blurred
    >

        {parts.map((part, index) => {
          return part.highlight ? (

              {part.text}

          ) : (

              {part.text}

          )
        })}

    </MenuItem>
  )
}

function renderSuggestionsContainer (options) {
  const { containerProps, children } = options

  return (
    <Paper {...containerProps} square>
      {children}
    </Paper>
  )
}

function getSuggestionValue (suggestion) {
  return suggestion.name
}

function getSuggestions (value) {
  const inputValue = value.trim().toLowerCase()
  const inputLength = inputValue.length
  let count = 0

  return inputLength === 0
    ? []
    : suggestions.filter(suggestion => {
      const keep =
          count < 5 && suggestion.name.toLowerCase().slice(0, inputLength) === inputValue

      if (keep) {
        count += 1
      }

      return keep
    })
}

const styles = theme => ({
  container: {
    flexGrow: 1,
    position: 'relative',
    height: 200
  },
  suggestionsContainerOpen: {
    position: 'absolute',
    marginTop: theme.spacing.unit,
    marginBottom: theme.spacing.unit * 3,
    left: 0,
    right: 0
  },
  suggestion: {
    display: 'block'
  },
  suggestionsList: {
    margin: 0,
    padding: 0,
    listStyleType: 'none'
  },
  textField: {
    width: '100%'
  }
})

class ReactAutosuggestExample extends React.Component {
  state = {
    // value: '',
    suggestions: [],
    value: [],
    textFieldInput: ''
  };

  handleSuggestionsFetchRequested = ({ value }) => {
    this.setState({
      suggestions: getSuggestions(value)
    })
  };

  handleSuggestionsClearRequested = () => {
    this.setState({
      suggestions: []
    })
  };

  handletextFieldInputChange = (event, { newValue }) => {
    this.setState({
      textFieldInput: newValue
    })
  };

  handleAddChip (chip) {
    this.setState({
      value: [...this.state.value, chip],
      textFieldInput: ''
    })
  }
  handleDeleteChip (chip, index) {
    let temp = this.state.value
    temp.splice(index, 1)
    this.setState({ value: temp })
  }

  render () {
    const { classes, ...rest } = this.props

    return (
      <Autosuggest
        theme={{
          container: classes.container,
          suggestionsContainerOpen: classes.suggestionsContainerOpen,
          suggestionsList: classes.suggestionsList,
          suggestion: classes.suggestion
        }}
        renderInputComponent={renderInput}
        suggestions={this.state.suggestions}
        onSuggestionsFetchRequested={this.handleSuggestionsFetchRequested}
        onSuggestionsClearRequested={this.handleSuggestionsClearRequested}
        renderSuggestionsContainer={renderSuggestionsContainer}
        getSuggestionValue={getSuggestionValue}
        renderSuggestion={renderSuggestion}
        onSuggestionSelected={(e, { suggestionValue }) => { this.handleAddChip(suggestionValue); e.preventDefault() }}
        focusInputOnSuggestionClick={false}
        inputProps={{
          classes,
          chips: this.state.value,
          onChange: this.handletextFieldInputChange,
          value: this.state.textFieldInput,
          onAdd: (chip) => this.handleAddChip(chip),
          onDelete: (chip, index) => this.handleDeleteChip(chip, index),
          ...rest
        }}
      />
    )
  }
}

ReactAutosuggestExample.propTypes = {
  classes: PropTypes.object.isRequired
}

exports.ReactAutosuggestExample = withStyles(styles)(ReactAutosuggestExample)

class ReactAutosuggestRemoteExample extends React.Component {
  state = {
    // value: '',
    suggestions: [],
    value: [],
    textFieldInput: ''
  };

  handleSuggestionsFetchRequested = ({ value }) => {
    var oReq = new XMLHttpRequest()
    var that = this
    oReq.addEventListener('load', function () {
      that.setState({
        suggestions: oReq.status === 200 ? JSON.parse(this.responseText) : []
      })
    })
    oReq.open('GET', 'https://restcountries.eu/rest/v2/name/' + value)
    oReq.send()
  };

  handleSuggestionsClearRequested = () => {
    this.setState({
      suggestions: []
    })
  };

  handletextFieldInputChange = (event, { newValue }) => {
    this.setState({
      textFieldInput: newValue
    })
  };

  handleAddChip (chip) {
    this.setState({ value: this.state.value.concat([chip]) })
  }
  handleDeleteChip (chip, index) {
    let temp = this.state.value
    temp.splice(index, 1)
    this.setState({ value: temp })
  }

  render () {
    const { classes, ...rest } = this.props

    return (
      <Autosuggest
        theme={{
          container: classes.container,
          suggestionsContainerOpen: classes.suggestionsContainerOpen,
          suggestionsList: classes.suggestionsList,
          suggestion: classes.suggestion
        }}
        renderInputComponent={renderInput}
        suggestions={this.state.suggestions}
        onSuggestionsFetchRequested={this.handleSuggestionsFetchRequested}
        onSuggestionsClearRequested={this.handleSuggestionsClearRequested}
        renderSuggestionsContainer={renderSuggestionsContainer}
        getSuggestionValue={getSuggestionValue}
        renderSuggestion={renderSuggestion}
        onSuggestionSelected={(e, { suggestionValue }) => { this.handleAddChip(suggestionValue); e.preventDefault() }}
        focusInputOnSuggestionClick={false}
        inputProps={{
          classes,
          chips: this.state.value,
          onChange: this.handletextFieldInputChange,
          value: this.state.textFieldInput,
          onAdd: (chip) => this.handleAddChip(chip),
          onDelete: (chip, index) => this.handleDeleteChip(chip, index),
          ...rest
        }}
      />
    )
  }
}

ReactAutosuggestRemoteExample.propTypes = {
  classes: PropTypes.object.isRequired
}
exports.ReactAutosuggestRemoteExample = withStyles(styles)(ReactAutosuggestRemoteExample)
<commit_msg>Update the react-autosuggest example.<commit_after>/* global XMLHttpRequest */
import React from 'react'
import PropTypes from 'prop-types'
import Autosuggest from 'react-autosuggest'
import match from 'autosuggest-highlight/match'
import parse from 'autosuggest-highlight/parse'
import Paper from '@material-ui/core/Paper'
import MenuItem from '@material-ui/core/MenuItem'
import { withStyles } from '@material-ui/core/styles'
import ChipInput from '../../src/ChipInput'

const suggestions = [
  { name: 'Afghanistan' },
  { name: 'Aland Islands' },
  { name: 'Albania' },
  { name: 'Algeria' },
  { name: 'American Samoa' },
  { name: 'Andorra' },
  { name: 'Angola' },
  { name: 'Anguilla' },
  { name: 'Antarctica' },
  { name: 'Antigua and Barbuda' },
  { name: 'Argentina' },
  { name: 'Armenia' },
  { name: 'Aruba' },
  { name: 'Australia' },
  { name: 'Austria' },
  { name: 'Azerbaijan' },
  { name: 'Bahamas' },
  { name: 'Bahrain' },
  { name: 'Bangladesh' },
  { name: 'Barbados' },
  { name: 'Belarus' },
  { name: 'Belgium' },
  { name: 'Belize' },
  { name: 'Benin' },
  { name: 'Bermuda' },
  { name: 'Bhutan' },
  { name: 'Bolivia, Plurinational State of' },
  { name: 'Bonaire, Sint Eustatius and Saba' },
  { name: 'Bosnia and Herzegovina' },
  { name: 'Botswana' },
  { name: 'Bouvet Island' },
  { name: 'Brazil' },
  { name: 'British Indian Ocean Territory' },
  { name: 'Brunei Darussalam' }
]

function renderInput (inputProps) {
  const { classes, autoFocus, value, onChange, onAdd, onDelete, chips, ref, ...other } = inputProps

  return (
    <ChipInput
      clearInputValueOnChange
      onUpdateInput={onChange}
      onAdd={onAdd}
      onDelete={onDelete}
      value={chips}
      inputRef={ref}
      {...other}
    />
  )
}

function renderSuggestion (suggestion, { query, isHighlighted }) {
  const matches = match(suggestion.name, query)
  const parts = parse(suggestion.name, matches)

  return (
    <MenuItem
      selected={isHighlighted}
      component='div'
      onMouseDown={(e) => e.preventDefault()} // prevent the click causing the input to be blurred
    >

        {parts.map((part, index) => {
          return part.highlight ? (

              {part.text}

          ) : (

              {part.text}

          )
        })}

    </MenuItem>
  )
}

function renderSuggestionsContainer (options) {
  const { containerProps, children } = options

  return (
    <Paper {...containerProps} square>
      {children}
    </Paper>
  )
}

function getSuggestionValue (suggestion) {
  return suggestion.name
}

function getSuggestions (value) {
  const inputValue = value.trim().toLowerCase()
  const inputLength = inputValue.length
  let count = 0

  return inputLength === 0
    ? []
    : suggestions.filter(suggestion => {
      const keep =
          count < 5 && suggestion.name.toLowerCase().slice(0, inputLength) === inputValue

      if (keep) {
        count += 1
      }

      return keep
    })
}

const styles = theme => ({
  container: {
    flexGrow: 1,
    position: 'relative',
    height: 200
  },
  suggestionsContainerOpen: {
    position: 'absolute',
    marginTop: theme.spacing.unit,
    marginBottom: theme.spacing.unit * 3,
    left: 0,
    right: 0
  },
  suggestion: {
    display: 'block'
  },
  suggestionsList: {
    margin: 0,
    padding: 0,
    listStyleType: 'none'
  },
  textField: {
    width: '100%'
  }
})

class ReactAutosuggest extends React.Component {
  state = {
    // value: '',
    suggestions: [],
    value: [],
    textFieldInput: ''
  };

  handleSuggestionsFetchRequested = ({ value }) => {
    this.setState({
      suggestions: getSuggestions(value)
    })
  };

  handleSuggestionsClearRequested = () => {
    this.setState({
      suggestions: []
    })
  };

  handletextFieldInputChange = (event, { newValue }) => {
    this.setState({
      textFieldInput: newValue
    })
  };

  handleAddChip (chip) {
    this.setState(({ value }) => ({
      value: [...value, chip],
      textFieldInput: ''
    }))
  }

  handleDeleteChip (chip, index) {
    this.setState(({ value }) => {
      const temp = value.slice()
      temp.splice(index, 1)
      return {
        value: temp
      }
    })
  };

  render () {
    const { classes, ...other } = this.props

    return (
      <Autosuggest
        theme={{
          container: classes.container,
          suggestionsContainerOpen: classes.suggestionsContainerOpen,
          suggestionsList: classes.suggestionsList,
          suggestion: classes.suggestion
        }}
        renderInputComponent={renderInput}
        suggestions={this.state.suggestions}
        onSuggestionsFetchRequested={this.handleSuggestionsFetchRequested}
        onSuggestionsClearRequested={this.handleSuggestionsClearRequested}
        renderSuggestionsContainer={renderSuggestionsContainer}
        getSuggestionValue={getSuggestionValue}
        renderSuggestion={renderSuggestion}
        onSuggestionSelected={(e, { suggestionValue }) => { this.handleAddChip(suggestionValue); e.preventDefault() }}
        focusInputOnSuggestionClick={false}
        inputProps={{
          classes,
          chips: this.state.value,
          value: this.state.textFieldInput,
          onChange: this.handletextFieldInputChange,
          onAdd: (chip) => this.handleAddChip(chip),
          onDelete: (chip, index) => this.handleDeleteChip(chip, index),
          ...other
        }}
      />
    )
  }
}

ReactAutosuggest.propTypes = {
  classes: PropTypes.object.isRequired
}

export const ReactAutosuggestExample = withStyles(styles)(ReactAutosuggest)

class ReactAutosuggestRemote extends React.Component {
  state = {
    // value: '',
    suggestions: [],
    value: [],
    textFieldInput: ''
  };

  handleSuggestionsFetchRequested = ({ value }) => {
    var oReq = new XMLHttpRequest()
    var that = this
    oReq.addEventListener('load', function () {
      that.setState({
        suggestions: oReq.status === 200 ? JSON.parse(this.responseText) : []
      })
    })
    oReq.open('GET', 'https://restcountries.eu/rest/v2/name/' + value)
    oReq.send()
  };

  handleSuggestionsClearRequested = () => {
    this.setState({
      suggestions: []
    })
  };

  handletextFieldInputChange = (event, { newValue }) => {
    this.setState({
      textFieldInput: newValue
    })
  };

  handleAddChip (chip) {
    this.setState({ value: this.state.value.concat([chip]) })
  }
  handleDeleteChip (chip, index) {
    let temp = this.state.value
    temp.splice(index, 1)
    this.setState({ value: temp })
  }

  render () {
    const { classes, ...rest } = this.props

    return (
      <Autosuggest
        theme={{
          container: classes.container,
          suggestionsContainerOpen: classes.suggestionsContainerOpen,
          suggestionsList: classes.suggestionsList,
          suggestion: classes.suggestion
        }}
        renderInputComponent={renderInput}
        suggestions={this.state.suggestions}
        onSuggestionsFetchRequested={this.handleSuggestionsFetchRequested}
        onSuggestionsClearRequested={this.handleSuggestionsClearRequested}
        renderSuggestionsContainer={renderSuggestionsContainer}
        getSuggestionValue={getSuggestionValue}
        renderSuggestion={renderSuggestion}
        onSuggestionSelected={(e, { suggestionValue }) => { this.handleAddChip(suggestionValue); e.preventDefault() }}
        focusInputOnSuggestionClick={false}
        inputProps={{
          classes,
          chips: this.state.value,
          onChange: this.handletextFieldInputChange,
          value: this.state.textFieldInput,
          onAdd: (chip) => this.handleAddChip(chip),
          onDelete: (chip, index) => this.handleDeleteChip(chip, index),
          ...rest
        }}
      />
    )
  }
}

ReactAutosuggestRemote.propTypes = {
  classes: PropTypes.object.isRequired
}
exports.ReactAutosuggestRemote = withStyles(styles)(ReactAutosuggestRemote)
<|endoftext|>


<commit_before>"use strict";

module.exports = ($scope, $interval, BMA, UIUtils, summary, bmapi, ws) => {

  let co = require('co');
  let moment = require('moment');

  bindBlockWS(() => {
    $scope.loadPowData();
  });
  const M = summary.current.monetaryMass || 0;
  // const nbUDperYear = Math.ceil(365.25 * 3600 * 24 / summary.parameters.dt);
  // const globalC = Math.round(Math.pow(1 + summary.parameters.c, nbUDperYear) * 100) / 100 - 1;
  let UD = summary.parameters.ud0;
  if (summary.lastUD) {
    UD = (1 + summary.parameters.c) * summary.lastUD;
  }
  $scope.current = summary.current;
  $scope.monetaryMass = parseInt(M / UD) || 0;
  $scope.server_started = true;
  $scope.server_stopped = false;
  $scope.phones = [];
  $scope.abc = 'abcdef';
  $scope.newIdentities = 2;

  $(".dropdown-button").dropdown({ constrainwidth: false });

  $scope.lastNearPoW = '';
  $scope.totalPoW = '...';
  $scope.sync_state = 'home.pulling.state.unkown';
  $scope.network_percent = 0;
  $scope.peer_percent = 0;
  $scope.has_pulled = false;
  $scope.is_pulling = false;
  $scope.last_pulling = 0;
  let start_block = 0;

  $interval(() => {
    if ($scope.last_pulling) {
      $scope.sync_state = $scope.is_pulling ? 'home.pulling.state.syncing' : 'home.pulling.state.synced';
      $scope.sync_time = moment($scope.last_pulling).fromNow();
    }
  }, 1000);

  $scope.loadPowData = () => co(function*() {
    let res = yield BMA.webmin.powSummary();
    $scope.pow_total = res.total;
    $scope.pow_mirror = res.mirror;
    $scope.pow_waiting = res.waiting;
  });

  ws.on(undefined, (data) => {
    if (data.type === 'started') {
      $scope.server_started = true;
      $scope.server_stopped = false;
      bindBlockWS();
      UIUtils.toast('general.server.started');
      $scope.$apply();
    }
    if (data.type === 'stopped') {
      $scope.server_stopped = true;
      $scope.server_started = false;
      UIUtils.toast('general.server.stopped');
      $scope.$apply();
    }
    if (data.type === 'pulling') {
      $scope.is_pulling = true;
      $scope.has_pulled = true;
      const event = data.value;
      if (($scope.last_pulling && event.type === 'start') || (!$scope.last_pulling && event.type !== 'end')) {
        $scope.last_pulling = moment();
      }
      if (event.type === 'peer') {
        $scope.network_percent = parseInt((event.data.number + 1) / event.data.length * 100);
        $scope.peer_percent = 100;
        start_block = 0;
      }
      if (event.type === 'applying') {
        if (!start_block) {
          start_block = event.data.number;
        }
        const total = event.data.last - start_block;
        const doneCount = event.data.number - start_block;
        $scope.peer_percent = parseInt(doneCount / total * 100);
      }
      if (event.type === 'end') {
        $scope.is_pulling = false;
        $scope.network_percent = 0;
        $scope.peer_percent = 0;
        start_block = 0;
      }
    }
    if (data.type === 'pow') {
      const pow = data.value;
      if (pow.found) {
        $scope.pow_waiting = true;
        $scope.lastNearPoW = '#' + pow.hash;
        $scope.$apply();
      } else {
        $scope.pow_waiting = false;
        $scope.lastNearPoW = '#' + pow.hash;
        $scope.$apply();
      }
    }
  });

  function bindBlockWS(cb) {
    BMA.websocket.block().on(undefined, (block) => {
      $scope.current = block;
      const M = $scope.current.monetaryMass || 0;
      let UD = summary.parameters.ud0;
      if (summary.lastUD) {
        UD = (1 + summary.parameters.c) * summary.lastUD;
      }
      $scope.monetaryMass = parseInt(M / UD) || 0;
      $scope.$apply();
      cb && cb();
    });
  }

  $scope.reconfigure_network = () => co(function *() {
    $scope.reconfiguring = true;
    let delay = Q.delay(1000);
    try {
      let netinferfaces = yield BMA.webmin.network.interfaces();
      let conf = {};
      conf.local_ipv4 = netinferfaces.auto.local.ipv4 || '';
      conf.local_ipv6 = netinferfaces.auto.local.ipv6 || '';
      conf.remote_ipv4 = netinferfaces.auto.remote.ipv4 || '';
      conf.remote_ipv6 = netinferfaces.auto.remote.ipv6 || '';
      conf.lport = netinferfaces.auto.local.port || 9330;
      conf.rport = netinferfaces.auto.remote.port || 9330;
      conf.upnp = netinferfaces.auto.remote.upnp || false;
      conf.dns = netinferfaces.auto.remote.dns || '';
      yield BMA.webmin.server.netConf({
        conf: conf
      });
      yield delay;
      $scope.should_reconfigure = false;
      UIUtils.toast('general.network.reconf_ok');
      $scope.$apply();
    } catch (e) {
      yield delay;
      $scope.reconfiguring = false;
      $scope.$apply();
    }
  });

  return co(function *() {
    yield $scope.startServer();
    try {
      yield [
        bmapi.origin.network.peering.self(),
        $scope.loadPowData()
      ];
    } catch (e) {
      console.log(e);
      $scope.should_reconfigure = true;
    }
  });
};
<commit_msg>Fixing #648 Monetary mass was still buggy<commit_after>"use strict";

module.exports = ($scope, $interval, BMA, UIUtils, summary, bmapi, ws) => {

  let co = require('co');
  let moment = require('moment');

  bindBlockWS(() => {
    $scope.loadPowData();
  });
  let M = summary.current.monetaryMass || 0;
  // const nbUDperYear = Math.ceil(365.25 * 3600 * 24 / summary.parameters.dt);
  // const globalC = Math.round(Math.pow(1 + summary.parameters.c, nbUDperYear) * 100) / 100 - 1;
  let UD = summary.parameters.ud0;
  if (summary.lastUDBlock) {
    UD = (1 + summary.parameters.c) * summary.lastUDBlock.dividend * Math.pow(10, summary.lastUDBlock.unitbase);
  }
  $scope.current = summary.current;
  $scope.monetaryMass = parseInt(M / UD) || 0;
  $scope.server_started = true;
  $scope.server_stopped = false;
  $scope.phones = [];
  $scope.abc = 'abcdef';
  $scope.newIdentities = 2;

  $(".dropdown-button").dropdown({ constrainwidth: false });

  $scope.lastNearPoW = '';
  $scope.totalPoW = '...';
  $scope.sync_state = 'home.pulling.state.unkown';
  $scope.network_percent = 0;
  $scope.peer_percent = 0;
  $scope.has_pulled = false;
  $scope.is_pulling = false;
  $scope.last_pulling = 0;
  let start_block = 0;

  $interval(() => {
    if ($scope.last_pulling) {
      $scope.sync_state = $scope.is_pulling ? 'home.pulling.state.syncing' : 'home.pulling.state.synced';
      $scope.sync_time = moment($scope.last_pulling).fromNow();
    }
  }, 1000);

  $scope.loadPowData = () => co(function*() {
    let res = yield BMA.webmin.powSummary();
    $scope.pow_total = res.total;
    $scope.pow_mirror = res.mirror;
    $scope.pow_waiting = res.waiting;
  });

  ws.on(undefined, (data) => {
    if (data.type === 'started') {
      $scope.server_started = true;
      $scope.server_stopped = false;
      bindBlockWS();
      UIUtils.toast('general.server.started');
      $scope.$apply();
    }
    if (data.type === 'stopped') {
      $scope.server_stopped = true;
      $scope.server_started = false;
      UIUtils.toast('general.server.stopped');
      $scope.$apply();
    }
    if (data.type === 'pulling') {
      $scope.is_pulling = true;
      $scope.has_pulled = true;
      const event = data.value;
      if (($scope.last_pulling && event.type === 'start') || (!$scope.last_pulling && event.type !== 'end')) {
        $scope.last_pulling = moment();
      }
      if (event.type === 'peer') {
        $scope.network_percent = parseInt((event.data.number + 1) / event.data.length * 100);
        $scope.peer_percent = 100;
        start_block = 0;
      }
      if (event.type === 'applying') {
        if (!start_block) {
          start_block = event.data.number;
        }
        const total = event.data.last - start_block;
        const doneCount = event.data.number - start_block;
        $scope.peer_percent = parseInt(doneCount / total * 100);
      }
      if (event.type === 'end') {
        $scope.is_pulling = false;
        $scope.network_percent = 0;
        $scope.peer_percent = 0;
        start_block = 0;
      }
    }
    if (data.type === 'pow') {
      const pow = data.value;
      if (pow.found) {
        $scope.pow_waiting = true;
        $scope.lastNearPoW = '#' + pow.hash;
        $scope.$apply();
      } else {
        $scope.pow_waiting = false;
        $scope.lastNearPoW = '#' + pow.hash;
        $scope.$apply();
      }
    }
  });

  function bindBlockWS(cb) {
    BMA.websocket.block().on(undefined, (block) => {
      $scope.current = block;
      let M = summary.current.monetaryMass || 0;
      let UD = summary.parameters.ud0;
      if (summary.lastUDBlock) {
        UD = (1 + summary.parameters.c) * summary.lastUDBlock.dividend * Math.pow(10, summary.lastUDBlock.unitbase);
      }
      $scope.monetaryMass = parseInt(M / UD) || 0;
      $scope.$apply();
      cb && cb();
    });
  }

  $scope.reconfigure_network = () => co(function *() {
    $scope.reconfiguring = true;
    let delay = Q.delay(1000);
    try {
      let netinferfaces = yield BMA.webmin.network.interfaces();
      let conf = {};
      conf.local_ipv4 = netinferfaces.auto.local.ipv4 || '';
      conf.local_ipv6 = netinferfaces.auto.local.ipv6 || '';
      conf.remote_ipv4 = netinferfaces.auto.remote.ipv4 || '';
      conf.remote_ipv6 = netinferfaces.auto.remote.ipv6 || '';
      conf.lport = netinferfaces.auto.local.port || 9330;
      conf.rport = netinferfaces.auto.remote.port || 9330;
      conf.upnp = netinferfaces.auto.remote.upnp || false;
      conf.dns = netinferfaces.auto.remote.dns || '';
      yield BMA.webmin.server.netConf({
        conf: conf
      });
      yield delay;
      $scope.should_reconfigure = false;
      UIUtils.toast('general.network.reconf_ok');
      $scope.$apply();
    } catch (e) {
      yield delay;
      $scope.reconfiguring = false;
      $scope.$apply();
    }
  });

  return co(function *() {
    yield $scope.startServer();
    try {
      yield [
        bmapi.origin.network.peering.self(),
        $scope.loadPowData()
      ];
    } catch (e) {
      console.log(e);
      $scope.should_reconfigure = true;
    }
  });
};
<|endoftext|>


<commit_before>
describe("Buttton Tests", function() {
    beforeEach(function() {
        var result = yr.run('main', { username: 'bs' });
        $('.content').append(result);

        nb.init();

        this.button = nb.find('button');
    });
    describe("Init", function() {
        it("Init", function() {
            expect(this.button).to.not.equal(null);
        });
    });
    describe("setText()", function() {

        it("check text", function() {
            this.button.setText("Privet");
            expect($(this.button.node).find('.nb-button__text').html()).to.equal("Privet");
        });

        it("check event", function() {

            var flag = false;
            this.button.on('nb-button_text-setted', function() {
                flag = true;
            });

            this.button.setText("Privet");
            expect(flag).to.ok();
        });
    });

    describe("getText()", function() {
        it("check text", function() {
            this.button.setText("SetText");
            expect(this.button.getText()).to.equal("SetText");
        });
    });

    describe("setUrl()", function() {
        it("check url", function() {
            this.button.setUrl("http://ya.ru");
            expect($(this.button.node).attr('href')).to.equal("http://ya.ru");
        });

        it("check event", function() {
            var flag = false;
            this.button.on('nb-button_url-setted', function() {
                flag = true;
            });

            this.button.setUrl("http://ya.ru");
            expect(flag).to.ok();
        });
    });

    describe("getUrl()", function() {
        it("check url", function() {
            this.button.setUrl("http://yandex.ru");
            expect(this.button.getUrl()).to.equal("http://yandex.ru");
        });
    });

    describe("disable()", function() {
        it("check state", function() {
            this.button.disable();
            expect(this.button.isEnabled()).to.not.ok();
        });

        it("check event", function() {
            var flag = true;

            this.button.on('nb-button_disabled', function() {
                flag = false;
            });

            this.button.disable();

            expect(flag).to.not.ok();
        });
    });

    describe("enable()", function() {
        it("check state", function() {
            this.button.disable();
            this.button.enable();
            expect(this.button.isEnabled()).to.ok();
        });

        it("check event", function() {
            var flag = false;
            this.button.on('nb-button_enabled', function() {
                flag = true;
            });

            this.button.disable();
            this.button.enable();
            expect(flag).to.ok();
        });
    });

    afterEach(function() {
        delete this.button;
    });
});<commit_msg>v0.1.26<commit_after>
describe("Buttton Tests", function() {
    beforeEach(function() {
        var result = yr.run('main', { username: 'bs' });
        $('.content').append(result);

        nb.init();

        this.button = nb.find('button');
    });
    describe("Init", function() {
        it("Init", function() {
            expect(this.button).to.not.equal(null);
        });
    });
    describe("setText()", function() {

        it("check text", function() {
            this.button.setText("Privet");
            expect($(this.button.node).find('.nb-button__text').html()).to.equal("Privet");
        });

        it("check event", function() {

            var flag = false;
            this.button.on('nb-button_text-setted', function() {
                flag = true;
            });

            this.button.setText("Privet");
            expect(flag).to.ok();
        });
    });

    describe("getText()", function() {
        it("check text", function() {
            this.button.setText("SetText");
            expect(this.button.getText()).to.equal("SetText");
        });
    });

    describe("setUrl()", function() {
        it("check url", function() {
            this.button.setUrl("http://ya.ru");
            expect($(this.button.node).attr('href')).to.equal("http://ya.ru");
        });

        it("check event", function() {
            var flag = false;
            this.button.on('nb-button_url-setted', function() {
                flag = true;
            });

            this.button.setUrl("http://ya.ru");
            expect(flag).to.ok();
        });
    });

    describe("getUrl()", function() {
        it("check url", function() {
            this.button.setUrl("http://yandex.ru");
            expect(this.button.getUrl()).to.equal("http://yandex.ru");
        });
    });

    describe("disable()", function() {
        it("check state", function() {
            this.button.disable();
            expect(this.button.isEnabled()).to.not.ok();
        });

        it("check event", function() {
            var flag = true;

            this.button.on('nb-button_disabled', function() {
                flag = false;
            });

            this.button.disable();

            expect(flag).to.not.ok();
        });
    });

    describe("enable()", function() {
        it("check state", function() {
            this.button.disable();
            this.button.enable();
            expect(this.button.isEnabled()).to.ok();
        });

        it("check event", function() {
            var flag = false;
            this.button.on('nb-button_enabled', function() {
                flag = true;
            });

            this.button.disable();
            this.button.enable();
            expect(flag).to.ok();
        });
    });

    afterEach(function() {
        delete this.button;
    });

    it("setUrl()", function () {
       button.setUrl("http://ya.ru");
       expect($(button.node).attr('href')).to.equal("http://ya.ru");
    });

    it("getUrl()", function () {
       $(button.node).removeAttr('href');
       button.setUrl("http://yandex.ru");
       expect(button.getUrl()).to.equal("http://yandex.ru");
    });
});<|endoftext|>