<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Redirect } from 'react-router';
import { Link } from 'react-router-dom';
import Accounts from './Accounts';
import Paymenttypes from './Paymenttypes';
import Amount from './Amount';

class Admin extends Component {
    constructor(props) {
        super(props);
        this.state = {...props};
    }

    componentDidMount() {
        this.props.onDeselectAccountInDropdown(this.state.firstTimeAfterLogin);
        this.props.onAccounts();
        this.props.onPaymenttypeList();
    }

    componentWillReceiveProps(props) {
        this.setState({...props});
    }

    render() {
        let {
            loginResponse,
            account,
            payment,
            paymenttype,
            amount,
            accounts,
            accountsMap,
            paymenttypes,
            paymenttypesMap,
            onAccountsFieldChange,
            onPaymenttypeFieldChange,
            onAmountFieldChange,
            onRegisterPayment,
            onLogout } = this.state;

        if (loginResponse.roles.length === 0) {
            return <Redirect to="/ukelonn/login" />;
        }

        return (

Registrer betaling

                <form onSubmit={ e => { e.preventDefault(); }}>
                    Velg hvem det skal betales til:
                    <Accounts  id="account-selector" accounts={accounts} accountsMap={accountsMap} account={account} paymenttype={paymenttype} onAccountsFieldChange={onAccountsFieldChange}/>

                    Til gode:<input id="account-balance" type="text" value={account.balance} readOnly="true" />

                    Type av utbetaling:
                    <Paymenttypes id="paymenttype-selector" paymenttypes={paymenttypes} paymenttypesMap={paymenttypesMap} account={account} paymenttype={paymenttype} onPaymenttypeFieldChange={onPaymenttypeFieldChange} />

                    Beløp:
                    <Amount id="amount" payment={payment} onAmountFieldChange={onAmountFieldChange} />

                    <button onClick={() => onRegisterPayment(payment)}>Registrer betaling</button>
                </form>

                <Link to="/ukelonn/performedjobs">Utforte jobber</Link>

                <Link to="/ukelonn/performedpayments">Siste utbetalinger til bruker</Link>

                <Link to="/ukelonn/admin/jobtypes">Administrere jobbtyper</Link>

                <Link to="/ukelonn/admin/paymenttypes">Administrere utbetalingstyper</Link>

                <button onClick={() => onLogout()}>Logout</button>

        );
    };
};

const emptyAccount = {
    accountId: -1,
    fullName: '',
    balance: 0.0,
};

const mapStateToProps = state => {
    if (!state.jobtypes.find((job) => job.id === -1)) {
        state.accounts.unshift(emptyAccount);
    }

    return {
        loginResponse: state.loginResponse,
        firstTimeAfterLogin: state.firstTimeAfterLogin,
        account: state.account,
        payment: state.payment,
        paymenttype: state.paymenttype,
        accounts: state.accounts,
        accountsMap: new Map(state.accounts.map(i => [i.fullName, i])),
        paymenttypes: state.paymenttypes,
        paymenttypesMap: new Map(state.paymenttypes.map(i => [i.transactionTypeName, i])),
    };
};

const mapDispatchToProps = dispatch => {
    return {
        onLogout: () => dispatch({ type: 'LOGOUT_REQUEST' }),
        onDeselectAccountInDropdown: (firstTimeAfterLogin) => {
            if (firstTimeAfterLogin) {
                dispatch({ type: 'UPDATE',
                           data: {
                               firstTimeAfterLogin: false,
                               account: emptyAccount,
                               payment: {
                                   account: emptyAccount,
                                   transactionAmount: 0.0,
                                   transactionTypeId: -1
                               }
                           }
                         });
            }
        },
        onAccounts: () => dispatch({ type: 'ACCOUNTS_REQUEST' }),
        onPaymenttypeList: () => dispatch({ type: 'PAYMENTTYPES_REQUEST' }),
        onAccountsFieldChange: (selectedValue, accountsMap, paymenttype) => {
            let account = accountsMap.get(selectedValue);
            let amount = (paymenttype.transactionAmount > 0) ? paymenttype.transactionAmount : account.balance;
            let changedField = {
                account,
                payment: {
                    transactionTypeId: paymenttype.id,
                    transactionAmount: amount,
                    account: account,
                },
            };
            dispatch({ type: 'UPDATE', data: changedField });
        },
        onPaymenttypeFieldChange: (selectedValue, paymenttypeMap, account) => {
            let paymenttype = paymenttypeMap.get(selectedValue);
            let amount = (paymenttype.transactionAmount > 0) ? paymenttype.transactionAmount : account.balance;
            let changedField = {
                paymenttype,
                payment: {
                    transactionTypeId: paymenttype.id,
                    transactionAmount: amount,
                    account: account,
                }
            };
            dispatch({ type: 'UPDATE', data: changedField });
        },
        onAmountFieldChange: (formValue, payment) => {
            let changedField = {
                payment: { ...payment, transactionAmount: formValue }
            };
            dispatch({ type: 'UPDATE', data: changedField });
        },
        onRegisterPayment: (payment) => dispatch({ type: 'REGISTERPAYMENT_REQUEST', payment }),
    };
};

Admin = connect(mapStateToProps, mapDispatchToProps)(Admin);

export default Admin;
<commit_msg>Check against accountId to avoid inserting duplicate empty accounts in accounts array<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Redirect } from 'react-router';
import { Link } from 'react-router-dom';
import Accounts from './Accounts';
import Paymenttypes from './Paymenttypes';
import Amount from './Amount';

class Admin extends Component {
    constructor(props) {
        super(props);
        this.state = {...props};
    }

    componentDidMount() {
        this.props.onDeselectAccountInDropdown(this.state.firstTimeAfterLogin);
        this.props.onAccounts();
        this.props.onPaymenttypeList();
    }

    componentWillReceiveProps(props) {
        this.setState({...props});
    }

    render() {
        let {
            loginResponse,
            account,
            payment,
            paymenttype,
            amount,
            accounts,
            accountsMap,
            paymenttypes,
            paymenttypesMap,
            onAccountsFieldChange,
            onPaymenttypeFieldChange,
            onAmountFieldChange,
            onRegisterPayment,
            onLogout } = this.state;

        if (loginResponse.roles.length === 0) {
            return <Redirect to="/ukelonn/login" />;
        }

        return (

Registrer betaling

                <form onSubmit={ e => { e.preventDefault(); }}>
                    Velg hvem det skal betales til:
                    <Accounts  id="account-selector" accounts={accounts} accountsMap={accountsMap} account={account} paymenttype={paymenttype} onAccountsFieldChange={onAccountsFieldChange}/>

                    Til gode:<input id="account-balance" type="text" value={account.balance} readOnly="true" />

                    Type av utbetaling:
                    <Paymenttypes id="paymenttype-selector" paymenttypes={paymenttypes} paymenttypesMap={paymenttypesMap} account={account} paymenttype={paymenttype} onPaymenttypeFieldChange={onPaymenttypeFieldChange} />

                    Beløp:
                    <Amount id="amount" payment={payment} onAmountFieldChange={onAmountFieldChange} />

                    <button onClick={() => onRegisterPayment(payment)}>Registrer betaling</button>
                </form>

                <Link to="/ukelonn/performedjobs">Utforte jobber</Link>

                <Link to="/ukelonn/performedpayments">Siste utbetalinger til bruker</Link>

                <Link to="/ukelonn/admin/jobtypes">Administrere jobbtyper</Link>

                <Link to="/ukelonn/admin/paymenttypes">Administrere utbetalingstyper</Link>

                <button onClick={() => onLogout()}>Logout</button>

        );
    };
};

const emptyAccount = {
    accountId: -1,
    fullName: '',
    balance: 0.0,
};

const mapStateToProps = state => {
    if (!state.accounts.find((account) => account.accountId === -1)) {
        state.accounts.unshift(emptyAccount);
    }

    return {
        loginResponse: state.loginResponse,
        firstTimeAfterLogin: state.firstTimeAfterLogin,
        account: state.account,
        payment: state.payment,
        paymenttype: state.paymenttype,
        accounts: state.accounts,
        accountsMap: new Map(state.accounts.map(i => [i.fullName, i])),
        paymenttypes: state.paymenttypes,
        paymenttypesMap: new Map(state.paymenttypes.map(i => [i.transactionTypeName, i])),
    };
};

const mapDispatchToProps = dispatch => {
    return {
        onLogout: () => dispatch({ type: 'LOGOUT_REQUEST' }),
        onDeselectAccountInDropdown: (firstTimeAfterLogin) => {
            if (firstTimeAfterLogin) {
                dispatch({ type: 'UPDATE',
                           data: {
                               firstTimeAfterLogin: false,
                               account: emptyAccount,
                               payment: {
                                   account: emptyAccount,
                                   transactionAmount: 0.0,
                                   transactionTypeId: -1
                               }
                           }
                         });
            }
        },
        onAccounts: () => dispatch({ type: 'ACCOUNTS_REQUEST' }),
        onPaymenttypeList: () => dispatch({ type: 'PAYMENTTYPES_REQUEST' }),
        onAccountsFieldChange: (selectedValue, accountsMap, paymenttype) => {
            let account = accountsMap.get(selectedValue);
            let amount = (paymenttype.transactionAmount > 0) ? paymenttype.transactionAmount : account.balance;
            let changedField = {
                account,
                payment: {
                    transactionTypeId: paymenttype.id,
                    transactionAmount: amount,
                    account: account,
                },
            };
            dispatch({ type: 'UPDATE', data: changedField });
        },
        onPaymenttypeFieldChange: (selectedValue, paymenttypeMap, account) => {
            let paymenttype = paymenttypeMap.get(selectedValue);
            let amount = (paymenttype.transactionAmount > 0) ? paymenttype.transactionAmount : account.balance;
            let changedField = {
                paymenttype,
                payment: {
                    transactionTypeId: paymenttype.id,
                    transactionAmount: amount,
                    account: account,
                }
            };
            dispatch({ type: 'UPDATE', data: changedField });
        },
        onAmountFieldChange: (formValue, payment) => {
            let changedField = {
                payment: { ...payment, transactionAmount: formValue }
            };
            dispatch({ type: 'UPDATE', data: changedField });
        },
        onRegisterPayment: (payment) => dispatch({ type: 'REGISTERPAYMENT_REQUEST', payment }),
    };
};

Admin = connect(mapStateToProps, mapDispatchToProps)(Admin);

export default Admin;
<|endoftext|>


<commit_before>/**
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const path = require('path');
const webpackConfig = require('./webpack.config')[0];

const USING_TRAVISCI = Boolean(process.env.TRAVIS);
const USING_SL = Boolean(process.env.SAUCE_USERNAME && process.env.SAUCE_ACCESS_KEY);

const LOCAL_LAUNCHERS = {
  /** See https://github.com/travis-ci/travis-ci/issues/8836#issuecomment-348248951 */
  'ChromeHeadlessNoSandbox': {
    base: 'ChromeHeadless',
    flags: ['--no-sandbox'],
  },
};

