<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 * @flow
 */

'use strict';

const ColorPropType = require('ColorPropType');
const NativeMethodsMixin = require('NativeMethodsMixin');
const Platform = require('Platform');
const ProgressBarAndroid = require('ProgressBarAndroid');
const PropTypes = require('prop-types');
const React = require('React');
const StyleSheet = require('StyleSheet');
const View = require('View');
const ViewPropTypes = require('ViewPropTypes');

const createReactClass = require('create-react-class');
const requireNativeComponent = require('requireNativeComponent');
let RCTActivityIndicator;

const GRAY = '#999999';

type IndicatorSize = number | 'small' | 'large';

type DefaultProps = {
  animating: boolean,
  color: any,
  hidesWhenStopped: boolean,
  size: IndicatorSize,
};

/**
 * Displays a circular loading indicator.
 *
 * See http://facebook.github.io/react-native/docs/activityindicator.html
 */
const ActivityIndicator = createReactClass({
  displayName: 'ActivityIndicator',
  mixins: [NativeMethodsMixin],

  propTypes: {
    ...ViewPropTypes,
    /**
     * Whether to show the indicator (true, the default) or hide it (false).
     *
     * See http://facebook.github.io/react-native/docs/activityindicator.html#animating
     */
    animating: PropTypes.bool,
    /**
     * The foreground color of the spinner (default is gray).
     *
     * See http://facebook.github.io/react-native/docs/activityindicator.html#color
     */
    color: ColorPropType,
    /**
     * Size of the indicator (default is 'small').
     * Passing a number to the size prop is only supported on Android.
     *
     * See http://facebook.github.io/react-native/docs/activityindicator.html#size
     */
    size: PropTypes.oneOfType([
      PropTypes.oneOf(['small', 'large']),
      PropTypes.number,
    ]),
    /**
     * Whether the indicator should hide when not animating (true by default).
     *
     * @platform ios
     *
     * See http://facebook.github.io/react-native/docs/activityindicator.html#hideswhenstopped
     */
    hidesWhenStopped: PropTypes.bool,
  },

  getDefaultProps(): DefaultProps {
    return {
      animating: true,
      color: Platform.OS === 'ios' ? GRAY : undefined,
      hidesWhenStopped: true,
      size: 'small',
    };
  },

  render() {
    const {onLayout, style, ...props} = this.props;
    let sizeStyle;

    switch (props.size) {
      case 'small':
        sizeStyle = styles.sizeSmall;
        break;
      case 'large':
        sizeStyle = styles.sizeLarge;
        break;
      default:
        sizeStyle = {height: props.size, width: props.size};
        break;
    }

    const nativeProps = {
      ...props,
      style: sizeStyle,
      styleAttr: 'Normal',
      indeterminate: true,
    };

    return (
      <View onLayout={onLayout} style={[styles.container, style]}>
        {Platform.OS === 'ios' ? (
          <RCTActivityIndicator {...nativeProps} />
        ) : (
          <ProgressBarAndroid {...nativeProps} />
        )}
      </View>
    );
  },
});

if (Platform.OS === 'ios') {
  RCTActivityIndicator = requireNativeComponent(
    'RCTActivityIndicatorView',
    ActivityIndicator,
    {nativeOnly: {activityIndicatorViewStyle: true}},
  );
}

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  sizeSmall: {
    width: 20,
    height: 20,
  },
  sizeLarge: {
    width: 36,
    height: 36,
  },
});

module.exports = ActivityIndicator;
<commit_msg>Flow Typing ActivityIndicator<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 * @flow
 */

'use strict';

const ColorPropType = require('ColorPropType');
const NativeMethodsMixin = require('NativeMethodsMixin');
const Platform = require('Platform');
const ProgressBarAndroid = require('ProgressBarAndroid');
const PropTypes = require('prop-types');
const React = require('React');
const StyleSheet = require('StyleSheet');
const View = require('View');
const ViewPropTypes = require('ViewPropTypes');

const createReactClass = require('create-react-class');
const requireNativeComponent = require('requireNativeComponent');

import type {ViewProps} from 'ViewPropTypes';

let RCTActivityIndicator;

const GRAY = '#999999';

type IndicatorSize = number | 'small' | 'large';

type Props = $ReadOnly<{|
  ...ViewProps,

  animating?: ?boolean,
  color?: ?string,
  hidesWhenStopped?: ?boolean,
  size?: ?IndicatorSize,
|}>;

type DefaultProps = {
  animating: boolean,
  color: ?string,
  hidesWhenStopped: boolean,
  size: IndicatorSize,
};

/**
 * Displays a circular loading indicator.
 *
 * See http://facebook.github.io/react-native/docs/activityindicator.html
 */
const ActivityIndicator = ((createReactClass({
  displayName: 'ActivityIndicator',
  mixins: [NativeMethodsMixin],

  propTypes: {
    ...ViewPropTypes,
    /**
     * Whether to show the indicator (true, the default) or hide it (false).
     *
     * See http://facebook.github.io/react-native/docs/activityindicator.html#animating
     */
    animating: PropTypes.bool,
    /**
     * The foreground color of the spinner (default is gray).
     *
     * See http://facebook.github.io/react-native/docs/activityindicator.html#color
     */
    color: ColorPropType,
    /**
     * Size of the indicator (default is 'small').
     * Passing a number to the size prop is only supported on Android.
     *
     * See http://facebook.github.io/react-native/docs/activityindicator.html#size
     */
    size: PropTypes.oneOfType([
      PropTypes.oneOf(['small', 'large']),
      PropTypes.number,
    ]),
    /**
     * Whether the indicator should hide when not animating (true by default).
     *
     * @platform ios
     *
     * See http://facebook.github.io/react-native/docs/activityindicator.html#hideswhenstopped
     */
    hidesWhenStopped: PropTypes.bool,
  },

  getDefaultProps(): DefaultProps {
    return {
      animating: true,
      color: Platform.OS === 'ios' ? GRAY : null,
      hidesWhenStopped: true,
      size: 'small',
    };
  },

  render() {
    const {onLayout, style, ...props} = this.props;
    let sizeStyle;

    switch (props.size) {
      case 'small':
        sizeStyle = styles.sizeSmall;
        break;
      case 'large':
        sizeStyle = styles.sizeLarge;
        break;
      default:
        sizeStyle = {height: props.size, width: props.size};
        break;
    }

    const nativeProps = {
      ...props,
      style: sizeStyle,
      styleAttr: 'Normal',
      indeterminate: true,
    };

    return (
      <View onLayout={onLayout} style={[styles.container, style]}>
        {Platform.OS === 'ios' ? (
          <RCTActivityIndicator {...nativeProps} />
        ) : (
          <ProgressBarAndroid {...nativeProps} />
        )}
      </View>
    );
  },
}): any): React.ComponentType<Props>);

if (Platform.OS === 'ios') {
  RCTActivityIndicator = requireNativeComponent(
    'RCTActivityIndicatorView',
    ActivityIndicator,
    {nativeOnly: {activityIndicatorViewStyle: true}},
  );
}

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  sizeSmall: {
    width: 20,
    height: 20,
  },
  sizeLarge: {
    width: 36,
    height: 36,
  },
});

module.exports = ActivityIndicator;
<|endoftext|>


<commit_before>PRESTATION_TO_TEST_POSITION = 1
PRESTATION_NAME = /Prime d’activité/
PRESTATION_DESCRIPTION = /complète les revenus/
HAS_PRESTATION_WARNING = false
HAS_PRESTATION_ENGAGER_DEMARCHES_LINK = true
<commit_msg>Increase test resilience<commit_after>PRESTATION_TO_TEST_POSITION = 1
PRESTATION_NAME = /Prime d’activité/
PRESTATION_DESCRIPTION = /revenus/
HAS_PRESTATION_WARNING = false
HAS_PRESTATION_ENGAGER_DEMARCHES_LINK = true
<|endoftext|>


<commit_before>'use strict';

const bootstrap = require('./bootstrap');

const config = bootstrap.config;
const should = bootstrap.should;

const Wechat = require('../lib');

const util = require('../lib/utils');

const wx = new Wechat(config);