const SAUCE_LAUNCHERS = {
  /*
   * Chrome (desktop)
   */

  'sl-chrome-stable': {
    base: 'SauceLabs',
    browserName: 'chrome',
    version: 'latest',
    platform: 'macOS 10.12',
    extendedDebugging: true,
  },
  // 'sl-chrome-beta': {
  //   base: 'SauceLabs',
  //   browserName: 'chrome',
  //   version: 'dev',
  //   platform: 'macOS 10.12',
  //   extendedDebugging: true,
  // },
  // 'sl-chrome-previous': {
  //   base: 'SauceLabs',
  //   browserName: 'chrome',
  //   version: 'latest-1',
  //   platform: 'macOS 10.12',
  //   extendedDebugging: true,
  // },

  /*
   * Firefox
   */

  'sl-firefox-stable': {
    base: 'SauceLabs',
    browserName: 'firefox',
    version: 'latest',
    platform: 'Windows 10',
    extendedDebugging: true,
  },
  // 'sl-firefox-previous': {
  //   base: 'SauceLabs',
  //   browserName: 'firefox',
  //   version: 'latest-1',
  //   platform: 'Windows 10',
  //   extendedDebugging: true,
  // },

  /*
   * IE
   */

  'sl-ie': {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    version: '11',
    platform: 'Windows 8.1',
  },

  /*
   * Edge
   */

  // TODO(sgomes): Re-enable Edge and Safari after Sauce Labs problems are fixed.
  // 'sl-edge': {
  //   base: 'SauceLabs',
  //   browserName: 'microsoftedge',
  //   version: 'latest',
  //   platform: 'Windows 10',
  // },

  /*
   * Safari (desktop)
   */

  // 'sl-safari-stable': {
  //   base: 'SauceLabs',
  //   browserName: 'safari',
  //   version: 'latest',
  //   platform: 'macOS 10.12',
  // },
  // 'sl-safari-previous': {
  //   base: 'SauceLabs',
  //   browserName: 'safari',
  //   version: '9.0',
  //   platform: 'OS X 10.11',
  // },

  /*
   * Safari (mobile)
   */

  'sl-ios-safari-latest': {
    base: 'SauceLabs',
    deviceName: 'iPhone Simulator',
    platformVersion: '10.0',
    platformName: 'iOS',
    browserName: 'Safari',
  },
  // 'sl-ios-safari-previous': {
  //   base: 'SauceLabs',
  //   deviceName: 'iPhone Simulator',
  //   platformVersion: '9.3',
  //   platformName: 'iOS',
  //   browserName: 'Safari',
  // },
};

const getLaunchers = () => {
  if (USING_TRAVISCI) {
    return USING_SL ? SAUCE_LAUNCHERS : LOCAL_LAUNCHERS;
  } else {
    return ['Chrome'];
  }
};

const getBrowsers = () => Object.keys(getLaunchers());

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['mocha'],
    files: [
      'test/unit/index.js',
    ],
    preprocessors: {
      'test/unit/index.js': ['webpack', 'sourcemap'],
    },
    reporters: ['dots', 'coverage'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    browsers: getBrowsers(),
    browserDisconnectTimeout: 40000,
    browserNoActivityTimeout: 120000,
    captureTimeout: 240000,
    concurrency: USING_SL ? 4 : Infinity,
    customLaunchers: getLaunchers(),

    coverageReporter: {
      dir: 'coverage',
      reporters: [
        {type: 'lcovonly', subdir: '.'},
        {type: 'json', subdir: '.', file: 'coverage.json'},
        {type: 'html'},
      ],
    },

    client: {
      mocha: {
        reporter: 'html',
        ui: 'qunit',

        // Number of milliseconds to wait for an individual `test(...)` function to complete.
        // The default is 2000.
        timeout: 10000,
      },
    },

    webpack: Object.assign({}, webpackConfig, {
      devtool: 'inline-source-map',
      module: Object.assign({}, webpackConfig.module, {
        // Cover source files when not debugging tests. Otherwise, omit coverage instrumenting to get
        // uncluttered source maps.
        rules: webpackConfig.module.rules.concat([config.singleRun ? {
          test: /\.js$/,
          include: path.resolve('./packages'),
          exclude: [
            /node_modules/,
            /adapter.js/,
          ],
          loader: 'istanbul-instrumenter-loader',
          query: {esModules: true},
        } : undefined]).filter(Boolean),
      }),
    }),

    webpackMiddleware: {
      noInfo: true,
    },
  });

  if (USING_SL) {
    const sauceLabsConfig = {
      username: process.env.SAUCE_USERNAME,
      accessKey: process.env.SAUCE_ACCESS_KEY,
    };

    if (USING_TRAVISCI) {
      // See https://github.com/karma-runner/karma-sauce-launcher/issues/73
      Object.assign(sauceLabsConfig, {
        testName: 'Material Components Web Unit Tests - CI',
        tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
        startConnect: false,
      });
    }

    config.set({
      sauceLabs: sauceLabsConfig,
      // Attempt to de-flake Sauce Labs tests on TravisCI.
      transports: ['polling'],
      browserDisconnectTolerance: 3,
    });
  }
};
<commit_msg>chore(infrastructure): Fix local tests (#3223)<commit_after>/**
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

const path = require('path');
const webpackConfig = require('./webpack.config')[0];

const USING_TRAVISCI = Boolean(process.env.TRAVIS);
const USING_SL = Boolean(process.env.SAUCE_USERNAME && process.env.SAUCE_ACCESS_KEY);

const LOCAL_LAUNCHERS = {
  /** See https://github.com/travis-ci/travis-ci/issues/8836#issuecomment-348248951 */
  'ChromeHeadlessNoSandbox': {
    base: 'ChromeHeadless',
    flags: ['--no-sandbox'],
  },
};

const SAUCE_LAUNCHERS = {
  /*
   * Chrome (desktop)
   */

  'sl-chrome-stable': {
    base: 'SauceLabs',
    browserName: 'chrome',
    version: 'latest',
    platform: 'macOS 10.12',
    extendedDebugging: true,
  },
  // 'sl-chrome-beta': {
  //   base: 'SauceLabs',
  //   browserName: 'chrome',
  //   version: 'dev',
  //   platform: 'macOS 10.12',
  //   extendedDebugging: true,
  // },
  // 'sl-chrome-previous': {
  //   base: 'SauceLabs',
  //   browserName: 'chrome',
  //   version: 'latest-1',
  //   platform: 'macOS 10.12',
  //   extendedDebugging: true,
  // },

  /*
   * Firefox
   */

  'sl-firefox-stable': {
    base: 'SauceLabs',
    browserName: 'firefox',
    version: 'latest',
    platform: 'Windows 10',
    extendedDebugging: true,
  },
  // 'sl-firefox-previous': {
  //   base: 'SauceLabs',
  //   browserName: 'firefox',
  //   version: 'latest-1',
  //   platform: 'Windows 10',
  //   extendedDebugging: true,
  // },

  /*
   * IE
   */

  'sl-ie': {
    base: 'SauceLabs',
    browserName: 'internet explorer',
    version: '11',
    platform: 'Windows 8.1',
  },

  /*
   * Edge
   */

  // TODO(sgomes): Re-enable Edge and Safari after Sauce Labs problems are fixed.
  // 'sl-edge': {
  //   base: 'SauceLabs',
  //   browserName: 'microsoftedge',
  //   version: 'latest',
  //   platform: 'Windows 10',
  // },

  /*
   * Safari (desktop)
   */

  // 'sl-safari-stable': {
  //   base: 'SauceLabs',
  //   browserName: 'safari',
  //   version: 'latest',
  //   platform: 'macOS 10.12',
  // },
  // 'sl-safari-previous': {
  //   base: 'SauceLabs',
  //   browserName: 'safari',
  //   version: '9.0',
  //   platform: 'OS X 10.11',
  // },

  /*
   * Safari (mobile)
   */

  'sl-ios-safari-latest': {
    base: 'SauceLabs',
    deviceName: 'iPhone Simulator',
    platformVersion: '10.0',
    platformName: 'iOS',
    browserName: 'Safari',
  },
  // 'sl-ios-safari-previous': {
  //   base: 'SauceLabs',
  //   deviceName: 'iPhone Simulator',
  //   platformVersion: '9.3',
  //   platformName: 'iOS',
  //   browserName: 'Safari',
  // },
};

const getLaunchers = () => USING_SL ? SAUCE_LAUNCHERS : LOCAL_LAUNCHERS;
const getBrowsers = () => USING_TRAVISCI ? Object.keys(getLaunchers()) : ['Chrome'];

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['mocha'],
    files: [
      'test/unit/index.js',
    ],
    preprocessors: {
      'test/unit/index.js': ['webpack', 'sourcemap'],
    },
    reporters: ['dots', 'coverage'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    browsers: getBrowsers(),
    browserDisconnectTimeout: 40000,
    browserNoActivityTimeout: 120000,
    captureTimeout: 240000,
    concurrency: USING_SL ? 4 : Infinity,
    customLaunchers: getLaunchers(),

    coverageReporter: {
      dir: 'coverage',
      reporters: [
        {type: 'lcovonly', subdir: '.'},
        {type: 'json', subdir: '.', file: 'coverage.json'},
        {type: 'html'},
      ],
    },

    client: {
      mocha: {
        reporter: 'html',
        ui: 'qunit',

        // Number of milliseconds to wait for an individual `test(...)` function to complete.
        // The default is 2000.
        timeout: 10000,
      },
    },

    webpack: Object.assign({}, webpackConfig, {
      devtool: 'inline-source-map',
      module: Object.assign({}, webpackConfig.module, {
        // Cover source files when not debugging tests. Otherwise, omit coverage instrumenting to get
        // uncluttered source maps.
        rules: webpackConfig.module.rules.concat([config.singleRun ? {
          test: /\.js$/,
          include: path.resolve('./packages'),
          exclude: [
            /node_modules/,
            /adapter.js/,
          ],
          loader: 'istanbul-instrumenter-loader',
          query: {esModules: true},
        } : undefined]).filter(Boolean),
      }),
    }),

    webpackMiddleware: {
      noInfo: true,
    },
  });

  if (USING_SL) {
    const sauceLabsConfig = {
      username: process.env.SAUCE_USERNAME,
      accessKey: process.env.SAUCE_ACCESS_KEY,
    };

    if (USING_TRAVISCI) {
      // See https://github.com/karma-runner/karma-sauce-launcher/issues/73
      Object.assign(sauceLabsConfig, {
        testName: 'Material Components Web Unit Tests - CI',
        tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
        startConnect: false,
      });
    }

    config.set({
      sauceLabs: sauceLabsConfig,
      // Attempt to de-flake Sauce Labs tests on TravisCI.
      transports: ['polling'],
      browserDisconnectTolerance: 3,
    });
  }
};
<|endoftext|>


<commit_before>var _ = require('underscore'),
    query = require('assetgraph').query,
    i18nTools = require('../util/i18nTools');