describe('Card', function () {

  describe('#getCardSignature()', function () {
    this.timeout(20000);
    it('should get cardSign', function (done) {
      wx.card.getCardSignature('myShopId', 'myCardType', 'myCardId')
        .then(sigInfo => {
          // console.log(sigInfo);
          sigInfo.should.have.property('cardSign');
          sigInfo.should.have.property('timestamp');
          sigInfo.should.have.property('nonceStr');
        })
        .catch(reason => {
          // console.log(reason);
        })
        .then(() => done());
    });

  });

  describe('#getApiTicket()', function (done) {
    setTimeout(() => {
      const store = wx.card.store;
      store.store.card = {};
      store.store.globalToken.modifyDate = new Date(0);
      wx.card.getApiTicket()
        .then(ticket => {
          ticket.should.have.property('ticket');
          done();
        })
        .catch(() => done());
    }, 1000);
  });

  describe('#getCardExt()', function () {
    this.timeout(20000);
    it('should get cardExt', function (done) {
      wx.card.getCardExt('myCardId', 'myCode', 'myOpenId', util.timestamp(), util.nonceStr())
        .then(cardExt => {
          // console.log(cardExt);
          const extObj = JSON.parse(cardExt);
          extObj.should.have.property('signature');
          extObj.should.have.property('timestamp');
          extObj.should.have.property('nonce_str');
        })
        .catch(reason => {
          // console.log(reason);
        })
        .then(() => done());
    });
  });

});
<commit_msg>enable card in card tests<commit_after>'use strict';

const bootstrap = require('./bootstrap');

const config = bootstrap.config;
const should = bootstrap.should;

const Wechat = require('../lib');

const util = require('../lib/utils');

const wx = new Wechat(Object.assign({}, config, {
  card: true,
}));

describe('Card', function () {

  describe('#getCardSignature()', function () {
    this.timeout(20000);
    it('should get cardSign', function (done) {
      wx.card.getCardSignature('myShopId', 'myCardType', 'myCardId')
        .then(sigInfo => {
          // console.log(sigInfo);
          sigInfo.should.have.property('cardSign');
          sigInfo.should.have.property('timestamp');
          sigInfo.should.have.property('nonceStr');
        })
        .catch(reason => {
          // console.log(reason);
        })
        .then(() => done());
    });

  });

  describe('#getApiTicket()', function (done) {
    setTimeout(() => {
      const store = wx.card.store;
      store.store.card = {};
      store.store.globalToken.modifyDate = new Date(0);
      wx.card.getApiTicket()
        .then(ticket => {
          ticket.should.have.property('ticket');
          done();
        })
        .catch(() => done());
    }, 1000);
  });

  describe('#getCardExt()', function () {
    this.timeout(20000);
    it('should get cardExt', function (done) {
      wx.card.getCardExt('myCardId', 'myCode', 'myOpenId', util.timestamp(), util.nonceStr())
        .then(cardExt => {
          // console.log(cardExt);
          const extObj = JSON.parse(cardExt);
          extObj.should.have.property('signature');
          extObj.should.have.property('timestamp');
          extObj.should.have.property('nonce_str');
        })
        .catch(reason => {
          // console.log(reason);
        })
        .then(() => done());
    });
  });

});
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var assert = require('assert');
var globalTimers = {
    setTimeout: require('timers').setTimeout,
    clearTimeout: require('timers').clearTimeout,
    now: Date.now
};
var globalRandom = Math.random;
var net = require('net');
var format = require('util').format;
var extend = require('xtend');

var inherits = require('util').inherits;
var StatEmitter = require('./lib/stat_emitter');

var nullLogger = require('./null-logger.js');
var EndpointHandler = require('./endpoint-handler.js');
var TChannelRequest = require('./request');
var TChannelServiceNameHandler = require('./service-name-handler');
var errors = require('./errors');

var TChannelConnection = require('./connection');
var TChannelPeers = require('./peers');
var TChannelServices = require('./services');

var TracingAgent = require('./trace/agent');

var CONN_STALE_PERIOD = 1500;

// TODO restore spying
// var Spy = require('./v2/spy');
// var dumpEnabled = /\btchannel_dump\b/.test(process.env.NODE_DEBUG || '');

function TChannel(options) {
    if (!(this instanceof TChannel)) {
        return new TChannel(options);
    }

    var self = this;
    StatEmitter.call(self);
    self.errorEvent = self.defineEvent('error');
    self.listeningEvent = self.defineEvent('listening');
    self.connectionEvent = self.defineEvent('connection');
    self.requestEvent = self.defineEvent('request');
    self.outboundCallsSentStat = self.defineCounter('outbound.calls.sent');
    self.outboundCallsSystemErrorsStat = self.defineCounter('outbound.calls.system-errors');
    self.outboundCallsOperationalErrorsStat = self.defineCounter('outbound.calls.operational-errors');
    self.outboundCallsSuccessStat = self.defineCounter('outbound.calls.success');
    self.outboundCallsAppErrorsStat = self.defineCounter('outbound.app-errors.success');
    self.outboundCallsRetriesStat = self.defineCounter('outbound.calls.retries');
    self.outboundCallsLatencyStat = self.defineTiming('outbound.calls.latency');
    self.outboundCallsPerAttemptLatencyStat = self.defineTiming('outbound.calls.per-attempt-latency');

    self.options = extend({
        timeoutCheckInterval: 100,
        timeoutFuzz: 100,
        connectionStalePeriod: CONN_STALE_PERIOD,

        // TODO: maybe we should always add pid to user-supplied?
        processName: format('%s[%s]', process.title, process.pid)
    }, options);

    // must have 'app', 'host', 'cluster', 'version'
    self.statTags = self.options.statTags || {};

    self.requestDefaults = extend({
        timeout: TChannelRequest.defaultTimeout
    }, self.options.requestDefaults);

    self.logger = self.options.logger || nullLogger;
    self.random = self.options.random || globalRandom;
    self.timers = self.options.timers || globalTimers;
    self.initTimeout = self.options.initTimeout || 2000;

    // Filled in by the listen call:
    self.host = null;
    self.requestedPort = null;

    // Filled in by listening event:
    self.hostPort = null;

    // name of the service running over this channel
    self.serviceName = '';
    if (self.options.serviceName) {
        self.serviceName = self.options.serviceName;
        delete self.options.serviceName;
    }

    // populated by makeSubChannel
    self.topChannel = null;
    self.subChannels = self.serviceName ? null : {};

    // how to handle incoming requests
    if (!self.options.handler) {
        if (!self.serviceName) {
            self.handler = TChannelServiceNameHandler(self);
        } else {
            self.handler = EndpointHandler(self.serviceName);
        }
    } else {
        self.handler = self.options.handler;
        delete self.options.handler;
    }

    // populated by:
    // - manually api (.peers.add etc)
    // - incoming connections on any listening socket
    self.peers = TChannelPeers(self, self.options);

    // For tracking the number of pending requests to any service
    self.services = new TChannelServices();
    if (self.options.maxPending !== undefined) {
        self.services.maxPending = self.options.maxPending;
    }
    if (self.options.maxPendingForService !== undefined) {
        self.services.maxPendingForService = self.options.maxPendingForService;
    }

    // TChannel advances through the following states.
    self.listened = false;
    self.listening = false;
    self.destroyed = false;

    if (self.options.trace) {
        self.tracer = new TracingAgent({
            logger: self.logger,
            forceTrace: self.options.forceTrace,
            serviceName: self.options.tracingServiceName,
            reporter: self.options.traceReporter
        });

        if (self.requestDefaults.trace !== false) {
            self.requestDefaults.trace = true;
        }
    }

    // lazily created by .getServer (usually from .listen)
    self.serverSocket = null;
    self.serverConnections = null;
}
inherits(TChannel, StatEmitter);

TChannel.prototype.getServer = function getServer() {
    var self = this;
    if (self.serverSocket) {
        return self.serverSocket;
    }

    self.serverConnections = Object.create(null);
    self.serverSocket = net.createServer(onServerSocketConnection);
    self.serverSocket.on('listening', onServerSocketListening);
    self.serverSocket.on('error', onServerSocketError);

    return self.serverSocket;

    function onServerSocketConnection(sock) {
        self.onServerSocketConnection(sock);
    }

    function onServerSocketListening() {
        self.onServerSocketListening();
    }

    function onServerSocketError(err) {
        self.onServerSocketError(err);
    }
};

TChannel.prototype.onServerSocketConnection = function onServerSocketConnection(sock) {
    var self = this;

    if (self.destroyed) {
        self.logger.error('got incoming socket whilst destroyed', {
            remoteAddr: sock.remoteAddr,
            remotePort: sock.remotePort,
            hostPort: self.hostPort
        });
        return;
    }

    var remoteAddr = sock.remoteAddress + ':' + sock.remotePort;
    var conn = new TChannelConnection(self, sock, 'in', remoteAddr);

    conn.spanEvent.on(function handleSpanFromConn(span) {
        self.tracer.report(span);
    });

    if (self.serverConnections[remoteAddr]) {
        var oldConn = self.serverConnections[remoteAddr];
        oldConn.resetAll(errors.SocketClosedError({
            reason: 'duplicate remoteAddr incoming conn'
        }));
        delete self.serverConnections[remoteAddr];
    }

    sock.on('close', onSocketClose);

    self.serverConnections[remoteAddr] = conn;
    self.connectionEvent.emit(self, conn);

    function onSocketClose() {
        delete self.serverConnections[remoteAddr];
    }
};