module.exports = function (queryObj, localeIds) {
    return function cloneForEachLocale(assetGraph) {
        assetGraph.findAssets(_.extend({type: 'Html'}, queryObj)).forEach(function (originalHtmlAsset) {
            var nonInlineJavaScriptsToCloneById = {};

            // First note which JavaScript assets need to be cloned for each locale:
            assetGraph.findRelations({type: 'HtmlScript', from: originalHtmlAsset, node: {id: query.not('oneBootstrapper')}, to: {isInline: false}}).forEach(function (htmlScript) {
                // Only clone the JavaScript if it contains at least one one.tr/one.trPattern expression
                i18nTools.eachOneTrInAst(htmlScript.to.parseTree, function () {
                    nonInlineJavaScriptsToCloneById[htmlScript.to.id] = htmlScript.to;
                    return false;
                });
            });
            localeIds.forEach(function (localeId) {
                var localizedHtml = originalHtmlAsset.clone();
                localizedHtml.url = originalHtmlAsset.url.replace(/(?:\.html)?$/, '.' + localeId + '.html');

                localizedHtml.parseTree.documentElement.setAttribute('lang', localeId);
                localizedHtml.markDirty();

                assetGraph.findRelations({type: 'HtmlScript', from: localizedHtml, node: {id: query.not('oneBootstrapper')}}).forEach(function (htmlScript) {
                    if (htmlScript.to.id in nonInlineJavaScriptsToCloneById) {
                        htmlScript.to.clone(htmlScript);
                    }
                    i18nTools.eachOneTrInAst(htmlScript.to.parseTree,
                                             i18nTools.createOneTrReplacer(i18nTools.extractAllReachableKeysForLocale(assetGraph, localeId, localizedHtml), localeId));
                    htmlScript.to.markDirty();
                });
                assetGraph.findRelations({type: 'HtmlCacheManifest', from: localizedHtml}).forEach(function (htmlCacheManifest) {
                    htmlCacheManifest.to.clone(htmlCacheManifest);
                    htmlCacheManifest.to.url = originalHtmlAsset.url.replace(/(?:\.html)?$/, '.' + localeId + '.html');
                });
            });
            assetGraph.findRelations({type: 'HtmlCacheManifest', from: originalHtmlAsset}).forEach(function (htmlCacheManifest) {
                assetGraph.removeAsset(htmlCacheManifest.to);
            });
            assetGraph.removeAsset(originalHtmlAsset);
            _.values(nonInlineJavaScriptsToCloneById).forEach(function (javaScript) {
                if (assetGraph.findRelations({to: javaScript}).length === 0) {
                    assetGraph.removeAsset(javaScript);
                }
            });
        });
    };
};
<commit_msg>transforms.cloneForEachLocale: Preserve the extension of the original Html asset when cloning.<commit_after>var _ = require('underscore'),
    query = require('assetgraph').query,
    i18nTools = require('../util/i18nTools');

module.exports = function (queryObj, localeIds) {
    return function cloneForEachLocale(assetGraph) {
        assetGraph.findAssets(_.extend({type: 'Html'}, queryObj)).forEach(function (originalHtmlAsset) {
            var nonInlineJavaScriptsToCloneById = {};

            // First note which JavaScript assets need to be cloned for each locale:
            assetGraph.findRelations({type: 'HtmlScript', from: originalHtmlAsset, node: {id: query.not('oneBootstrapper')}, to: {isInline: false}}).forEach(function (htmlScript) {
                // Only clone the JavaScript if it contains at least one one.tr/one.trPattern expression
                i18nTools.eachOneTrInAst(htmlScript.to.parseTree, function () {
                    nonInlineJavaScriptsToCloneById[htmlScript.to.id] = htmlScript.to;
                    return false;
                });
            });
            localeIds.forEach(function (localeId) {
                var localizedHtml = originalHtmlAsset.clone();
                localizedHtml.url = originalHtmlAsset.url; // Avoidable if asset.clone() is changed to duplicate the original url.
                localizedHtml.extension = '.' + localeId + localizedHtml.extension;

                localizedHtml.parseTree.documentElement.setAttribute('lang', localeId);
                localizedHtml.markDirty();

                assetGraph.findRelations({type: 'HtmlScript', from: localizedHtml, node: {id: query.not('oneBootstrapper')}}).forEach(function (htmlScript) {
                    if (htmlScript.to.id in nonInlineJavaScriptsToCloneById) {
                        htmlScript.to.clone(htmlScript);
                    }
                    i18nTools.eachOneTrInAst(htmlScript.to.parseTree,
                                             i18nTools.createOneTrReplacer(i18nTools.extractAllReachableKeysForLocale(assetGraph, localeId, localizedHtml), localeId));
                    htmlScript.to.markDirty();
                });
                assetGraph.findRelations({type: 'HtmlCacheManifest', from: localizedHtml}).forEach(function (htmlCacheManifest) {
                    htmlCacheManifest.to.clone(htmlCacheManifest);
                    htmlCacheManifest.to.url = originalHtmlAsset.url.replace(/(?:\.html)?$/, '.' + localeId + '.html');
                });
            });
            assetGraph.findRelations({type: 'HtmlCacheManifest', from: originalHtmlAsset}).forEach(function (htmlCacheManifest) {
                assetGraph.removeAsset(htmlCacheManifest.to);
            });
            assetGraph.removeAsset(originalHtmlAsset);
            _.values(nonInlineJavaScriptsToCloneById).forEach(function (javaScript) {
                if (assetGraph.findRelations({to: javaScript}).length === 0) {
                    assetGraph.removeAsset(javaScript);
                }
            });
        });
    };
};
<|endoftext|>


<commit_before>var frameModule = require("ui/frame");
var utilsModule = require("utils/utils");

function share(thingsToShare, index) {
	var activityController = UIActivityViewController.alloc()
		.initWithActivityItemsApplicationActivities(thingsToShare, null);
	var presentViewController = activityController.popoverPresentationController;
	if (presentViewController) {
		var page = frameModule.topmost().currentPage;
		if (page && page.ios.navigationItem.rightBarButtonItems &&
			page.ios.navigationItem.rightBarButtonItems.count > 0) {
			presentViewController.barButtonItem = page.ios.navigationItem.rightBarButtonItems[0];
		} else {
			presentViewController.sourceView = page.ios.view;
		}
	}

	utilsModule.ios.getter(UIApplication, UIApplication.sharedApplication)
		.keyWindow
		.rootViewController
		.presentViewControllerAnimatedCompletion(activityController, true, null);
}

module.exports = {
	shareImage: function(image) {
		share([image]);
	},
	shareText: function(text) {
		share([text]);
	},
	shareUrl: function(url, text) {
		share([NSURL.URLWithString(url), text]);
	}
};
<commit_msg>fix: iOS hard crash <commit_after>var frameModule = require("ui/frame");
var utilsModule = require("utils/utils");

function share(thingsToShare, index) {
	var activityController = UIActivityViewController.alloc()
		.initWithActivityItemsApplicationActivities(thingsToShare, null);
	var presentViewController = activityController.popoverPresentationController;
	if (presentViewController) {
		var page = frameModule.topmost().currentPage;
		if (page && page.ios.navigationItem.rightBarButtonItems &&
			page.ios.navigationItem.rightBarButtonItems.count > 0) {
			presentViewController.barButtonItem = page.ios.navigationItem.rightBarButtonItems[0];
		} else {
			presentViewController.sourceView = page.ios.view;
		}
	}

	utilsModule.ios.getter(UIApplication, UIApplication.sharedApplication)
		.keyWindow
		.rootViewController
		.presentViewControllerAnimatedCompletion(activityController, true, null);
}

module.exports = {
	shareImage: function(image) {
		share(NSArray.arrayWithObject(image));
	},
	shareText: function(text) {
		share(NSArray.arrayWithObject(text));
	},
	shareUrl: function(url, text) {
		share(NSArray.arrayWithObject(NSURL.URLWithString(url)));
	}
};
<|endoftext|>


<commit_before>var _ = require('underscore');
var Room = require('../../models').room;
var UserModel = require('../../models').user;

module.exports = function(server){
  server.sock.when('CREATE /api/rooms', createRoom);
  server.sock.when('READ /api/rooms', readRooms);
  server.sock.when('READ /api/room/:id', readRoom);
  server.sock.when('UPDATE /api/room/:id', server.sock.can('updateRoom'), updateRoom);
  server.sock.when('DELETE /api/room/:id', server.sock.can('deleteRoom'), deleteRoom);
  server.sock.when('JOIN /api/room/:id', joinRoom);
  server.sock.when('LEAVE /api/room/:id', leaveRoom);
}

function joinRoom(socket, data, next){
  var user = UserModel.user(socket.user);
  user.joinRoom(socket.params['id'], function(err, result){
    if(err){
      return next(err);
    }
    socket.join(socket.params['id']);
    socket.json({result: result});
  });
}

function leaveRoom(socket, data, next){
  //TODO: implement
  // remove from DB
  //remove from socket
}

function createRoom(socket, data){
  var newRoom = _(data).pick("description", "name");
  newRoom.owner = socket.user._id;

  Room.create(newRoom, function(err, room, next){
    if(err){
      return next(err);
    }
    socket.json(room);
  });
}

function readRooms(socket, data, next){
  Room.getAll(socket.user._id, function(err, rooms, next) {
    if(err){
      return next(err);
    }
    socket.json({statusCode: 200, rooms: rooms});
  });
}

function readRoom(socket){
  Room.getById(socket.params['id'], function(err, room, next){
    if(err){
      return next(err);
    }
    room ? socket.json(room) : socket.json({err: 'Room not found', statusCode: 404});
  });
}

function updateRoom(socket, data, next){
  var updatedRoom = _(data).pick("description", "name");
  updatedRoom.owner = socket.user._id;

  Room.updateById(socket.params['id'], updatedRoom, function(err, room){
    if(err){
      return next(err);
    }
    socket.json(room);
  });
}

function deleteRoom(socket, data, next){
  Room.deleteById(socket.params['id'], function(err){
    if(err){
      return next(err);
    }
    socket.json({statusCode: 200});
  });
}
<commit_msg>Fixed missed error handling in rooms socket flow processor<commit_after>var _ = require('underscore');
var Room = require('../../models').room;
var UserModel = require('../../models').user;

module.exports = function(server){
  server.sock.when('CREATE /api/rooms', createRoom);
  server.sock.when('READ /api/rooms', readRooms);
  server.sock.when('READ /api/room/:id', readRoom);
  server.sock.when('UPDATE /api/room/:id', server.sock.can('updateRoom'), updateRoom);
  server.sock.when('DELETE /api/room/:id', server.sock.can('deleteRoom'), deleteRoom);
  server.sock.when('JOIN /api/room/:id', joinRoom);
  server.sock.when('LEAVE /api/room/:id', leaveRoom);
}

function joinRoom(socket, data, next){
  var user = UserModel.user(socket.user);
  user.joinRoom(socket.params['id'], function(err, result){
    if(err){
      return next(err);
    }
    socket.join(socket.params['id']);
    socket.json({result: result});
  });
}

function leaveRoom(socket, data, next){
  //TODO: implement
  // remove from DB
  //remove from socket
}

function createRoom(socket, data, next){
  var newRoom = _(data).pick("description", "name");
  newRoom.owner = socket.user._id;

  Room.create(newRoom, function(err, room, next){
    if(err){
      return next(err);
    }
    socket.json(room);
  });
}

function readRooms(socket, data, next){
  Room.getAll(socket.user._id, function(err, rooms, next) {
    if(err){
      return next(err);
    }
    socket.json({statusCode: 200, rooms: rooms});
  });
}

function readRoom(socket, data, next){
  Room.getById(socket.params['id'], function(err, room, next){
    if(err){
      return next(err);
    }
    room ? socket.json(room) : socket.json({err: 'Room not found', statusCode: 404});
  });
}

function updateRoom(socket, data, next){
  var updatedRoom = _(data).pick("description", "name");
  updatedRoom.owner = socket.user._id;

  Room.updateById(socket.params['id'], updatedRoom, function(err, room){
    if(err){
      return next(err);
    }
    socket.json(room);
  });
}

function deleteRoom(socket, data, next){
  Room.deleteById(socket.params['id'], function(err){
    if(err){
      return next(err);
    }
    socket.json({statusCode: 200});
  });
}
<|endoftext|>