TChannel.prototype.onServerSocketListening = function onServerSocketListening() {
    var self = this;

    if (self.destroyed) {
        self.logger.error('got serverSocket listen whilst destroyed', {
            requestHostPort: self.host + ':' + self.requestedPort,
            hostPort: self.host + ':' + self.serverSocket.address().port
        });
        return;
    }

    var address = self.serverSocket.address();
    self.hostPort = self.host + ':' + address.port;
    self.listening = true;

    if (self.subChannels) {
        Object.keys(self.subChannels).forEach(function each(serviceName) {
            var chan = self.subChannels[serviceName];
            if (!chan.hostPort) {
                chan.hostPort = self.hostPort;
            }
        });
    }

    self.listeningEvent.emit(self);
};

TChannel.prototype.onServerSocketError = function onServerSocketError(err) {
    var self = this;

    if (err.code === 'EADDRINUSE') {
        err = errors.TChannelListenError(err, {
            requestedPort: self.requestedPort,
            host: self.host
        });
    }
    self.logger.error('server socket error', {
        err: err,
        requestedPort: self.requestedPort,
        host: self.host,
        hostPort: self.hostPort || null
    });
    self.errorEvent.emit(self, err);
};

TChannel.prototype.makeSubChannel = function makeSubChannel(options) {
    var self = this;
    if (!options) options = {};
    assert(!self.serviceName, 'arbitrary-depth sub channels are unsupported');
    assert(options.serviceName, 'must specify serviceName');
    assert(!self.subChannels[options.serviceName], 'duplicate sub channel creation');
    var opts = extend(self.options);
    var keys = Object.keys(options);
    for (var i = 0; i < keys.length; i++) {
        switch (keys[i]) {
            case 'peers':
                break;
            default:
                opts[keys[i]] = options[keys[i]];
        }
    }
    var chan = TChannel(opts);
    chan.topChannel = self;
    if (options.peers) {
        for (i = 0; i < options.peers.length; i++) {
            if (typeof options.peers[i] === 'string') {
                chan.peers.addPeer(self.peers.add(options.peers[i]));
            } else {
                chan.peers.addPeer(options.peers[i]);
            }
        }
    }
    self.subChannels[chan.serviceName] = chan;

    if (self.hostPort) {
        chan.hostPort = self.hostPort;
    }

    return chan;
};

TChannel.prototype.listen = function listen(port, host, callback) {
    // Note:
    // - 0 is a valid port number, indicating that the system must assign an
    //   available ephemeral port
    // - 127.0.0.1 is a valid host, primarily for testing
    var self = this;
    assert(!self.listened, 'TChannel can only listen once');
    assert(typeof host === 'string', 'TChannel requires host argument');
    assert(typeof port === 'number', 'TChannel must listen with numeric port');
    assert(host !== '0.0.0.0', 'TChannel must listen with externally visible host');
    self.listened = true;
    self.requestedPort = port;
    self.host = host;
    self.getServer().listen(port, host, callback);
};

TChannel.prototype.register = function register(name, options, handler) {
    var self = this;

    var handlerType = self.handler && self.handler.type;

    switch (handlerType) {
        case 'tchannel.endpoint-handler':
            self.handler.register(name, options, handler);
            break;

        case 'tchannel.service-name-handler':
            throw errors.TopLevelRegisterError();

        default:
            throw errors.InvalidHandlerForRegister({
                handlerType: handlerType,
                handler: self.handler
            });
    }
};

TChannel.prototype.address = function address() {
    var self = this;
    if (self.serverSocket) {
        return self.serverSocket.address() || null;
    } else if (self.topChannel) {
        return self.topChannel.address();
    } else {
        return null;
    }
};

TChannel.prototype.requestOptions = function requestOptions(options) {
    var self = this;
    var prop;
    var opts = {};
    // jshint forin:false
    for (prop in self.requestDefaults) {
        opts[prop] = self.requestDefaults[prop];
    }
    if (options) {
        for (prop in options) {
            opts[prop] = options[prop];
        }
    }
    // jshint forin:true
    return opts;
};

TChannel.prototype.waitForIdentified =
function waitForIdentified(options, callback) {
    var self = this;

    self.peers.waitForIdentified(options, callback);
};

TChannel.prototype.request = function channelRequest(options) {
    var self = this;
    assert(!self.destroyed, 'cannot request() to destroyed tchannel');
    var opts = self.requestOptions(options);

    if (!self.serviceName && !opts.host) {
        if (opts.serviceName &&
            self.subChannels &&
            self.subChannels[opts.serviceName]) {
            return self.subChannels[opts.serviceName].request(opts);
        } else {
            throw errors.TopLevelRequestError();
        }
    }

    var req = null;
    if (opts.host || // retries are only between hosts
        opts.streamed // streaming retries not yet implemented
    ) {
        req = self.peers.request(null, opts);
    } else {
        req = new TChannelRequest(self, opts);
    }
    self.requestEvent.emit(self, req);
    return req;
};

TChannel.prototype.quit = // to provide backward compatibility.
TChannel.prototype.close = function close(callback) {
    var self = this;
    assert(!self.destroyed, 'TChannel double close');
    self.destroyed = true;

    var counter = 1;

    if (self.serverSocket) {
        ++counter;
        if (self.serverSocket.address()) {
            closeServerSocket();
        } else {
            self.serverSocket.once('listening', closeServerSocket);
        }
    }

    if (self.serverConnections) {
        var incomingConns = Object.keys(self.serverConnections);
        for (var i = 0; i < incomingConns.length; i++) {
            ++counter;
            var incomingConn = self.serverConnections[incomingConns[i]];
            incomingConn.close(onClose);
        }
    }

    if (self.subChannels) {
        var serviceNames = Object.keys(self.subChannels);
        serviceNames.forEach(function each(serviceName) {
            var svcchan = self.subChannels[serviceName];
            if (!svcchan.destroyed) {
                counter++;
                svcchan.close(onClose);
            }
        });
    }

    self.peers.close(onClose);

    function closeServerSocket() {
        self.serverSocket.once('close', onClose);
        self.serverSocket.close();
    }

    function onClose() {
        if (--counter <= 0) {
            if (counter < 0) {
                self.logger.error('closed more channel sockets than expected', {
                    counter: counter
                });
            }
            if (typeof callback === 'function') {
                callback();
            }
        }
    }
};

TChannel.prototype.emitStat = function emitStat(stat) {
    var self = this;

    var commonTags = self.statTags;
    var commonKeys = Object.keys(self.statTags);

    var localTags = stat.tags;
    for (var i = 0; i < commonKeys.length; i++) {
        localTags[commonKeys[i]] = commonTags[commonKeys[i]];
    }

    self.statEvent.emit(self, stat);

    if (self.topChannel) {
        self.topChannel.statEvent.emit(self, stat);
    }
};

module.exports = TChannel;
<commit_msg>channel: fix stats name typo<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var assert = require('assert');
var globalTimers = {
    setTimeout: require('timers').setTimeout,
    clearTimeout: require('timers').clearTimeout,
    now: Date.now
};
var globalRandom = Math.random;
var net = require('net');
var format = require('util').format;
var extend = require('xtend');

var inherits = require('util').inherits;
var StatEmitter = require('./lib/stat_emitter');

var nullLogger = require('./null-logger.js');
var EndpointHandler = require('./endpoint-handler.js');
var TChannelRequest = require('./request');
var TChannelServiceNameHandler = require('./service-name-handler');
var errors = require('./errors');

var TChannelConnection = require('./connection');
var TChannelPeers = require('./peers');
var TChannelServices = require('./services');

var TracingAgent = require('./trace/agent');

var CONN_STALE_PERIOD = 1500;

// TODO restore spying
// var Spy = require('./v2/spy');
// var dumpEnabled = /\btchannel_dump\b/.test(process.env.NODE_DEBUG || '');

function TChannel(options) {
    if (!(this instanceof TChannel)) {
        return new TChannel(options);
    }

    var self = this;
    StatEmitter.call(self);
    self.errorEvent = self.defineEvent('error');
    self.listeningEvent = self.defineEvent('listening');
    self.connectionEvent = self.defineEvent('connection');
    self.requestEvent = self.defineEvent('request');
    self.outboundCallsSentStat = self.defineCounter('outbound.calls.sent');
    self.outboundCallsSystemErrorsStat = self.defineCounter('outbound.calls.system-errors');
    self.outboundCallsOperationalErrorsStat = self.defineCounter('outbound.calls.operational-errors');
    self.outboundCallsSuccessStat = self.defineCounter('outbound.calls.success');
    self.outboundCallsAppErrorsStat = self.defineCounter('outbound.calls.app-errors');
    self.outboundCallsRetriesStat = self.defineCounter('outbound.calls.retries');
    self.outboundCallsLatencyStat = self.defineTiming('outbound.calls.latency');
    self.outboundCallsPerAttemptLatencyStat = self.defineTiming('outbound.calls.per-attempt-latency');

    self.options = extend({
        timeoutCheckInterval: 100,
        timeoutFuzz: 100,
        connectionStalePeriod: CONN_STALE_PERIOD,

        // TODO: maybe we should always add pid to user-supplied?
        processName: format('%s[%s]', process.title, process.pid)
    }, options);

    // must have 'app', 'host', 'cluster', 'version'
    self.statTags = self.options.statTags || {};

    self.requestDefaults = extend({
        timeout: TChannelRequest.defaultTimeout
    }, self.options.requestDefaults);

    self.logger = self.options.logger || nullLogger;
    self.random = self.options.random || globalRandom;
    self.timers = self.options.timers || globalTimers;
    self.initTimeout = self.options.initTimeout || 2000;

    // Filled in by the listen call:
    self.host = null;
    self.requestedPort = null;

    // Filled in by listening event:
    self.hostPort = null;

    // name of the service running over this channel
    self.serviceName = '';
    if (self.options.serviceName) {
        self.serviceName = self.options.serviceName;
        delete self.options.serviceName;
    }

    // populated by makeSubChannel
    self.topChannel = null;
    self.subChannels = self.serviceName ? null : {};

    // how to handle incoming requests
    if (!self.options.handler) {
        if (!self.serviceName) {
            self.handler = TChannelServiceNameHandler(self);
        } else {
            self.handler = EndpointHandler(self.serviceName);
        }
    } else {
        self.handler = self.options.handler;
        delete self.options.handler;
    }

    // populated by:
    // - manually api (.peers.add etc)
    // - incoming connections on any listening socket
    self.peers = TChannelPeers(self, self.options);

    // For tracking the number of pending requests to any service
    self.services = new TChannelServices();
    if (self.options.maxPending !== undefined) {
        self.services.maxPending = self.options.maxPending;
    }
    if (self.options.maxPendingForService !== undefined) {
        self.services.maxPendingForService = self.options.maxPendingForService;
    }

    // TChannel advances through the following states.
    self.listened = false;
    self.listening = false;
    self.destroyed = false;

    if (self.options.trace) {
        self.tracer = new TracingAgent({
            logger: self.logger,
            forceTrace: self.options.forceTrace,
            serviceName: self.options.tracingServiceName,
            reporter: self.options.traceReporter
        });

        if (self.requestDefaults.trace !== false) {
            self.requestDefaults.trace = true;
        }
    }

    // lazily created by .getServer (usually from .listen)
    self.serverSocket = null;
    self.serverConnections = null;
}
inherits(TChannel, StatEmitter);

TChannel.prototype.getServer = function getServer() {
    var self = this;
    if (self.serverSocket) {
        return self.serverSocket;
    }

    self.serverConnections = Object.create(null);
    self.serverSocket = net.createServer(onServerSocketConnection);
    self.serverSocket.on('listening', onServerSocketListening);
    self.serverSocket.on('error', onServerSocketError);

    return self.serverSocket;

    function onServerSocketConnection(sock) {
        self.onServerSocketConnection(sock);
    }

    function onServerSocketListening() {
        self.onServerSocketListening();
    }

    function onServerSocketError(err) {
        self.onServerSocketError(err);
    }
};

TChannel.prototype.onServerSocketConnection = function onServerSocketConnection(sock) {
    var self = this;

    if (self.destroyed) {
        self.logger.error('got incoming socket whilst destroyed', {
            remoteAddr: sock.remoteAddr,
            remotePort: sock.remotePort,
            hostPort: self.hostPort
        });
        return;
    }

    var remoteAddr = sock.remoteAddress + ':' + sock.remotePort;
    var conn = new TChannelConnection(self, sock, 'in', remoteAddr);

    conn.spanEvent.on(function handleSpanFromConn(span) {
        self.tracer.report(span);
    });

    if (self.serverConnections[remoteAddr]) {
        var oldConn = self.serverConnections[remoteAddr];
        oldConn.resetAll(errors.SocketClosedError({
            reason: 'duplicate remoteAddr incoming conn'
        }));
        delete self.serverConnections[remoteAddr];
    }

    sock.on('close', onSocketClose);

    self.serverConnections[remoteAddr] = conn;
    self.connectionEvent.emit(self, conn);

    function onSocketClose() {
        delete self.serverConnections[remoteAddr];
    }
};

TChannel.prototype.onServerSocketListening = function onServerSocketListening() {
    var self = this;

    if (self.destroyed) {
        self.logger.error('got serverSocket listen whilst destroyed', {
            requestHostPort: self.host + ':' + self.requestedPort,
            hostPort: self.host + ':' + self.serverSocket.address().port
        });
        return;
    }

    var address = self.serverSocket.address();
    self.hostPort = self.host + ':' + address.port;
    self.listening = true;

    if (self.subChannels) {
        Object.keys(self.subChannels).forEach(function each(serviceName) {
            var chan = self.subChannels[serviceName];
            if (!chan.hostPort) {
                chan.hostPort = self.hostPort;
            }
        });
    }

    self.listeningEvent.emit(self);
};

TChannel.prototype.onServerSocketError = function onServerSocketError(err) {
    var self = this;

    if (err.code === 'EADDRINUSE') {
        err = errors.TChannelListenError(err, {
            requestedPort: self.requestedPort,
            host: self.host
        });
    }
    self.logger.error('server socket error', {
        err: err,
        requestedPort: self.requestedPort,
        host: self.host,
        hostPort: self.hostPort || null
    });
    self.errorEvent.emit(self, err);
};

TChannel.prototype.makeSubChannel = function makeSubChannel(options) {
    var self = this;
    if (!options) options = {};
    assert(!self.serviceName, 'arbitrary-depth sub channels are unsupported');
    assert(options.serviceName, 'must specify serviceName');
    assert(!self.subChannels[options.serviceName], 'duplicate sub channel creation');
    var opts = extend(self.options);
    var keys = Object.keys(options);
    for (var i = 0; i < keys.length; i++) {
        switch (keys[i]) {
            case 'peers':
                break;
            default:
                opts[keys[i]] = options[keys[i]];
        }
    }
    var chan = TChannel(opts);
    chan.topChannel = self;
    if (options.peers) {
        for (i = 0; i < options.peers.length; i++) {
            if (typeof options.peers[i] === 'string') {
                chan.peers.addPeer(self.peers.add(options.peers[i]));
            } else {
                chan.peers.addPeer(options.peers[i]);
            }
        }
    }
    self.subChannels[chan.serviceName] = chan;

    if (self.hostPort) {
        chan.hostPort = self.hostPort;
    }

    return chan;
};

TChannel.prototype.listen = function listen(port, host, callback) {
    // Note:
    // - 0 is a valid port number, indicating that the system must assign an
    //   available ephemeral port
    // - 127.0.0.1 is a valid host, primarily for testing
    var self = this;
    assert(!self.listened, 'TChannel can only listen once');
    assert(typeof host === 'string', 'TChannel requires host argument');
    assert(typeof port === 'number', 'TChannel must listen with numeric port');
    assert(host !== '0.0.0.0', 'TChannel must listen with externally visible host');
    self.listened = true;
    self.requestedPort = port;
    self.host = host;
    self.getServer().listen(port, host, callback);
};

TChannel.prototype.register = function register(name, options, handler) {
    var self = this;

    var handlerType = self.handler && self.handler.type;

    switch (handlerType) {
        case 'tchannel.endpoint-handler':
            self.handler.register(name, options, handler);
            break;

        case 'tchannel.service-name-handler':
            throw errors.TopLevelRegisterError();

        default:
            throw errors.InvalidHandlerForRegister({
                handlerType: handlerType,
                handler: self.handler
            });
    }
};

TChannel.prototype.address = function address() {
    var self = this;
    if (self.serverSocket) {
        return self.serverSocket.address() || null;
    } else if (self.topChannel) {
        return self.topChannel.address();
    } else {
        return null;
    }
};