<commit_before>import React, { useEffect, useState } from 'react'
import { injectIntl, FormattedMessage } from 'react-intl'
import ReactPlaceholder from 'react-placeholder'
import {
  withStyles,
  Grid,
  Button,
  Typography,
  InputLabel,
  FormControl,
  Input,
  Select,
  FormHelperText,
} from '@material-ui/core'

import MuiAlert from '@material-ui/lab/Alert'
import 'react-phone-number-input/style.css'
import MaskedInput from 'react-text-mask'

import CountryPicker, { countryCodes } from './country-picker'
import DeleteUser from './settings/deleteUser'

import messages from './messages'

const styles = (theme) => ({
  legend: {
    fontSize: 18,
    fontWeight: 500,
    color: theme.palette.primary.dark,
  },
  fieldset: {
    border: `1px solid ${theme.palette.primary.light}`,
    marginBottom: 20
  }
})

const AccountDetails = ({
  intl,
  account,
  history,
  updateAccount,
  user,
  updateUser,
  deleteUser,
  createAccount,
  createBankAccount,
  getBankAccount,
  bankAccount,
  fetchAccount,
  classes
}) => {
  const [ accountData, setAccountData ] = useState({})
  const [ displayCurrentCountry, setDisplayCurrentCountry ] = useState({})
  const [ userId ] = useState('')
  const [ openCountryPicker, setOpenCountryPicker ] = useState(false)
  const [ deleteUserDialog, setDeleteUserDialog ] = useState(false)

  const handleSubmit = (e) => {
    e.preventDefault()
    if (!e.target) return false
    let formData = {
      'business_profile[url]': e.target['business_profile[url]'].value,
      'individual[phone]': e.target['individual[phone]'].value,
      'individual[first_name]': e.target['individual[first_name]'].value,
      'individual[last_name]': e.target['individual[last_name]'].value,
      'individual[address][city]':
        e.target['individual[address][city]'].value,
      'individual[address][line1]':
        e.target['individual[address][line1]'].value,
      'individual[address][line2]':
        e.target['individual[address][line2]'].value,
      'individual[address][postal_code]':
        e.target['individual[address][postal_code]'].value,
      'individual[address][state]':
        e.target['individual[address][state]'].value,
      'individual[dob][day]': e.target['individual[dob][day]'].value,
      'individual[dob][month]': e.target['individual[dob][month]'].value,
      'individual[dob][year]': e.target['individual[dob][year]'].value
    }

    if (e.target['individual[id_number]'].value) {
      formData['individual[id_number]'] =
        e.target['individual[id_number]'].value
    }
    setAccountData(formData)
    updateAccount(userId, formData)
  }
  const onChange = (e) => {

  }

  const Alert = (props) => {
    return <MuiAlert elevation={ 2 } variant='outlined' { ...props } />
  }

  function TextMaskCustom (props) {
    const { inputRef, ...other } = props

    return (
      <MaskedInput
        { ...other }
        ref={ (ref) => {
          inputRef(ref ? ref.inputElement : null)
        } }
        mask={ ['(', '+', /[1-9]/, /\d/, ')', ' ', /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/] }
        placeholderChar={ '\u2000' }
        showMask
      />
    )
  }

  const Field = ({ name, label, type = 'text', required = false, defaultValue, placeholder, disabled, help, inputComponent }) => {
    return (
      <FormControl style={ { width: '100%' } }>
        <InputLabel htmlFor={ name }>{ label }</InputLabel>
        <Input
          id={ name }
          name={ name }
          type={ type }
          required={ required }
          defaultValue={ defaultValue }
          fullWidth
          style={ { width: '100%' } }
          placeholder={ placeholder }
          disabled={ disabled }
          inputComponent={ inputComponent }
        />
        { help &&
          <FormHelperText id='component-helper-text'>
            <FormattedMessage id='validation-message' defaultMessage='+Country code and Number' />
          </FormHelperText>
        }
      </FormControl>
    )
  }

  const onDeleteUser = (user) => {
    deleteUser(user).then(response => {
      history.push('/')
    }).catch(e => {
      // eslint-disable-next-line no-console
      console.log(e)
    })
  }

  useEffect(() => {
    if (user.user.id) {
      const userId = user.user.id
      fetchAccount(userId)
    }
  }, [user])

  const closeCountryPicker = (e, country) => {
    setDisplayCurrentCountry(country)
    setOpenCountryPicker(false)
  }

  return (
    <form
      onSubmit={ handleSubmit }
      onChange={ onChange }
      style={ { marginTop: 20, marginBottom: 20, width: '100%' } }
    >
      <Grid container spacing={ 2 }>
        <Grid item xs={ 12 } md={ 12 }>
          <Typography variant='h6' gutterBottom>
            <FormattedMessage id='account-details-personal-information-title' defaultMessage='Account details' />
          </Typography>
        </Grid>
        <Grid item xs={ 12 } md={ 12 }>
          <ReactPlaceholder
            showLoadingAnimation
            type='media'
            rows={ 1 }
            ready={ account.completed }
          >
            <fieldset className={ classes.fieldset }>
              <legend className={ classes.legend }>
                <Typography>
                  <FormattedMessage id='account-details-country-information-title' defaultMessage='Country' />
                </Typography>
              </legend>
              <Grid container spacing={ 2 }>
                { displayCurrentCountry.country &&
                <Grid item xs={ 12 } md={ 12 }>
                  <Alert severity='info'>
                    <FormattedMessage id='account-details-country-information-desc' defaultMessage='Please make sure you have bank account on the country selected before continue.' />
                  </Alert>
                </Grid>
                }
                { account && account.data.country
                  ? <Grid item xs={ 12 } md={ 12 }>

                      <img width='48' src={ require(`../../images/countries/${countryCodes.find(c => c.code === account.data.country).image}.png`) } />
                      <Typography component='span' style={ { marginLeft: 10 } }>
                        { countryCodes.find(c => c.code === account.data.country).country }
                      </Typography>

                  </Grid>
                  :

                    <Button variant='outlined' onClick={ () => setOpenCountryPicker(true) } style={ { margin: 20 } }>
                      <FormattedMessage id='account-details-country-information-action' defaultMessage='Select Country' />
                    </Button>
                    <CountryPicker open={ openCountryPicker } onClose={ closeCountryPicker } classes={ classes } />

                }
                { account && JSON.stringify(account.data) }
              </Grid>
              { displayCurrentCountry.country ? (
                <Grid container spacing={ 2 }>
                  <Grid item xs={ 12 } md={ 12 }>

                      <img width='48' src={ require(`../../images/countries/${countryCodes.find(c => c.code === displayCurrentCountry.code).image}.png`) } />
                      <Typography component='span' style={ { marginLeft: 10 } }>
                        { countryCodes.find(c => c.code === displayCurrentCountry.code).country }
                      </Typography>

                  </Grid>
                  <Grid item xs={ 12 } md={ 12 }>
                    <Button variant='text' onClick={ () => {
                      displayCurrentCountry.code && createAccount(displayCurrentCountry.code)
                      setDisplayCurrentCountry({})
                    } } style={ { margin: 20 } }>
                      <FormattedMessage id='account-details-country-information-save' defaultMessage='Save Country and continue' />
                    </Button>
                  </Grid>
                </Grid>
              ) : ('') }
            </fieldset>
          </ReactPlaceholder>
        </Grid>
        { account.completed && account.data.country && (
          <Grid item xs={ 12 } md={ 12 }>
            <fieldset className={ classes.fieldset }>
              <legend className={ classes.legend }>
                <Typography>
                  <FormattedMessage id='account-details-personal-information' defaultMessage='Personal details' />
                </Typography>
              </legend>
              <Grid container spacing={ 2 }>
                <Grid item xs={ 12 } sm={ 6 } md={ 6 }>
                  <FormattedMessage id='account.verify.firstName' defaultMessage='First name'>
                    { (msg) => (
                      <Field
                        name='individual[first_name]'
                        label={ msg }
                        defaultValue={ accountData['individual[first_name]'] || account.data.individual && account.data.individual.first_name }
                      />
                    ) }
                  </FormattedMessage>
                </Grid>
                <Grid item xs={ 12 } sm={ 6 } md={ 6 }>
                  <FormattedMessage id='account.verify.lastName' defaultMessage='Last name'>
                    { (msg) => (
                      <Field
                        name='individual[last_name]'
                        label={ msg }
                        defaultValue={ accountData['individual[last_name]'] || account.data.individual && account.data.individual.last_name }
                      />
                    ) }
                  </FormattedMessage>
                </Grid>
                <Grid item xs={ 12 } sm={ 6 } md={ 4 }>
                  <Field
                    name='individual[id_number]'
                    label='ID number'
                    placeholder={
                      account.data.individual && account.data.individual
                        .id_number_provided
                        ? intl.formatMessage(messages.documentProvided)
                        : intl.formatMessage(messages.documentProvide)
                    }
                    disabled={
                      accountData['individual[id_number]'] || account.data.individual && account.data.individual.id_number_provided
                    }
                    defaultValue={
                      accountData['individual[id_number]'] || account.data.individual && account.data.individual.id_number
                    }
                  />
                </Grid>
                <Grid item xs={ 12 } sm={ 12 } md={ 4 }>
                  <FormattedMessage id='account.verify.phone_number' defaultMessage='Phone number'>
                    { (msg) => (
                      <Field
                        name='individual[phone]'
                        label={ msg }
                        defaultValue={ accountData['individual[phone]'] || account.data.individual && account.data.individual.phone }
                        help
                        inputComponent={ TextMaskCustom }
                      />
                    ) }
                  </FormattedMessage>
                </Grid>
                <Grid item xs={ 12 } sm={ 12 } md={ 4 }>
                  <FormattedMessage id='account.verify.business_profile_url' defaultMessage='Website'>
                    { (msg) => (
                      <Field
                        name='business_profile[url]'
                        label={ msg }
                        defaultValue={ accountData['business_profile[url]'] || account.data.business_profile && account.data.business_profile.url }
                      />
                    ) }
                  </FormattedMessage>
                </Grid>
              </Grid>
              <Grid container spacing={ 2 }>
                <Grid item xs={ 12 } md={ 12 }>
                  <Typography color='textPrimary' style={ { marginBottom: -20, marginTop: 10 } }>
                    <FormattedMessage id='account-details-personal-information-birth-date' defaultMessage='Birth date' />
                  </Typography>
                </Grid>
                <Grid item xs={ 12 } md={ 4 }>
                  <Field name='individual[dob][day]' label='Day' type='number' defaultValue={ accountData['individual[dob][day]'] || account.data.individual && account.data.individual.dob && account.data.individual.dob.day } />
                </Grid>
                <Grid item xs={ 12 } md={ 4 }>
                  <FormControl style={ { width: '100%' } }>
                    <Select
                      autoWidth
                      native
                      name='individual[dob][month]'
                      style={ { marginRight: 8, marginTop: 16, width: '100%' } }
                    >
                      <FormattedMessage id='account.details.month' defaultMessage='Month of birth'>{ (msg) => <option value='' key={ 'default' }>{ msg }</option> }</FormattedMessage>
                      { [[1, 'Jan'], [2, 'Fev'], [3, 'Mar'], [4, 'Apr'], [5, 'May'], [6, 'June'], [7, 'Jul'], [8, 'Aug'], [9, 'Set'], [10, 'Oct'], [11, 'Nov'], [12, 'Dec']].map(
                        (item, i) => {
                          return (
                            <option selected={ account.data.individual && !!(item[0] === account.data.individual.dob.month || item[1] === accountData['individual[dob][month]']) } key={ i } value={ item[0] }>
                              { `${item[1]}` }
                            </option>
                          )
                        }
                      ) }
                    </Select>
                  </FormControl>
                </Grid>
                <Grid item xs={ 12 } md={ 4 }>
                  <Field name='individual[dob][year]' label='Year' type='number' defaultValue={ accountData['individual[dob][year]'] || account.data.individual && account.data.individual.dob && account.data.individual.dob.year } />
                </Grid>
              </Grid>
            </fieldset>
            <fieldset className={ classes.fieldset }>
              <legend className={ classes.legend }>
                <Typography>
                  <FormattedMessage id='account-details-address' defaultMessage='Address information' />
                </Typography>
              </legend>
              <Grid container spacing={ 2 }>
                <Grid item xs={ 12 } md={ 6 }>
                  <Field name='individual[address][line1]' label='Address line 1' defaultValue={ accountData['individual[address][line1]'] || account.data.individual && account.data.individual.address.line1 } />
                </Grid>
                <Grid item xs={ 12 } md={ 6 }>
                  <Field name='individual[address][line2]' label='Address line 2' defaultValue={ accountData['individual[address][line2]'] || account.data.individual && account.data.individual.address.line2 } />
                </Grid>
                <Grid item xs={ 12 } md={ 6 }>
                  <Field name='individual[address][city]' label='City' defaultValue={ accountData['individual[address][city]'] || account.data.individual && account.data.individual.address.city } />
                </Grid>
                <Grid item xs={ 12 } md={ 2 }>
                  <Field name='individual[address][state]' label='State' defaultValue={ accountData['individual[address][state]'] || account.data.individual && account.data.individual.address.state } />
                </Grid>
                <Grid item xs={ 12 } md={ 4 }>
                  <Field name='individual[address][postal_code]' label='Postal code' defaultValue={ accountData['individual[address][postal_code]'] || account.data.individual && account.data.individual.address.postal_code } />
                </Grid>
              </Grid>
            </fieldset>
            <Grid item xs={ 12 }>

                <Button onClick={ () => setDeleteUserDialog(true) }
                  variant='link'
                  style={ { color: '#353A42' } }
                >
                  <FormattedMessage id='account.profile.settings.delete.user.button' defaultMessage='Delete my account' />
                </Button>

                <DeleteUser
                  deleteUser={ () => user && onDeleteUser(user.user) }
                  user={ user }
                  visible={ deleteUserDialog }
                  onClose={ () => setDeleteUserDialog(false) }
                  onOpen={ () => setDeleteUserDialog(true) }
                />
                <Button
                  color='primary'
                  // onClick={closeUpdateModal}
                >
                  <FormattedMessage id='account.actions.cancel' defaultMessage='Cancel' />
                </Button>
                <Button
                  type='submit'
                  variant='contained'
                  color='secondary'
                >
                  <FormattedMessage id='account.actions.update' defaultMessage='Update Account' />
                </Button>

            </Grid>
          </Grid>) }
      </Grid>
    </form>
  )
}