TChannel.prototype.requestOptions = function requestOptions(options) {
    var self = this;
    var prop;
    var opts = {};
    // jshint forin:false
    for (prop in self.requestDefaults) {
        opts[prop] = self.requestDefaults[prop];
    }
    if (options) {
        for (prop in options) {
            opts[prop] = options[prop];
        }
    }
    // jshint forin:true
    return opts;
};

TChannel.prototype.waitForIdentified =
function waitForIdentified(options, callback) {
    var self = this;

    self.peers.waitForIdentified(options, callback);
};

TChannel.prototype.request = function channelRequest(options) {
    var self = this;
    assert(!self.destroyed, 'cannot request() to destroyed tchannel');
    var opts = self.requestOptions(options);

    if (!self.serviceName && !opts.host) {
        if (opts.serviceName &&
            self.subChannels &&
            self.subChannels[opts.serviceName]) {
            return self.subChannels[opts.serviceName].request(opts);
        } else {
            throw errors.TopLevelRequestError();
        }
    }

    var req = null;
    if (opts.host || // retries are only between hosts
        opts.streamed // streaming retries not yet implemented
    ) {
        req = self.peers.request(null, opts);
    } else {
        req = new TChannelRequest(self, opts);
    }
    self.requestEvent.emit(self, req);
    return req;
};

TChannel.prototype.quit = // to provide backward compatibility.
TChannel.prototype.close = function close(callback) {
    var self = this;
    assert(!self.destroyed, 'TChannel double close');
    self.destroyed = true;

    var counter = 1;

    if (self.serverSocket) {
        ++counter;
        if (self.serverSocket.address()) {
            closeServerSocket();
        } else {
            self.serverSocket.once('listening', closeServerSocket);
        }
    }

    if (self.serverConnections) {
        var incomingConns = Object.keys(self.serverConnections);
        for (var i = 0; i < incomingConns.length; i++) {
            ++counter;
            var incomingConn = self.serverConnections[incomingConns[i]];
            incomingConn.close(onClose);
        }
    }

    if (self.subChannels) {
        var serviceNames = Object.keys(self.subChannels);
        serviceNames.forEach(function each(serviceName) {
            var svcchan = self.subChannels[serviceName];
            if (!svcchan.destroyed) {
                counter++;
                svcchan.close(onClose);
            }
        });
    }

    self.peers.close(onClose);

    function closeServerSocket() {
        self.serverSocket.once('close', onClose);
        self.serverSocket.close();
    }

    function onClose() {
        if (--counter <= 0) {
            if (counter < 0) {
                self.logger.error('closed more channel sockets than expected', {
                    counter: counter
                });
            }
            if (typeof callback === 'function') {
                callback();
            }
        }
    }
};

TChannel.prototype.emitStat = function emitStat(stat) {
    var self = this;

    var commonTags = self.statTags;
    var commonKeys = Object.keys(self.statTags);

    var localTags = stat.tags;
    for (var i = 0; i < commonKeys.length; i++) {
        localTags[commonKeys[i]] = commonTags[commonKeys[i]];
    }

    self.statEvent.emit(self, stat);

    if (self.topChannel) {
        self.topChannel.statEvent.emit(self, stat);
    }
};

module.exports = TChannel;
<|endoftext|>


<commit_before>/* eslint-disable no-var */
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var StaticSitePlugin = require('react-static-webpack-plugin');
var webpackBaseConfig = require('./webpack.config.base');

module.exports = Object.assign(webpackBaseConfig, {
  devtool: 'source-map',

  entry: {
    app: ['./client/index.js'],
  },

  output: {
    path: path.join(__dirname, 'public'),
    filename: '[name].js',
    libraryTarget: 'umd',
    publicPath: '/',
  },

  plugins: [
    new ExtractTextPlugin({ filename: '[name].css', allChunks: true }),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production'),
      },
    }),
    new webpack.optimize.UglifyJsPlugin({
      screw_ie8: true,
      compressor: { warnings: false },
    }),
    new StaticSitePlugin({
      src: 'app',
      stylesheet: '/app.css',
      favicon: '/favicon.ico',
      template: path.join(__dirname, 'index.html.js'),
    }),
  ],
});
<commit_msg>Update prod webpack<commit_after>/* eslint-disable no-var */
var path = require('path');
var webpack = require('webpack');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var StaticSitePlugin = require('react-static-webpack-plugin');
var webpackBaseConfig = require('./webpack.config.base');

module.exports = Object.assign(webpackBaseConfig, {
  devtool: 'source-map',

  entry: {
    app: ['./client/index.js'],
  },

  output: {
    path: path.join(__dirname, 'public'),
    filename: '[name].js',
    libraryTarget: 'umd',
    publicPath: '/',
  },

  plugins: [
    new ExtractTextPlugin({ filename: '[name].css', allChunks: true }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('production'),
      },
    }),
    new webpack.optimize.UglifyJsPlugin({
      screw_ie8: true,
      compressor: { warnings: false },
    }),
    new StaticSitePlugin({
      src: 'app',
      routes: './client/index.js',
      stylesheet: '/app.css',
      favicon: '/favicon.ico',
      template: path.join(__dirname, 'index.html.js'),
    }),
  ],
});
<|endoftext|>


<commit_before>/*
 * Copyright © 2013 VillageReach.  All Rights Reserved.  This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
 *
 * If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

function InitiateRnrController($scope, $location, $rootScope, Requisition, PeriodsForFacilityAndProgram, UserFacilityList, CreateRequisitionProgramList, UserSupervisedFacilitiesForProgram, FacilityProgramRights) {

  var DEFAULT_FACILITY_MESSAGE = '--choose facility--';
  var DEFAULT_PROGRAM_MESSAGE = '--choose program--';
  var PREVIOUS_RNR_PENDING_STATUS = "Previous R&R pending";
  var RNR_NOT_YET_STARTED_STATUS = "Not yet started";

  var resetRnrData = function () {
    $scope.periodGridData = [];
    $scope.selectedProgram = null;
    $scope.selectedFacilityId = null;
    $scope.selectedPeriod = null;
    $scope.myFacility = null;
    $scope.programs = null;
    $scope.facilities = null;
    $scope.error = null;
  };

  $scope.loadFacilityData = function (selectedType) {
    resetRnrData();

    if (selectedType == 0) { //My facility
      UserFacilityList.get({}, function (data) {
        $scope.facilities = data.facilityList;
        $scope.myFacility = data.facilityList[0];
        if ($scope.myFacility) {
          $scope.facilityDisplayName = $scope.myFacility.code + '-' + $scope.myFacility.name;
          $scope.selectedFacilityId = $scope.myFacility.id;

          CreateRequisitionProgramList.get({facilityId:$scope.selectedFacilityId}, function (data) {
            $scope.programs = data.programList;
          }, {});
        } else {
          $scope.facilityDisplayName = "--none assigned--";
          $scope.programs = null;
          $scope.selectedProgram = null;
        }
      }, {});
    } else if (selectedType == 1) { // Supervised facility
      CreateRequisitionProgramList.get({}, function (data) {
        $scope.programs = data.programList;
      }, {});
    }
  };

  $scope.loadFacilitiesForProgram = function () {
    if ($scope.selectedProgram) {
      UserSupervisedFacilitiesForProgram.get({programId:$scope.selectedProgram.id}, function (data) {
        $scope.facilities = data.facilities;
        $scope.selectedFacilityId = null;
        $scope.error = null;
      }, {});
    } else {
      $scope.facilities = null;
      $scope.selectedFacilityId = null;
    }
  };

  var getPeriodSpecificButton = function (activeForRnr) {
    return '<input type="button" ng-click="initRnr()" value="Proceed" class="btn btn-primary btn-small grid-btn" ng-show="' + activeForRnr + '"/>';
  };

  var optionMessage = function (entity, defaultMessage) {
    return entity == null || entity.length == 0 ? "--none assigned--" : defaultMessage;
  };

  var resetValuesForFirstPeriod = function (periodGridData) {
    var firstPeriodWithRnrStatus = periodGridData[0];
    firstPeriodWithRnrStatus.activeForRnr = true;
    if (!firstPeriodWithRnrStatus.rnrId) {
      firstPeriodWithRnrStatus.rnrStatus = RNR_NOT_YET_STARTED_STATUS;
    }
  };

  var createPeriodWithRnrStatus = function (periods, rnr) {
    $scope.periodGridData = [];
    $scope.selectedPeriod = null;

    var periodWithRnrStatus;
    if (periods == null || periods.length == 0) {
      periodWithRnrStatus = {name:"No period(s) available"};
      $scope.selectedPeriod = null;
      $scope.periodGridData.push(periodWithRnrStatus);
      return;
    }

    $scope.selectedPeriod = periods[0];
    periods.forEach(function (period) {
      periodWithRnrStatus = angular.copy(period);
      periodWithRnrStatus.rnrStatus = PREVIOUS_RNR_PENDING_STATUS;
      if (rnr != null && periodWithRnrStatus.id == rnr.period.id) {
        periodWithRnrStatus.rnrId = rnr.id;
        periodWithRnrStatus.rnrStatus = rnr.status;
      }
      $scope.periodGridData.push(periodWithRnrStatus);
    });

    resetValuesForFirstPeriod($scope.periodGridData);
  };

  $scope.periodGridOptions = { data:'periodGridData',
    canSelectRows:false,
    displayFooter:false,
    displaySelectionCheckbox:false,
    enableColumnResize:true,
    enableColumnReordering:true,
    enableSorting:false,
    showColumnMenu:false,
    showFilter:false,
    columnDefs:[
      {field:'name', displayName:'Period(s)'},
      {field:'startDate', displayName:'Start Date', cellFilter:"date:'dd/MM/yyyy'" },
      {field:'endDate', displayName:'End Date', cellFilter:"date:'dd/MM/yyyy'" },
      {field:'rnrStatus', displayName:'R&R Status' },
      {field:'', displayName:'', cellTemplate:getPeriodSpecificButton('row.entity.activeForRnr')}
    ]
  };

  $scope.facilityOptionMessage = function () {
    return optionMessage($scope.facilities, DEFAULT_FACILITY_MESSAGE);
  };

  $scope.programOptionMessage = function () {
    return optionMessage($scope.programs, DEFAULT_PROGRAM_MESSAGE);
  };

  $scope.loadPeriods = function () {
    $scope.selectedPeriod = null;
    $scope.periodGridData = [];
    if ($scope.selectedProgram && $scope.selectedFacilityId) {
      PeriodsForFacilityAndProgram.get({facilityId:$scope.selectedFacilityId, programId:$scope.selectedProgram.id},
        function (data) {
          $scope.error = "";
          createPeriodWithRnrStatus(data.periods, data.rnr);
        },
        function (data) {
          $scope.error = data.data.error;
        });
    } else {
      $scope.error = "";
    }
  };

  $scope.initRnr = function () {
    if (!($scope.selectedProgram && $scope.selectedPeriod)) {
      $scope.error = "Please select Facility, Program and Period to proceed";
      return;
    }

    $scope.error = "";
    $scope.sourceUrl = $location.$$url;
    var createRnrPath;

    FacilityProgramRights.get({facilityId:$scope.selectedFacilityId, programId:$scope.selectedProgram.id}, function (data) {

      var rights = data.rights;

      var hasPermission = function (permission) {
        return _.find(rights, function (right) {
          return right.right == permission
        });
      };

      Requisition.get({facilityId:$scope.selectedFacilityId, programId:$scope.selectedProgram.id, periodId:$scope.selectedPeriod.id}, {},
        function (data) {
          if ((data.rnr == null || data.rnr == undefined) && !hasPermission('CREATE_REQUISITION')) {
            $scope.error = "Requisition not initiated yet";
            return;
          }

          if (data.rnr) {
            if (data.rnr.status != 'SUBMITTED' && !hasPermission('CREATE_REQUISITION')) {
              $scope.error = "Requisition not submitted yet";
              return;
            }
            $scope.$parent.rnr = data.rnr;
            createRnrPath = '/create-rnr/' + $scope.$parent.rnr.id + '/' + $scope.selectedFacilityId + '/' + $scope.selectedProgram.id + "?supplyType=full-supply&page=1";
            $location.url(createRnrPath);
          }
          else {
            Requisition.save({facilityId:$scope.selectedFacilityId, programId:$scope.selectedProgram.id, periodId:$scope.selectedPeriod.id}, {}, function (data) {
              $scope.$parent.rnr = data.rnr;
              createRnrPath = '/create-rnr/' + $scope.$parent.rnr.id + '/' + $scope.selectedFacilityId + '/' + $scope.selectedProgram.id + "?supplyType=full-supply&page=1";
              $location.url(createRnrPath);
            }, function (data) {
              $scope.error = data.data.error ? data.data.error : "Requisition does not exist. Please initiate.";
            })
          }
        }, {});

    }, {});
  };
}

InitiateRnrController.resolve = {
  preAuthorize:function (AuthorizationService) {
    AuthorizationService.preAuthorize('CREATE_REQUISITION', 'AUTHORIZE_REQUISITION');
  }
};
<commit_msg>#605 | +Anshul, Jaideep | Moving focus to Error message if appears<commit_after>/*
 * Copyright © 2013 VillageReach.  All Rights Reserved.  This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
 *
 * If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

function InitiateRnrController($scope, $location, $rootScope, Requisition, PeriodsForFacilityAndProgram, UserFacilityList, CreateRequisitionProgramList, UserSupervisedFacilitiesForProgram, FacilityProgramRights) {

  var DEFAULT_FACILITY_MESSAGE = '--choose facility--';
  var DEFAULT_PROGRAM_MESSAGE = '--choose program--';
  var PREVIOUS_RNR_PENDING_STATUS = "Previous R&R pending";
  var RNR_NOT_YET_STARTED_STATUS = "Not yet started";

  var resetRnrData = function () {
    $scope.periodGridData = [];
    $scope.selectedProgram = null;
    $scope.selectedFacilityId = null;
    $scope.selectedPeriod = null;
    $scope.myFacility = null;
    $scope.programs = null;
    $scope.facilities = null;
    $scope.error = null;
  };

  $scope.loadFacilityData = function (selectedType) {
    resetRnrData();

    if (selectedType == 0) { //My facility
      UserFacilityList.get({}, function (data) {
        $scope.facilities = data.facilityList;
        $scope.myFacility = data.facilityList[0];
        if ($scope.myFacility) {
          $scope.facilityDisplayName = $scope.myFacility.code + '-' + $scope.myFacility.name;
          $scope.selectedFacilityId = $scope.myFacility.id;

          CreateRequisitionProgramList.get({facilityId:$scope.selectedFacilityId}, function (data) {
            $scope.programs = data.programList;
          }, {});
        } else {
          $scope.facilityDisplayName = "--none assigned--";
          $scope.programs = null;
          $scope.selectedProgram = null;
        }
      }, {});
    } else if (selectedType == 1) { // Supervised facility
      CreateRequisitionProgramList.get({}, function (data) {
        $scope.programs = data.programList;
      }, {});
    }
  };

  $scope.loadFacilitiesForProgram = function () {
    if ($scope.selectedProgram) {
      UserSupervisedFacilitiesForProgram.get({programId:$scope.selectedProgram.id}, function (data) {
        $scope.facilities = data.facilities;
        $scope.selectedFacilityId = null;
        $scope.error = null;
      }, {});
    } else {
      $scope.facilities = null;
      $scope.selectedFacilityId = null;
    }
  };

  var getPeriodSpecificButton = function (activeForRnr) {
    return '<input type="button" ng-click="initRnr()" value="Proceed" class="btn btn-primary btn-small grid-btn" ng-show="' + activeForRnr + '"/>';
  };

  var optionMessage = function (entity, defaultMessage) {
    return entity == null || entity.length == 0 ? "--none assigned--" : defaultMessage;
  };

  var resetValuesForFirstPeriod = function (periodGridData) {
    var firstPeriodWithRnrStatus = periodGridData[0];
    firstPeriodWithRnrStatus.activeForRnr = true;
    if (!firstPeriodWithRnrStatus.rnrId) {
      firstPeriodWithRnrStatus.rnrStatus = RNR_NOT_YET_STARTED_STATUS;
    }
  };

  var createPeriodWithRnrStatus = function (periods, rnr) {
    $scope.periodGridData = [];
    $scope.selectedPeriod = null;

    var periodWithRnrStatus;
    if (periods == null || periods.length == 0) {
      periodWithRnrStatus = {name:"No period(s) available"};
      $scope.selectedPeriod = null;
      $scope.periodGridData.push(periodWithRnrStatus);
      return;
    }

    $scope.selectedPeriod = periods[0];
    periods.forEach(function (period) {
      periodWithRnrStatus = angular.copy(period);
      periodWithRnrStatus.rnrStatus = PREVIOUS_RNR_PENDING_STATUS;
      if (rnr != null && periodWithRnrStatus.id == rnr.period.id) {
        periodWithRnrStatus.rnrId = rnr.id;
        periodWithRnrStatus.rnrStatus = rnr.status;
      }
      $scope.periodGridData.push(periodWithRnrStatus);
    });

    resetValuesForFirstPeriod($scope.periodGridData);
  };

  $scope.periodGridOptions = { data:'periodGridData',
    canSelectRows:false,
    displayFooter:false,
    displaySelectionCheckbox:false,
    enableColumnResize:true,
    enableColumnReordering:true,
    enableSorting:false,
    showColumnMenu:false,
    showFilter:false,
    columnDefs:[
      {field:'name', displayName:'Period(s)'},
      {field:'startDate', displayName:'Start Date', cellFilter:"date:'dd/MM/yyyy'" },
      {field:'endDate', displayName:'End Date', cellFilter:"date:'dd/MM/yyyy'" },
      {field:'rnrStatus', displayName:'R&R Status' },
      {field:'', displayName:'', cellTemplate:getPeriodSpecificButton('row.entity.activeForRnr')}
    ]
  };

  $scope.$watch("error", function(errorMsg, oldErrorMsg) {
    setTimeout(function() {
      if(errorMsg) {
        document.getElementById('saveSuccessMsgDiv').scrollIntoView();
      }
    });
  });

  $scope.facilityOptionMessage = function () {
    return optionMessage($scope.facilities, DEFAULT_FACILITY_MESSAGE);
  };

  $scope.programOptionMessage = function () {
    return optionMessage($scope.programs, DEFAULT_PROGRAM_MESSAGE);
  };

  $scope.loadPeriods = function () {
    $scope.selectedPeriod = null;
    $scope.periodGridData = [];
    if ($scope.selectedProgram && $scope.selectedFacilityId) {
      PeriodsForFacilityAndProgram.get({facilityId:$scope.selectedFacilityId, programId:$scope.selectedProgram.id},
        function (data) {
          $scope.error = "";
          createPeriodWithRnrStatus(data.periods, data.rnr);
        },
        function (data) {
          $scope.error = data.data.error;
        });
    } else {
      $scope.error = "";
    }
  };

  $scope.initRnr = function () {
    if (!($scope.selectedProgram && $scope.selectedPeriod)) {
      $scope.error = "Please select Facility, Program and Period to proceed";
      return;
    }

    $scope.error = "";
    $scope.sourceUrl = $location.$$url;
    var createRnrPath;

    FacilityProgramRights.get({facilityId:$scope.selectedFacilityId, programId:$scope.selectedProgram.id}, function (data) {

      var rights = data.rights;

      var hasPermission = function (permission) {
        return _.find(rights, function (right) {
          return right.right == permission
        });
      };

      Requisition.get({facilityId:$scope.selectedFacilityId, programId:$scope.selectedProgram.id, periodId:$scope.selectedPeriod.id}, {},
        function (data) {
          if ((data.rnr == null || data.rnr == undefined) && !hasPermission('CREATE_REQUISITION')) {
            $scope.error = "Requisition not initiated yet";
            return;
          }

          if (data.rnr) {
            if (data.rnr.status != 'SUBMITTED' && !hasPermission('CREATE_REQUISITION')) {
              $scope.error = "Requisition not submitted yet";
              return;
            }
            $scope.$parent.rnr = data.rnr;
            createRnrPath = '/create-rnr/' + $scope.$parent.rnr.id + '/' + $scope.selectedFacilityId + '/' + $scope.selectedProgram.id + "?supplyType=full-supply&page=1";
            $location.url(createRnrPath);
          }
          else {
            Requisition.save({facilityId:$scope.selectedFacilityId, programId:$scope.selectedProgram.id, periodId:$scope.selectedPeriod.id}, {}, function (data) {
              $scope.$parent.rnr = data.rnr;
              createRnrPath = '/create-rnr/' + $scope.$parent.rnr.id + '/' + $scope.selectedFacilityId + '/' + $scope.selectedProgram.id + "?supplyType=full-supply&page=1";
              $location.url(createRnrPath);
            }, function (data) {
              $scope.error = data.data.error ? data.data.error : "Requisition does not exist. Please initiate.";
            })
          }
        }, {});

    }, {});
  };
}

InitiateRnrController.resolve = {
  preAuthorize:function (AuthorizationService) {
    AuthorizationService.preAuthorize('CREATE_REQUISITION', 'AUTHORIZE_REQUISITION');
  }
};
<|endoftext|>


<commit_before><commit_msg>add polyfill Array.forEach<commit_after><|endoftext|>


<commit_before>"use strict"

/**
 * This defines the entire context applying to the current node.
 */