export default injectIntl(withStyles(styles)(AccountDetails))
<commit_msg>updating account details<commit_after>import React, { useEffect, useState } from 'react'
import { injectIntl, FormattedMessage } from 'react-intl'
import ReactPlaceholder from 'react-placeholder'
import {
  withStyles,
  Grid,
  Button,
  Typography,
  InputLabel,
  FormControl,
  Input,
  Select,
  FormHelperText,
} from '@material-ui/core'

import MuiAlert from '@material-ui/lab/Alert'
import 'react-phone-number-input/style.css'
import MaskedInput from 'react-text-mask'

import CountryPicker, { countryCodes } from './country-picker'
import DeleteUser from './settings/deleteUser'

import messages from './messages'

const styles = (theme) => ({
  legend: {
    fontSize: 18,
    fontWeight: 500,
    color: theme.palette.primary.dark,
  },
  fieldset: {
    border: `1px solid ${theme.palette.primary.light}`,
    marginBottom: 20
  }
})

const AccountDetails = ({
  intl,
  account,
  history,
  updateAccount,
  user,
  updateUser,
  deleteUser,
  createAccount,
  createBankAccount,
  getBankAccount,
  bankAccount,
  fetchAccount,
  classes
}) => {
  const [ accountData, setAccountData ] = useState({})
  const [ displayCurrentCountry, setDisplayCurrentCountry ] = useState({})
  const [ userId ] = useState('')
  const [ openCountryPicker, setOpenCountryPicker ] = useState(false)
  const [ deleteUserDialog, setDeleteUserDialog ] = useState(false)

  const handleSubmit = (e) => {
    e.preventDefault()
    if (!e.target) return false
    let formData = {
      'business_profile[url]': e.target['business_profile[url]'].value,
      'individual[phone]': e.target['individual[phone]'].value,
      'individual[email]': user.user.data.email,
      'individual[first_name]': e.target['individual[first_name]'].value,
      'individual[last_name]': e.target['individual[last_name]'].value,
      'individual[address][city]':
        e.target['individual[address][city]'].value,
      'individual[address][line1]':
        e.target['individual[address][line1]'].value,
      'individual[address][line2]':
        e.target['individual[address][line2]'].value,
      'individual[address][postal_code]':
        e.target['individual[address][postal_code]'].value,
      'individual[address][state]':
        e.target['individual[address][state]'].value,
      'individual[dob][day]': e.target['individual[dob][day]'].value,
      'individual[dob][month]': e.target['individual[dob][month]'].value,
      'individual[dob][year]': e.target['individual[dob][year]'].value
    }

    if (e.target['individual[id_number]'].value) {
      formData['individual[id_number]'] =
        e.target['individual[id_number]'].value
    }
    setAccountData(formData)
    updateAccount(userId, formData)
  }
  const onChange = (e) => {

  }

  const Alert = (props) => {
    return <MuiAlert elevation={ 2 } variant='outlined' { ...props } />
  }

  function TextMaskCustom (props) {
    const { inputRef, ...other } = props

    return (
      <MaskedInput
        { ...other }
        ref={ (ref) => {
          inputRef(ref ? ref.inputElement : null)
        } }
        mask={ ['(', '+', /[1-9]/, /\d/, ')', ' ', /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/, /\d/] }
        placeholderChar={ '\u2000' }
        showMask
      />
    )
  }

  const Field = ({ name, label, type = 'text', required = false, defaultValue, placeholder, disabled, help, inputComponent }) => {
    return (
      <FormControl style={ { width: '100%' } }>
        <InputLabel htmlFor={ name }>{ label }</InputLabel>
        <Input
          id={ name }
          name={ name }
          type={ type }
          required={ required }
          defaultValue={ defaultValue }
          fullWidth
          style={ { width: '100%' } }
          placeholder={ placeholder }
          disabled={ disabled }
          inputComponent={ inputComponent }
        />
        { help &&
          <FormHelperText id='component-helper-text'>
            <FormattedMessage id='validation-message' defaultMessage='+Country code and Number' />
          </FormHelperText>
        }
      </FormControl>
    )
  }

  const onDeleteUser = (user) => {
    deleteUser(user).then(response => {
      history.push('/')
    }).catch(e => {
      // eslint-disable-next-line no-console
      console.log(e)
    })
  }

  useEffect(() => {
    if (user.user.id) {
      const userId = user.user.id
      fetchAccount(userId)
    }
  }, [user])

  const closeCountryPicker = (e, country) => {
    setDisplayCurrentCountry(country)
    setOpenCountryPicker(false)
  }

  return (
    <form
      onSubmit={ handleSubmit }
      onChange={ onChange }
      style={ { marginTop: 20, marginBottom: 20, width: '100%' } }
    >
      <Grid container spacing={ 2 }>
        <Grid item xs={ 12 } md={ 12 }>
          <Typography variant='h6' gutterBottom>
            <FormattedMessage id='account-details-personal-information-title' defaultMessage='Account details' />
          </Typography>
        </Grid>
        <Grid item xs={ 12 } md={ 12 }>
          <ReactPlaceholder
            showLoadingAnimation
            type='media'
            rows={ 1 }
            ready={ account.completed }
          >
            <fieldset className={ classes.fieldset }>
              <legend className={ classes.legend }>
                <Typography>
                  <FormattedMessage id='account-details-country-information-title' defaultMessage='Country' />
                </Typography>
              </legend>
              <Grid container spacing={ 2 }>
                { displayCurrentCountry.country &&
                <Grid item xs={ 12 } md={ 12 }>
                  <Alert severity='info'>
                    <FormattedMessage id='account-details-country-information-desc' defaultMessage='Please make sure you have bank account on the country selected before continue.' />
                  </Alert>
                </Grid>
                }
                { account && account.data.country
                  ? <Grid item xs={ 12 } md={ 12 }>

                      <img width='48' src={ require(`../../images/countries/${countryCodes.find(c => c.code === account.data.country).image}.png`) } />
                      <Typography component='span' style={ { marginLeft: 10 } }>
                        { countryCodes.find(c => c.code === account.data.country).country }
                      </Typography>

                  </Grid>
                  :

                    <Button variant='outlined' onClick={ () => setOpenCountryPicker(true) } style={ { margin: 20 } }>
                      <FormattedMessage id='account-details-country-information-action' defaultMessage='Select Country' />
                    </Button>
                    <CountryPicker open={ openCountryPicker } onClose={ closeCountryPicker } classes={ classes } />

                }
                { account && JSON.stringify(account.data) }
              </Grid>
              { displayCurrentCountry.country ? (
                <Grid container spacing={ 2 }>
                  <Grid item xs={ 12 } md={ 12 }>

                      <img width='48' src={ require(`../../images/countries/${countryCodes.find(c => c.code === displayCurrentCountry.code).image}.png`) } />
                      <Typography component='span' style={ { marginLeft: 10 } }>
                        { countryCodes.find(c => c.code === displayCurrentCountry.code).country }
                      </Typography>

                  </Grid>
                  <Grid item xs={ 12 } md={ 12 }>
                    <Button variant='text' onClick={ () => {
                      displayCurrentCountry.code && createAccount(displayCurrentCountry.code)
                      setDisplayCurrentCountry({})
                    } } style={ { margin: 20 } }>
                      <FormattedMessage id='account-details-country-information-save' defaultMessage='Save Country and continue' />
                    </Button>
                  </Grid>
                </Grid>
              ) : ('') }
            </fieldset>
          </ReactPlaceholder>
        </Grid>
        { account.completed && account.data.country && (
          <Grid item xs={ 12 } md={ 12 }>
            <fieldset className={ classes.fieldset }>
              <legend className={ classes.legend }>
                <Typography>
                  <FormattedMessage id='account-details-personal-information' defaultMessage='Personal details' />
                </Typography>
              </legend>
              <Grid container spacing={ 2 }>
                <Grid item xs={ 12 } sm={ 6 } md={ 6 }>
                  <FormattedMessage id='account.verify.firstName' defaultMessage='First name'>
                    { (msg) => (
                      <Field
                        name='individual[first_name]'
                        label={ msg }
                        defaultValue={ accountData['individual[first_name]'] || account.data.individual && account.data.individual.first_name }
                      />
                    ) }
                  </FormattedMessage>
                </Grid>
                <Grid item xs={ 12 } sm={ 6 } md={ 6 }>
                  <FormattedMessage id='account.verify.lastName' defaultMessage='Last name'>
                    { (msg) => (
                      <Field
                        name='individual[last_name]'
                        label={ msg }
                        defaultValue={ accountData['individual[last_name]'] || account.data.individual && account.data.individual.last_name }
                      />
                    ) }
                  </FormattedMessage>
                </Grid>
                <Grid item xs={ 12 } sm={ 6 } md={ 4 }>
                  <Field
                    name='individual[id_number]'
                    label='ID number'
                    placeholder={
                      account.data.individual && account.data.individual
                        .id_number_provided
                        ? intl.formatMessage(messages.documentProvided)
                        : intl.formatMessage(messages.documentProvide)
                    }
                    disabled={
                      accountData['individual[id_number]'] || account.data.individual && account.data.individual.id_number_provided
                    }
                    defaultValue={
                      accountData['individual[id_number]'] || account.data.individual && account.data.individual.id_number
                    }
                  />
                </Grid>
                <Grid item xs={ 12 } sm={ 12 } md={ 4 }>
                  <FormattedMessage id='account.verify.phone_number' defaultMessage='Phone number'>
                    { (msg) => (
                      <Field
                        name='individual[phone]'
                        label={ msg }
                        defaultValue={ accountData['individual[phone]'] || account.data.individual && account.data.individual.phone }
                        help
                        inputComponent={ TextMaskCustom }
                      />
                    ) }
                  </FormattedMessage>
                </Grid>
                <Grid item xs={ 12 } sm={ 12 } md={ 4 }>
                  <FormattedMessage id='account.verify.business_profile_url' defaultMessage='Website'>
                    { (msg) => (
                      <Field
                        name='business_profile[url]'
                        label={ msg }
                        defaultValue={ accountData['business_profile[url]'] || account.data.business_profile && account.data.business_profile.url }
                      />
                    ) }
                  </FormattedMessage>
                </Grid>
              </Grid>
              <Grid container spacing={ 2 }>
                <Grid item xs={ 12 } md={ 12 }>
                  <Typography color='textPrimary' style={ { marginBottom: -20, marginTop: 10 } }>
                    <FormattedMessage id='account-details-personal-information-birth-date' defaultMessage='Birth date' />
                  </Typography>
                </Grid>
                <Grid item xs={ 12 } md={ 4 }>
                  <Field name='individual[dob][day]' label='Day' type='number' defaultValue={ accountData['individual[dob][day]'] || account.data.individual && account.data.individual.dob && account.data.individual.dob.day } />
                </Grid>
                <Grid item xs={ 12 } md={ 4 }>
                  <FormControl style={ { width: '100%' } }>
                    <Select
                      autoWidth
                      native
                      name='individual[dob][month]'
                      style={ { marginRight: 8, marginTop: 16, width: '100%' } }
                    >
                      <FormattedMessage id='account.details.month' defaultMessage='Month of birth'>{ (msg) => <option value='' key={ 'default' }>{ msg }</option> }</FormattedMessage>
                      { [[1, 'Jan'], [2, 'Fev'], [3, 'Mar'], [4, 'Apr'], [5, 'May'], [6, 'June'], [7, 'Jul'], [8, 'Aug'], [9, 'Set'], [10, 'Oct'], [11, 'Nov'], [12, 'Dec']].map(
                        (item, i) => {
                          return (
                            <option selected={ account.data.individual && !!(item[0] === account.data.individual.dob.month || item[1] === accountData['individual[dob][month]']) } key={ i } value={ item[0] }>
                              { `${item[1]}` }
                            </option>
                          )
                        }
                      ) }
                    </Select>
                  </FormControl>
                </Grid>
                <Grid item xs={ 12 } md={ 4 }>
                  <Field name='individual[dob][year]' label='Year' type='number' defaultValue={ accountData['individual[dob][year]'] || account.data.individual && account.data.individual.dob && account.data.individual.dob.year } />
                </Grid>
              </Grid>
            </fieldset>
            <fieldset className={ classes.fieldset }>
              <legend className={ classes.legend }>
                <Typography>
                  <FormattedMessage id='account-details-address' defaultMessage='Address information' />
                </Typography>
              </legend>
              <Grid container spacing={ 2 }>
                <Grid item xs={ 12 } md={ 6 }>
                  <Field name='individual[address][line1]' label='Address line 1' defaultValue={ accountData['individual[address][line1]'] || account.data.individual && account.data.individual.address.line1 } />
                </Grid>
                <Grid item xs={ 12 } md={ 6 }>
                  <Field name='individual[address][line2]' label='Address line 2' defaultValue={ accountData['individual[address][line2]'] || account.data.individual && account.data.individual.address.line2 } />
                </Grid>
                <Grid item xs={ 12 } md={ 6 }>
                  <Field name='individual[address][city]' label='City' defaultValue={ accountData['individual[address][city]'] || account.data.individual && account.data.individual.address.city } />
                </Grid>
                <Grid item xs={ 12 } md={ 2 }>
                  <Field name='individual[address][state]' label='State' defaultValue={ accountData['individual[address][state]'] || account.data.individual && account.data.individual.address.state } />
                </Grid>
                <Grid item xs={ 12 } md={ 4 }>
                  <Field name='individual[address][postal_code]' label='Postal code' defaultValue={ accountData['individual[address][postal_code]'] || account.data.individual && account.data.individual.address.postal_code } />
                </Grid>
              </Grid>
            </fieldset>
            <Grid item xs={ 12 }>

                <Button onClick={ () => setDeleteUserDialog(true) }
                  variant='link'
                  style={ { color: '#353A42' } }
                >
                  <FormattedMessage id='account.profile.settings.delete.user.button' defaultMessage='Delete my account' />
                </Button>

                <DeleteUser
                  deleteUser={ () => user && onDeleteUser(user.user) }
                  user={ user }
                  visible={ deleteUserDialog }
                  onClose={ () => setDeleteUserDialog(false) }
                  onOpen={ () => setDeleteUserDialog(true) }
                />
                <Button
                  color='primary'
                  // onClick={closeUpdateModal}
                >
                  <FormattedMessage id='account.actions.cancel' defaultMessage='Cancel' />
                </Button>
                <Button
                  type='submit'
                  variant='contained'
                  color='secondary'
                >
                  <FormattedMessage id='account.actions.update' defaultMessage='Update Account' />
                </Button>

            </Grid>
          </Grid>) }
      </Grid>
    </form>
  )
}