class Context {
    /**
     * Builds the object
     */
    constructor() {
        this.ns = {}
    }
    /**
     * Adds a name to the namespace list.
     * @param {string} name eg. "$foo"
     * @param {?Node} assignment_node
     */
    addName(name, assignment_node) {
        if(!this.ns[name]) {
            this.ns[name] = []
        }
        this.ns[name].push(assignment_node)
    }
    /**
     * If the name is in the namespace, returns it.
     * @param {string} name eg "$bar"
     * @returns {?string}
     */
    findName(name) {
        return Object.keys(this.ns).find(n => n == name)
    }
}

class Lint {
    constructor(tree, filename = null, namespace = []) {
        Object.assign(
            this,
            {
                filename: filename,
                namespace: namespace,
                tree: tree,
            }
        );
    }
    check() {
        return Lint.ShadowTree.Node.typed(this.tree).check(new Context());
    }
    static check(tree, filename = null) {
        var l = new Lint(tree, filename);
        return l.check();
    }
};

Lint.PHPStrictError = class extends Error {
};
Lint.ShadowTree = {
    Node: class {
        constructor(node) {
            Object.assign(
                this,
                {
                    _cache: {},
                    node: node
                }
            );
        }
        /** @type {string} */
        get kind() {
            return this.node.kind;
        }
        /** @type {?Location} */
        get loc() {
            return this.node.loc;
        }
        assertHasName(context, name) {
            if(!context.findName(name)) {
                throw new Lint.PHPStrictError(`Name ${name} is not defined in this namespace`);
            }
        }
        cacheNode(name) {
            return this.cacheProperty(
                name,
                subnode => subnode ?
                    Lint.ShadowTree.Node.typed(subnode) :
                    subnode
            );
        }
        cacheNodeArray(name) {
            return this.cacheProperty(
                name,
                subnodes => subnodes ? subnodes.map(
                    subnode => Lint.ShadowTree.Node.typed(subnode)
                ) : subnodes
            );
        }
        cacheProperty(name, f) {
            if(!this._cache.hasOwnProperty(name)) {
                this._cache[name] = f(this.node[name]);
            }
            return this._cache[name];
        }
        check(context) {
            return true;
        }
        static typed(node) {
            var c = Lint.ShadowTree[node.constructor.name];
            if(!c) {
                throw new Error(`No handler for ${node.constructor.name}`);
            }
            return new c(node);
        }
    },
};
Object.assign(
    Lint.ShadowTree,
    {
        Expression: class extends Lint.ShadowTree.Node {
        },
        Identifier: class extends Lint.ShadowTree.Node {
            /** @type {string} */
            get name() {
                return this.node.name;
            }
            /** @type {string} One of UNQUALIFIED_NAME,
              *     QUALIFIED_NAME, FULL_QUALIFIED_NAME or RELATIVE_NAME */
            get resolution() {
                return this.node.resolution;
            }
        },
        Statement: class extends Lint.ShadowTree.Node {
        },
        TraitUse: class extends Lint.ShadowTree.Node {
            /** @type {Identifier[]} */
            get adaptations() {
                return this.cacheNodeArray("adaptations");
            }
            /** @type {?Node[]} */
            get traits() {
                if(this.node.traits) {
                    return this.cacheNodeArray("traits");
                } else {
                    return null;
                }
            }
        },
    }
);
Object.assign(
    Lint.ShadowTree,
    {
        Assign: class extends Lint.ShadowTree.Statement {
            /** @type {string} */
            get operator() {
                return this.node.operator;
            }
            /** @type {Expression} */
            get left() {
                return this.cacheNode("left")
            }
            /** @type {Expression} */
            get right() {
                return this.cacheNode("right")
            }
            check(context) {
                context.addName('$' + this.left.name, this.node)
                this.right.check(context)
                return super.check(context)
            }
        },
        Block: class extends Lint.ShadowTree.Statement {
            /** @type {Node[]} */
            get children() {
                return this.cacheNodeArray("children");
            }
            check(context) {
                this.children.forEach(node => node.check(context));
                return super.check(context);
            }
        },
        Closure: class extends Lint.ShadowTree.Statement {
            /** @type {Parameter[]} */
            get arguments() {
                return this.cacheNodeArray("arguments");
            }
            /** @type {?Block} */
            get body() {
                return this.cacheNode("body");
            }
            /** @type {bool} */
            get byref() {
                return this.node.byref;
            }
            /** @type {bool} */
            get nullable() {
                return this.node.nullable;
            }
            /** @type {object[]} */
            get type() {
                return this.node.type;
            }
            check(context) {
                this.type.forEach(t => this.assertHasName(context, t[1]));
                var inner_context = new Context();
                this.arguments.forEach(node => inner_context.addName('$' + node.name, node));
                this.type.forEach(t => inner_context.addName(t[1], null));
                if(this.body) this.body.check(inner_context);
                return super.check(context);
            }
        },
        Literal: class extends Lint.ShadowTree.Expression {
            /** @type {Node|string|number|boolean|null} */
            get value() {
                return this.node.value
            }
        },
        Sys: class extends Lint.ShadowTree.Statement {
            /** @type {Node[]} */
            get arguments() {
                return this.cacheNodeArray("arguments");
            }
        },
        Variable: class extends Lint.ShadowTree.Expression {
            /** @type {bool} */
            get byref() {
                return this.node.byref;
            }
            /** @type {string|Node} */
            get name() {
                return this.cacheProperty(
                    "name",
                    node => {
                        if(typeof node == "object") {
                            return Lint.ShadowTree.Node.typed(child);
                        } else {
                            return node;
                        }
                    }
                );
            }
            check(context) {
                this.assertHasName(context, '$' + this.name);
                return super.check(context);
            }
        },
    }
);
Object.assign(
    Lint.ShadowTree,
    {
        Echo: class extends Lint.ShadowTree.Sys {
            check(context) {
                this.arguments.forEach(child => child.check(context));
                return super.check(context);
            }
        },
        Number: class extends Lint.ShadowTree.Literal {
        },
        Program: class extends Lint.ShadowTree.Block {
            /** @type {Error[]} */
            get errors() {
                return this.node.errors
            }
            check(context) {
                var inner_context = new Context();
                this.children.forEach(child => child.check(inner_context));
                return super.check(context);
            }
        },
        String: class extends Lint.ShadowTree.Literal {
            /** @type {string} */
            get label() {
                return this.node.label
            }
        },
    }
);
module.exports = Lint;
<commit_msg>Add some doc<commit_after>"use strict"

/**
 * This defines the entire context applying to the current node.
 */
class Context {
    /**
     * Builds the object
     */
    constructor() {
        this.ns = {}
    }
    /**
     * Adds a name to the namespace list.
     * @param {string} name eg. "$foo"
     * @param {?Node} assignment_node
     */
    addName(name, assignment_node) {
        if(!this.ns[name]) {
            this.ns[name] = []
        }
        this.ns[name].push(assignment_node)
    }
    /**
     * If the name is in the namespace, returns it.
     * @param {string} name eg "$bar"
     * @returns {?string}
     */
    findName(name) {
        return Object.keys(this.ns).find(n => n == name)
    }
}

class Lint {
    constructor(tree, filename = null, namespace = []) {
        Object.assign(
            this,
            {
                filename: filename,
                namespace: namespace,
                tree: tree,
            }
        );
    }
    check() {
        return Lint.ShadowTree.Node.typed(this.tree).check(new Context());
    }
    static check(tree, filename = null) {
        var l = new Lint(tree, filename);
        return l.check();
    }
};

Lint.PHPStrictError = class extends Error {
};
Lint.ShadowTree = {
    Node: class {
        constructor(node) {
            Object.assign(
                this,
                {
                    _cache: {},
                    node: node
                }
            );
        }
        /** @type {string} */
        get kind() {
            return this.node.kind;
        }
        /** @type {?Location} */
        get loc() {
            return this.node.loc;
        }
        assertHasName(context, name) {
            if(!context.findName(name)) {
                throw new Lint.PHPStrictError(`Name ${name} is not defined in this namespace`);
            }
        }
        cacheNode(name) {
            return this.cacheProperty(
                name,
                subnode => subnode ?
                    Lint.ShadowTree.Node.typed(subnode) :
                    subnode
            );
        }
        cacheNodeArray(name) {
            return this.cacheProperty(
                name,
                subnodes => subnodes ? subnodes.map(
                    subnode => Lint.ShadowTree.Node.typed(subnode)
                ) : subnodes
            );
        }
        cacheProperty(name, f) {
            if(!this._cache.hasOwnProperty(name)) {
                this._cache[name] = f(this.node[name]);
            }
            return this._cache[name];
        }
        /**
         * Checks that syntax seems ok
         * @param {Context} context
         */
        check(context) {
            return true;
        }
        static typed(node) {
            var c = Lint.ShadowTree[node.constructor.name];
            if(!c) {
                throw new Error(`No handler for ${node.constructor.name}`);
            }
            return new c(node);
        }
    },
};
Object.assign(
    Lint.ShadowTree,
    {
        Expression: class extends Lint.ShadowTree.Node {
        },
        Identifier: class extends Lint.ShadowTree.Node {
            /** @type {string} */
            get name() {
                return this.node.name;
            }
            /** @type {string} One of UNQUALIFIED_NAME,
              *     QUALIFIED_NAME, FULL_QUALIFIED_NAME or RELATIVE_NAME */
            get resolution() {
                return this.node.resolution;
            }
        },
        Statement: class extends Lint.ShadowTree.Node {
        },
        TraitUse: class extends Lint.ShadowTree.Node {
            /** @type {Identifier[]} */
            get adaptations() {
                return this.cacheNodeArray("adaptations");
            }
            /** @type {?Node[]} */
            get traits() {
                if(this.node.traits) {
                    return this.cacheNodeArray("traits");
                } else {
                    return null;
                }
            }
        },
    }
);
Object.assign(
    Lint.ShadowTree,
    {
        Assign: class extends Lint.ShadowTree.Statement {
            /** @type {string} */
            get operator() {
                return this.node.operator;
            }
            /** @type {Expression} */
            get left() {
                return this.cacheNode("left")
            }
            /** @type {Expression} */
            get right() {
                return this.cacheNode("right")
            }
            check(context) {
                context.addName('$' + this.left.name, this.node)
                this.right.check(context)
                return super.check(context)
            }
        },
        Block: class extends Lint.ShadowTree.Statement {
            /** @type {Node[]} */
            get children() {
                return this.cacheNodeArray("children");
            }
            check(context) {
                this.children.forEach(node => node.check(context));
                return super.check(context);
            }
        },
        Closure: class extends Lint.ShadowTree.Statement {
            /** @type {Parameter[]} */
            get arguments() {
                return this.cacheNodeArray("arguments");
            }
            /** @type {?Block} */
            get body() {
                return this.cacheNode("body");
            }
            /** @type {bool} */
            get byref() {
                return this.node.byref;
            }
            /** @type {bool} */
            get nullable() {
                return this.node.nullable;
            }
            /** @type {object[]} */
            get type() {
                return this.node.type;
            }
            check(context) {
                this.type.forEach(t => this.assertHasName(context, t[1]));
                var inner_context = new Context();
                this.arguments.forEach(node => inner_context.addName('$' + node.name, node));
                this.type.forEach(t => inner_context.addName(t[1], null));
                if(this.body) this.body.check(inner_context);
                return super.check(context);
            }
        },
        Literal: class extends Lint.ShadowTree.Expression {
            /** @type {Node|string|number|boolean|null} */
            get value() {
                return this.node.value
            }
        },
        Sys: class extends Lint.ShadowTree.Statement {
            /** @type {Node[]} */
            get arguments() {
                return this.cacheNodeArray("arguments");
            }
        },
        Variable: class extends Lint.ShadowTree.Expression {
            /** @type {bool} */
            get byref() {
                return this.node.byref;
            }
            /** @type {string|Node} */
            get name() {
                return this.cacheProperty(
                    "name",
                    node => {
                        if(typeof node == "object") {
                            return Lint.ShadowTree.Node.typed(child);
                        } else {
                            return node;
                        }
                    }
                );
            }
            check(context) {
                this.assertHasName(context, '$' + this.name);
                return super.check(context);
            }
        },
    }
);
Object.assign(
    Lint.ShadowTree,
    {
        Echo: class extends Lint.ShadowTree.Sys {
            check(context) {
                this.arguments.forEach(child => child.check(context));
                return super.check(context);
            }
        },
        Number: class extends Lint.ShadowTree.Literal {
        },
        Program: class extends Lint.ShadowTree.Block {
            /** @type {Error[]} */
            get errors() {
                return this.node.errors
            }
            check(context) {
                var inner_context = new Context();
                this.children.forEach(child => child.check(inner_context));
                return super.check(context);
            }
        },
        String: class extends Lint.ShadowTree.Literal {
            /** @type {string} */
            get label() {
                return this.node.label
            }
        },
    }
);
module.exports = Lint;
<|endoftext|>