export default injectIntl(withStyles(styles)(AccountDetails))
<|endoftext|>


<commit_before>/**
 初始化处理 vue component
 **/
(function (window, undefined) {
    "use strict";
    var vc = window.vc || {};
    var _vmOptions = {};
    var _initMethod = [];
    var _initEvent = [];
    var _component = {};
    var _destroyedMethod = [];
    var _timers = [];//定时器
    var _map = [];// 共享数据存储
    var _namespace = [];

    _vmOptions = {
        el: '#component',
        data: {},
        watch: {},
        methods: {},
        destroyed: function () {
            window.vc.destroyedMethod.forEach(function (eventMethod) {
                eventMethod();
            });
            //清理所有定时器

            window.vc.timers.forEach(function (timer) {
                clearInterval(timer);
            });

            _timers = [];
        }

    };
    vc = {
        version: "v0.0.1",
        name: "vue component",
        author: 'java110',
        vmOptions: _vmOptions,
        namespace: _namespace,
        initMethod: _initMethod,
        initEvent: _initEvent,
        component: _component,
        destroyedMethod: _destroyedMethod,
        debug: false,
        timers: _timers,
        _map: {}
    };
    //通知window对象
    window.vc = vc;
})(window);

/**
 vc 函数初始化
 add by wuxw
 **/
(function (vc) {
    var DEFAULT_NAMESPACE = "default";
    vc.http = {
        post: function (componentCode, componentMethod, param, options, successCallback, errorCallback) {
            vc.loading('open');
            Vue.http.post('/callComponent/' + componentCode + "/" + componentMethod, param, options)
                .then(function (res) {
                    successCallback(res.bodyText, res);
                    vc.loading('close');
                }, function (error) {
                    errorCallback(error.bodyText, error);
                    vc.loading('close');
                });
        },
        get: function (componentCode, componentMethod, param, successCallback, errorCallback) {
            //加入缓存机制
            var _getPath = '/' + componentCode + '/' + componentMethod;
            if (vc.constant.GET_CACHE_URL.includes(_getPath)) {
                var _cacheData = vc.getData(_getPath);
                //浏览器缓存中能获取到
                if (_cacheData != null && _cacheData != undefined) {
                    successCallback(JSON.stringify(_cacheData), {status: 200});
                    return;
                }
            }
            vc.loading('open');
            Vue.http.get('/callComponent/' + componentCode + "/" + componentMethod, param)
                .then(function (res) {
                    successCallback(res.bodyText, res);
                    if (vc.constant.GET_CACHE_URL.includes(_getPath) && res.status == 200) {
                        vc.saveData(_getPath, JSON.parse(res.bodyText));
                    }
                    vc.loading('close');
                }, function (error) {
                    errorCallback(error.bodyText, error);
                    vc.loading('close');
                });
        },
        upload: function (componentCode, componentMethod, param, options, successCallback, errorCallback) {
            vc.loading('open');
            Vue.http.post('/callComponent/upload/' + componentCode + "/" + componentMethod, param, options)
                .then(function (res) {
                    successCallback(res.bodyText, res);
                    vc.loading('close');
                }, function (error) {
                    errorCallback(error.bodyText, error);
                    vc.loading('close');
                });
        },

    };

    var vmOptions = vc.vmOptions;
    //继承方法,合并 _vmOptions 的数据到 vmOptions中
    vc.extends = function (_vmOptions) {
        if (typeof _vmOptions !== "object") {
            throw "_vmOptions is not Object";
        }
        var nameSpace = DEFAULT_NAMESPACE;
        if (_vmOptions.hasOwnProperty("namespace")) {
            nameSpace = _vmOptions.namespace;
            vc.namespace.push({
                namespace:_vmOptions.namespace,
            })
        }

        //处理 data 对象

        if (_vmOptions.hasOwnProperty('data')) {
            for (var dataAttr in _vmOptions.data) {
                if (nameSpace == DEFAULT_NAMESPACE) {
                    vmOptions.data[dataAttr] = _vmOptions.data[dataAttr];
                } else {
                    if(!vmOptions.data.hasOwnProperty(nameSpace)){
                        vmOptions.data[nameSpace] = {};
                    }
                    var dataNameSpace = vmOptions.data[nameSpace];
                    dataNameSpace[dataAttr] = _vmOptions.data[dataAttr];
                }
            }
        }
        //处理methods 对象
        if (_vmOptions.hasOwnProperty('methods')) {
            for (var methodAttr in _vmOptions.methods) {
                if (nameSpace == DEFAULT_NAMESPACE) {
                    vmOptions.methods[methodAttr] = _vmOptions.methods[methodAttr];
                } else {
                    if(!vmOptions.methods.hasOwnProperty(nameSpace)){
                        vmOptions.methods[nameSpace] = {};
                    }
                    var methodNameSpace = vmOptions.methods[nameSpace];
                    methodNameSpace[methodAttr] = _vmOptions.data[methodAttr];
                    /*vmOptions.methods[nameSpace][methodAttr] = _vmOptions.methods[methodAttr];*/
                }
            }
        }
        //处理methods 对象
        if (_vmOptions.hasOwnProperty('watch')) {
            for (var watchAttr in _vmOptions.watch) {
                if (nameSpace == DEFAULT_NAMESPACE) {
                    vmOptions.watch[watchAttr] = _vmOptions.watch[watchAttr];
                } else {
                    if(!vmOptions.watch.hasOwnProperty(nameSpace)){
                        vmOptions.watch[nameSpace] = {};
                    }
                    var methodNameSpace = vmOptions.watch[nameSpace];
                    methodNameSpace[watchAttr] = _vmOptions.watch[watchAttr];
                    /*vmOptions.watch[nameSpace][watchAttr] = _vmOptions.watch[watchAttr];*/
                }
            }
        }
        //处理_initMethod 初始化执行函数
        if (_vmOptions.hasOwnProperty('_initMethod')) {
            vc.initMethod.push(_vmOptions._initMethod);
        }
        //处理_initEvent
        if (_vmOptions.hasOwnProperty('_initEvent')) {
            vc.initEvent.push(_vmOptions._initEvent);
        }

        //处理_initEvent_destroyedMethod
        if (_vmOptions.hasOwnProperty('_destroyedMethod')) {
            vc.destroyedMethod.push(_vmOptions._destroyedMethod);
        }

    };

    //绑定跳转函数
    vc.jumpToPage = function (url) {
        window.location.href = url;
    };
    //保存菜单
    vc.setCurrentMenu = function (_menuId) {
        window.localStorage.setItem('hc_menuId', _menuId);
    };
    //获取菜单
    vc.getCurrentMenu = function () {
        return window.localStorage.getItem('hc_menuId');
    };

    //保存用户菜单
    vc.setMenus = function (_menus) {
        window.localStorage.setItem('hc_menus', JSON.stringify(_menus));
    };
    //获取用户菜单
    vc.getMenus = function () {
        return JSON.parse(window.localStorage.getItem('hc_menus'));
    };

    //保存菜单状态
    vc.setMenuState = function (_menuState) {
        window.localStorage.setItem('hc_menu_state', _menuState);
    };
    //获取菜单状态
    vc.getMenuState = function () {
        return window.localStorage.getItem('hc_menu_state');
    };

    //保存用户菜单
    vc.saveData = function (_key, _value) {
        window.localStorage.setItem(_key, JSON.stringify(_value));
    };
    //获取用户菜单
    vc.getData = function (_key) {
        return JSON.parse(window.localStorage.getItem(_key));
    };

    //保存当前小区信息 _communityInfo : {"communityId":"123213","name":"测试小区"}
    vc.setCurrentCommunity = function (_currentCommunityInfo) {
        window.localStorage.setItem('hc_currentCommunityInfo', JSON.stringify(_currentCommunityInfo));
    };

    //获取当前小区信息
    // @return   {"communityId":"123213","name":"测试小区"}
    vc.getCurrentCommunity = function () {
        return JSON.parse(window.localStorage.getItem('hc_currentCommunityInfo'));
    };

    //保存当前小区信息 _communityInfos : [{"communityId":"123213","name":"测试小区"}]
    vc.setCommunitys = function (_communityInfos) {
        window.localStorage.setItem('hc_communityInfos', JSON.stringify(_communityInfos));
    };

    //获取当前小区信息
    // @return   {"communityId":"123213","name":"测试小区"}
    vc.getCommunitys = function () {
        return JSON.parse(window.localStorage.getItem('hc_communityInfos'));
    };

    //删除缓存数据
    vc.clearCacheData = function () {
        window.localStorage.clear();
    };

    //将org 对象的属性值赋值给dst 属性名为一直的属性
    vc.copyObject = function (org, dst) {
        //for(key in Object.getOwnPropertyNames(dst)){
        for (var key in dst) {
            if (org.hasOwnProperty(key)) {
                dst[key] = org[key]
            }
        }
    };
    //扩展 现有的对象 没有的属性扩充上去
    vc.extendObject = function (org, dst) {
        for (var key in dst) {
            if (!org.hasOwnProperty(key)) {
                dst[key] = org[key]
            }
        }
    };
    //获取url参数
    vc.getParam = function (_key) {
        //返回当前 URL 的查询部分（问号 ? 之后的部分）。
        var urlParameters = location.search;
        //如果该求青中有请求的参数，则获取请求的参数，否则打印提示此请求没有请求的参数
        if (urlParameters.indexOf('?') != -1) {
            //获取请求参数的字符串
            var parameters = decodeURI(urlParameters.substr(1));
            //将请求的参数以&分割中字符串数组
            parameterArray = parameters.split('&');
            //循环遍历，将请求的参数封装到请求参数的对象之中
            for (var i = 0; i < parameterArray.length; i++) {
                if (_key == parameterArray[i].split('=')[0]) {
                    return parameterArray[i].split('=')[1];
                }
            }
        }

        return "";
    };
    //查询url
    vc.getUrl = function () {
        //返回当前 URL 的查询部分（问号 ? 之后的部分）。
        var urlParameters = location.pathname;
        return urlParameters;
    };
    //对象转get参数
    vc.objToGetParam = function (obj) {
        var str = [];
        for (var p in obj)
            if (obj.hasOwnProperty(p)) {
                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
            }
        return str.join("&");
    };
    //空判断 true 为非空 false 为空
    vc.notNull = function (_paramObj) {
        if (_paramObj == null || _paramObj == undefined || _paramObj.trim() == '') {
            return false;
        }
        return true;
    };
    //设置debug 模式
    vc.setDebug = function (_param) {
        vc.debug = _param;
    };
    //数据共享存放 主要为了组件间传递数据
    vc.put = function (_key, _value) {
        vc.map[_key] = _value;
    };
    //数据共享 获取 主要为了组件间传递数据
    vc.get = function (_key) {
        return vc.map[_key];
    };

})(window.vc);

/**
 vc 定时器处理
 **/
(function (w, vc) {

    /**
     创建定时器
     **/
    vc.createTimer = function (func, sec) {
        var _timer = w.setInterval(func, sec);
        vc.timers.push(_timer); //这里将所有的定时器保存起来，页面退出时清理

        return _timer;
    };
    //清理定时器
    vc.clearTimer = function (timer) {
        clearInterval(timer);
    }

})(window, window.vc);

/**
 时间处理工具类
 **/
(function (vc) {
    function add0(m) {
        return m < 10 ? '0' + m : m
    }

    vc.dateFormat = function (shijianchuo) {
        //shijianchuo是整数，否则要parseInt转换
        var time = new Date(parseInt(shijianchuo));
        var y = time.getFullYear();
        var m = time.getMonth() + 1;
        var d = time.getDate();
        var h = time.getHours();
        var mm = time.getMinutes();
        var s = time.getSeconds();
        return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
    }

})(window.vc);

(function (vc) {

    vc.propTypes = {
        string: "string",//字符串类型
        array: "array",
        object: "object",
        number: "number"
    }

})(window.vc);

/**
 toast
 **/
(function (vc) {
    vc.toast = function Toast(msg, duration) {
        duration = isNaN(duration) ? 3000 : duration;
        var m = document.createElement('div');
        m.innerHTML = msg;
        m.style.cssText = "max-width:60%;min-width: 150px;padding:0 14px;height: 40px;color: rgb(255, 255, 255);line-height: 40px;text-align: center;border-radius: 4px;position: fixed;top: 30%;left: 50%;transform: translate(-50%, -50%);z-index: 999999;background: rgba(0, 0, 0,.7);font-size: 16px;";
        document.body.appendChild(m);
        setTimeout(function () {
            var d = 0.5;
            m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
            m.style.opacity = '0';
            setTimeout(function () {
                document.body.removeChild(m)
            }, d * 1000);
        }, duration);
    }
})(window.vc);<commit_msg>优化method写错的问题<commit_after>/**
 初始化处理 vue component
 **/
(function (window, undefined) {
    "use strict";
    var vc = window.vc || {};
    var _vmOptions = {};
    var _initMethod = [];
    var _initEvent = [];
    var _component = {};
    var _destroyedMethod = [];
    var _timers = [];//定时器
    var _map = [];// 共享数据存储
    var _namespace = [];

    _vmOptions = {
        el: '#component',
        data: {},
        watch: {},
        methods: {},
        destroyed: function () {
            window.vc.destroyedMethod.forEach(function (eventMethod) {
                eventMethod();
            });
            //清理所有定时器

            window.vc.timers.forEach(function (timer) {
                clearInterval(timer);
            });

            _timers = [];
        }

    };
    vc = {
        version: "v0.0.1",
        name: "vue component",
        author: 'java110',
        vmOptions: _vmOptions,
        namespace: _namespace,
        initMethod: _initMethod,
        initEvent: _initEvent,
        component: _component,
        destroyedMethod: _destroyedMethod,
        debug: false,
        timers: _timers,
        _map: {}
    };
    //通知window对象
    window.vc = vc;
})(window);

/**
 vc 函数初始化
 add by wuxw
 **/
(function (vc) {
    var DEFAULT_NAMESPACE = "default";
    vc.http = {
        post: function (componentCode, componentMethod, param, options, successCallback, errorCallback) {
            vc.loading('open');
            Vue.http.post('/callComponent/' + componentCode + "/" + componentMethod, param, options)
                .then(function (res) {
                    successCallback(res.bodyText, res);
                    vc.loading('close');
                }, function (error) {
                    errorCallback(error.bodyText, error);
                    vc.loading('close');
                });
        },
        get: function (componentCode, componentMethod, param, successCallback, errorCallback) {
            //加入缓存机制
            var _getPath = '/' + componentCode + '/' + componentMethod;
            if (vc.constant.GET_CACHE_URL.includes(_getPath)) {
                var _cacheData = vc.getData(_getPath);
                //浏览器缓存中能获取到
                if (_cacheData != null && _cacheData != undefined) {
                    successCallback(JSON.stringify(_cacheData), {status: 200});
                    return;
                }
            }
            vc.loading('open');
            Vue.http.get('/callComponent/' + componentCode + "/" + componentMethod, param)
                .then(function (res) {
                    successCallback(res.bodyText, res);
                    if (vc.constant.GET_CACHE_URL.includes(_getPath) && res.status == 200) {
                        vc.saveData(_getPath, JSON.parse(res.bodyText));
                    }
                    vc.loading('close');
                }, function (error) {
                    errorCallback(error.bodyText, error);
                    vc.loading('close');
                });
        },
        upload: function (componentCode, componentMethod, param, options, successCallback, errorCallback) {
            vc.loading('open');
            Vue.http.post('/callComponent/upload/' + componentCode + "/" + componentMethod, param, options)
                .then(function (res) {
                    successCallback(res.bodyText, res);
                    vc.loading('close');
                }, function (error) {
                    errorCallback(error.bodyText, error);
                    vc.loading('close');
                });
        },

    };

    var vmOptions = vc.vmOptions;
    //继承方法,合并 _vmOptions 的数据到 vmOptions中
    vc.extends = function (_vmOptions) {
        if (typeof _vmOptions !== "object") {
            throw "_vmOptions is not Object";
        }
        var nameSpace = DEFAULT_NAMESPACE;
        if (_vmOptions.hasOwnProperty("namespace")) {
            nameSpace = _vmOptions.namespace;
            vc.namespace.push({
                namespace:_vmOptions.namespace,
            })
        }

        //处理 data 对象

        if (_vmOptions.hasOwnProperty('data')) {
            for (var dataAttr in _vmOptions.data) {
                if (nameSpace == DEFAULT_NAMESPACE) {
                    vmOptions.data[dataAttr] = _vmOptions.data[dataAttr];
                } else {
                    if(!vmOptions.data.hasOwnProperty(nameSpace)){
                        vmOptions.data[nameSpace] = {};
                    }
                    var dataNameSpace = vmOptions.data[nameSpace];
                    dataNameSpace[dataAttr] = _vmOptions.data[dataAttr];
                }
            }
        }
        //处理methods 对象
        if (_vmOptions.hasOwnProperty('methods')) {
            for (var methodAttr in _vmOptions.methods) {
                if (nameSpace == DEFAULT_NAMESPACE) {
                    vmOptions.methods[methodAttr] = _vmOptions.methods[methodAttr];
                } else {
                    if(!vmOptions.methods.hasOwnProperty(nameSpace)){
                        vmOptions.methods[nameSpace] = {};
                    }
                    var methodNameSpace = vmOptions.methods[nameSpace];
                    methodNameSpace[methodAttr] = _vmOptions.methods[methodAttr];
                    /*vmOptions.methods[nameSpace][methodAttr] = _vmOptions.methods[methodAttr];*/
                }
            }
        }
        //处理methods 对象
        if (_vmOptions.hasOwnProperty('watch')) {
            for (var watchAttr in _vmOptions.watch) {
                if (nameSpace == DEFAULT_NAMESPACE) {
                    vmOptions.watch[watchAttr] = _vmOptions.watch[watchAttr];
                } else {
                    if(!vmOptions.watch.hasOwnProperty(nameSpace)){
                        vmOptions.watch[nameSpace] = {};
                    }
                    var methodNameSpace = vmOptions.watch[nameSpace];
                    methodNameSpace[watchAttr] = _vmOptions.watch[watchAttr];
                    /*vmOptions.watch[nameSpace][watchAttr] = _vmOptions.watch[watchAttr];*/
                }
            }
        }
        //处理_initMethod 初始化执行函数
        if (_vmOptions.hasOwnProperty('_initMethod')) {
            vc.initMethod.push(_vmOptions._initMethod);
        }
        //处理_initEvent
        if (_vmOptions.hasOwnProperty('_initEvent')) {
            vc.initEvent.push(_vmOptions._initEvent);
        }

        //处理_initEvent_destroyedMethod
        if (_vmOptions.hasOwnProperty('_destroyedMethod')) {
            vc.destroyedMethod.push(_vmOptions._destroyedMethod);
        }

    };

    //绑定跳转函数
    vc.jumpToPage = function (url) {
        window.location.href = url;
    };
    //保存菜单
    vc.setCurrentMenu = function (_menuId) {
        window.localStorage.setItem('hc_menuId', _menuId);
    };
    //获取菜单
    vc.getCurrentMenu = function () {
        return window.localStorage.getItem('hc_menuId');
    };

    //保存用户菜单
    vc.setMenus = function (_menus) {
        window.localStorage.setItem('hc_menus', JSON.stringify(_menus));
    };
    //获取用户菜单
    vc.getMenus = function () {
        return JSON.parse(window.localStorage.getItem('hc_menus'));
    };

    //保存菜单状态
    vc.setMenuState = function (_menuState) {
        window.localStorage.setItem('hc_menu_state', _menuState);
    };
    //获取菜单状态
    vc.getMenuState = function () {
        return window.localStorage.getItem('hc_menu_state');
    };

    //保存用户菜单
    vc.saveData = function (_key, _value) {
        window.localStorage.setItem(_key, JSON.stringify(_value));
    };
    //获取用户菜单
    vc.getData = function (_key) {
        return JSON.parse(window.localStorage.getItem(_key));
    };

    //保存当前小区信息 _communityInfo : {"communityId":"123213","name":"测试小区"}
    vc.setCurrentCommunity = function (_currentCommunityInfo) {
        window.localStorage.setItem('hc_currentCommunityInfo', JSON.stringify(_currentCommunityInfo));
    };

    //获取当前小区信息
    // @return   {"communityId":"123213","name":"测试小区"}
    vc.getCurrentCommunity = function () {
        return JSON.parse(window.localStorage.getItem('hc_currentCommunityInfo'));
    };

    //保存当前小区信息 _communityInfos : [{"communityId":"123213","name":"测试小区"}]
    vc.setCommunitys = function (_communityInfos) {
        window.localStorage.setItem('hc_communityInfos', JSON.stringify(_communityInfos));
    };

    //获取当前小区信息
    // @return   {"communityId":"123213","name":"测试小区"}
    vc.getCommunitys = function () {
        return JSON.parse(window.localStorage.getItem('hc_communityInfos'));
    };

    //删除缓存数据
    vc.clearCacheData = function () {
        window.localStorage.clear();
    };

    //将org 对象的属性值赋值给dst 属性名为一直的属性
    vc.copyObject = function (org, dst) {
        //for(key in Object.getOwnPropertyNames(dst)){
        for (var key in dst) {
            if (org.hasOwnProperty(key)) {
                dst[key] = org[key]
            }
        }
    };
    //扩展 现有的对象 没有的属性扩充上去
    vc.extendObject = function (org, dst) {
        for (var key in dst) {
            if (!org.hasOwnProperty(key)) {
                dst[key] = org[key]
            }
        }
    };
    //获取url参数
    vc.getParam = function (_key) {
        //返回当前 URL 的查询部分（问号 ? 之后的部分）。
        var urlParameters = location.search;
        //如果该求青中有请求的参数，则获取请求的参数，否则打印提示此请求没有请求的参数
        if (urlParameters.indexOf('?') != -1) {
            //获取请求参数的字符串
            var parameters = decodeURI(urlParameters.substr(1));
            //将请求的参数以&分割中字符串数组
            parameterArray = parameters.split('&');
            //循环遍历，将请求的参数封装到请求参数的对象之中
            for (var i = 0; i < parameterArray.length; i++) {
                if (_key == parameterArray[i].split('=')[0]) {
                    return parameterArray[i].split('=')[1];
                }
            }
        }

        return "";
    };
    //查询url
    vc.getUrl = function () {
        //返回当前 URL 的查询部分（问号 ? 之后的部分）。
        var urlParameters = location.pathname;
        return urlParameters;
    };
    //对象转get参数
    vc.objToGetParam = function (obj) {
        var str = [];
        for (var p in obj)
            if (obj.hasOwnProperty(p)) {
                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
            }
        return str.join("&");
    };
    //空判断 true 为非空 false 为空
    vc.notNull = function (_paramObj) {
        if (_paramObj == null || _paramObj == undefined || _paramObj.trim() == '') {
            return false;
        }
        return true;
    };
    //设置debug 模式
    vc.setDebug = function (_param) {
        vc.debug = _param;
    };
    //数据共享存放 主要为了组件间传递数据
    vc.put = function (_key, _value) {
        vc.map[_key] = _value;
    };
    //数据共享 获取 主要为了组件间传递数据
    vc.get = function (_key) {
        return vc.map[_key];
    };

})(window.vc);

/**
 vc 定时器处理
 **/
(function (w, vc) {

    /**
     创建定时器
     **/
    vc.createTimer = function (func, sec) {
        var _timer = w.setInterval(func, sec);
        vc.timers.push(_timer); //这里将所有的定时器保存起来，页面退出时清理

        return _timer;
    };
    //清理定时器
    vc.clearTimer = function (timer) {
        clearInterval(timer);
    }

})(window, window.vc);

/**
 时间处理工具类
 **/
(function (vc) {
    function add0(m) {
        return m < 10 ? '0' + m : m
    }

    vc.dateFormat = function (shijianchuo) {
        //shijianchuo是整数，否则要parseInt转换
        var time = new Date(parseInt(shijianchuo));
        var y = time.getFullYear();
        var m = time.getMonth() + 1;
        var d = time.getDate();
        var h = time.getHours();
        var mm = time.getMinutes();
        var s = time.getSeconds();
        return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
    }

})(window.vc);

(function (vc) {

    vc.propTypes = {
        string: "string",//字符串类型
        array: "array",
        object: "object",
        number: "number"
    }

})(window.vc);

/**
 toast
 **/
(function (vc) {
    vc.toast = function Toast(msg, duration) {
        duration = isNaN(duration) ? 3000 : duration;
        var m = document.createElement('div');
        m.innerHTML = msg;
        m.style.cssText = "max-width:60%;min-width: 150px;padding:0 14px;height: 40px;color: rgb(255, 255, 255);line-height: 40px;text-align: center;border-radius: 4px;position: fixed;top: 30%;left: 50%;transform: translate(-50%, -50%);z-index: 999999;background: rgba(0, 0, 0,.7);font-size: 16px;";
        document.body.appendChild(m);
        setTimeout(function () {
            var d = 0.5;
            m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
            m.style.opacity = '0';
            setTimeout(function () {
                document.body.removeChild(m)
            }, d * 1000);
        }, duration);
    }
})(window.vc);<|endoftext|>


<commit_before>module.exports = function() {
    return {
      tableData:[],
      cols:false,
      totalPages:null,
      currentRecordsCount:null,
      lengths: [5,10,20,50],
      ascending:true,
      orderBy:null,
      query:'',
      page:1,
      limit:5,
      count:0,
      currentRecordsCount:null,
      texts:{
      count:"{count} Records",
      filter:"Filter Results:",
      filterPlaceholder:"Search query",
      limit:"Records:",
      sortable:[]
    }
  }
}

<commit_msg>change deafult limit to 10<commit_after>module.exports = function() {
    return {
      tableData:[],
      cols:false,
      totalPages:null,
      currentRecordsCount:null,
      lengths: [5,10,20,50],
      ascending:true,
      orderBy:null,
      query:'',
      page:1,
      limit:10,
      count:0,
      currentRecordsCount:null,
      texts:{
      count:"{count} Records",
      filter:"Filter Results:",
      filterPlaceholder:"Search query",
      limit:"Records:",
      sortable:[]
    }
  }
}

<|endoftext|>


<commit_before>
var data = JSON.parse(request.body);
properties = {};
properties.alert_name = data.alert_name;

console.log(properties.alert_name);

var trigger = JSON.stringify({
	"properties": {
  "alert_title": data.alert_title,
  "message": data.message,
  "alert_severity": data.alert_severity,
  "alert_event_samples": data.alert_event_samples,
  "text": data.text,
}

});

//"recipients" : [ {"targetName": callback.recipient } ]
console.log( 'Response payload: ' + JSON.stringify( trigger ) );
var req = http.request({
method: 'POST',
endpoint: 'xMatters',
path: '/reapi/2015-04-01/forms/205b29cc-d87f-4d07-b89d-04b112504da2/triggers',
headers: {
'Content-Type': 'application/json'
}
});
req.write(trigger);

<commit_msg>extension change<commit_after>
var data = JSON.parse(request.body);
properties = {};
properties.alert_name = data.alert_name;

console.log(properties.alert_name);

var trigger = JSON.stringify({
	"properties": {
  "alert_title": data.alert_title,
  "message": data.message,
  "alert_severity": data.alert_severity,
  "alert_event_samples": data.alert_event_samples,
  "text": data.text,
}

});

//"recipients" : [ {"targetName": callback.recipient } ]
console.log( 'Response payload: ' + JSON.stringify( trigger ) );
var req = http.request({
method: 'POST',
endpoint: 'xMatters',
path: '/reapi/2015-04-01/forms/205b29cc-d87f-4d07-b89d-04b112504da2/triggers',
headers: {
'Content-Type': 'application/json'
}
});
req.write(trigger);

<|endoftext|>