<commit_before>/**
 * @file DateTimePicker component
 * @author sunday(sunday.wei@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import _ from 'lodash';

import TextField from '../TextField';
import DayPicker from '../_DayPicker';
import MonthPicker from '../_MonthPicker';
import YearPicker from '../_YearPicker';
import TimeList from '../_TimeList';
import RaisedButton from '../RaisedButton';
import Popup from '../Popup';
import Theme from 'src/Theme';

export default class DateTimePicker extends Component {

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.validValue = true;
        this.state = {
            value: props.value,
            popupVisible: false,
            triggerEl: null,
            year: moment(props.value).format('YYYY'),
            month: moment(props.value).format('MM'),
            day: moment(props.value).format('DD'),
            hour: moment(props.value).format('HH'),
            minute: moment(props.value).format('mm'),
            second: moment(props.value).format('ss'),
            datePickerLevel: 'day'
        };

        this.textFieldChangeHandle = ::this.textFieldChangeHandle;
        this.togglePopup = ::this.togglePopup;
        this.closePopup = ::this.closePopup;
        this.datePickerChangeHandle = ::this.datePickerChangeHandle;
        this.yearPickerChangeHandle = ::this.yearPickerChangeHandle;
        this.monthPickerChangeHandle = ::this.monthPickerChangeHandle;
        this.dayPickerChangeHandle = ::this.dayPickerChangeHandle;
        this.timePickerChangeHandle = ::this.timePickerChangeHandle;
        this.chooseDateAndTimeHandle = ::this.chooseDateAndTimeHandle;
        this.nowHandle = ::this.nowHandle;
        this.selectDateTimeHandle = ::this.selectDateTimeHandle;
    }

    datePickerChangeHandle(selectLevel) {
        this.setState({
            datePickerLevel: selectLevel
        });
    }

    textFieldChangeHandle(text) {
        const {minValue, maxValue, dateFormat} = this.props;
        if (text && text.length) {
            const flag = moment(text, dateFormat, true).isValid();
            if (flag) {
                if (minValue && moment(text).isBefore(minValue) || maxValue && moment(text).isAfter(maxValue)) {

                } else {
                    const select_year = moment(text).format('YYYY'),
                        select_month = moment(text).format('MM'),
                        select_day = moment(text).format('DD'),
                        hour = moment(text).format('HH'),
                        minute = moment(text).format('mm'),
                        second = moment(text).format('ss');
                    this.setState({
                        value: moment(text, dateFormat),
                        year: select_year,
                        month: select_month,
                        day: select_day,
                        hour: hour,
                        minute: minute,
                        second: second
                    });
                }
            }
        } else {
            this.setState({
                value: ''
            });
        }
    }

    dayPickerChangeHandle(date) {
        const {dateFormat} = this.props;
        this.setState({
            value: moment(date.time, dateFormat),
            year: date.year,
            month: date.month,
            day: date.day
        });
    }

    monthPickerChangeHandle(date) {
        this.setState({
            datePickerLevel: 'day',
            year: date.year,
            month: date.month
        });
    }

    yearPickerChangeHandle(year) {
        this.setState({
            datePickerLevel: 'month',
            year: year
        });
    }

    timePickerChangeHandle(obj) {
        let state = _.cloneDeep(this.state);
        state.hour = obj.hour;
        state.minute = obj.minute;
        state.second = obj.second;
        let timer = moment([state.year, +state.month - 1, state.day, state.hour, state.minute, state.second]).format(this.props.dateFormat);
        timer = moment(timer, this.props.dateFormat);
        this.setState({
            hour: obj.hour,
            minute: obj.minute,
            second: obj.second,
            value: timer
        });
    }

    chooseDateAndTimeHandle(value) {
        this.setState({
            datePickerLevel: value
        });
    }

    selectDateTimeHandle() {
        let state = _.cloneDeep(this.state);
        state.popupVisible = false;
        state.datePickerLevel = 'day';
        !this.props.disabled && this.setState(state, () => {
            this.props.onChange && this.props.onChange(state.value && moment(state.value).format(this.props.dateFormat));
        });
    }

    nowHandle() {
        const year = moment().format('YYYY'),
            month = moment().format('MM'),
            day = moment().format('DD'),
            hour = moment().format('HH'),
            minute = moment().format('mm'),
            second = moment().format('ss');

        let timer = moment(moment(), this.props.dateFormat);
        this.setState({
            value: timer,
            year: year,
            month: month,
            day: day,
            hour: hour,
            minute: minute,
            second: second
        });
    }

    togglePopup(e) {
        if (this.validValue) {
            this.setState({
                popupVisible: !this.state.popupVisible,
                triggerEl: e.target
            });
        }
    }

    closePopup() {
        const {value} = this.state;
        !this.props.disabled && this.setState({
            popupVisible: false
        }, () => {
            this.props.onChange && this.props.onChange(value && moment(value).format(this.props.dateFormat));
        });
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.value !== this.props.value || nextProps.dateFormat !== this.props.dateFormat) {
            const value = moment(nextProps.value, nextProps.dateFormat);
            this.setState({
                value: value,
                dateFormat: nextProps.dateFormat,
                year: moment(nextProps.value).format('YYYY'),
                month: moment(nextProps.value).format('MM'),
                day: moment(nextProps.value).format('DD'),
                hour: moment(nextProps.value).format('HH'),
                minute: moment(nextProps.value).format('mm'),
                second: moment(nextProps.value).format('ss')
            });
        }
    }

    componentDidMount() {
        // debugger
        const {value, dateFormat} = this.props;
        let state = _.cloneDeep(this.state);
        if (value) {
            if (moment(value, dateFormat).isValid()) {
                const select_year = moment(value).format('YYYY'),
                    select_month = moment(value).format('MM'),
                    select_day = moment(value).format('DD');
                state.value = moment(value, dateFormat);
                state.year = select_year;
                state.month = select_month;
                state.day = select_day;
                this.setState(state);
            } else {
                console.error('Invalid date');
                this.validValue = false;
            }
        }
    }

    render() {
        const {className, style, name, placeholder, dateFormat, maxValue, minValue, isFooter, disabled} = this.props;
        const {value, popupVisible, datePickerLevel, year, month, day, hour, minute, second, triggerEl} = this.state;
        let textValue = value && moment(value).format(dateFormat);
        return (
            <div className={`date-time-picker ${className}`}
                 ref="datePicker"
                 style={style}>

                <TextField ref="trigger"
                           className="date-picker-field"
                           name={name}
                           placeholder={placeholder}
                           value={textValue}
                           readOnly={true}
                           disabled={disabled}
                           clearButtonVisible={false}
                           isFocusedSelectAll={false}
                           onTouchTap={e => {
                               this.togglePopup(e);
                           }}
                />
                <Popup className={`date-time-picker-popup`}
                       visible={popupVisible}
                       triggerEl={triggerEl}
                       hasTriangle={false}
                       onRequestClose={() => {
                           this.closePopup();
                       }}>

                        <TextField className='calendar-input'
                                   placeholder={'Select Date'}
                                   clearButtonVisible={false}
                                   value={textValue}
                                   onChange={this.textFieldChangeHandle}/>

                    {
                        datePickerLevel == 'day' ?
                            <DayPicker
                                value={value}
                                dateFormat={dateFormat}
                                year={year}
                                month={month}
                                day={day}
                                hour={hour}
                                minute={minute}
                                second={second}
                                maxValue={maxValue ? moment(maxValue).format('YYYY-MM-DD') : null}
                                minValue={minValue ? moment(minValue).format('YYYY-MM-DD') : null}
                                isFooter={true}
                                onChange={this.dayPickerChangeHandle}
                                previousClick={this.datePickerChangeHandle}
                            />
                            : (
                            datePickerLevel == 'month' ?
                                <MonthPicker
                                    value={value}
                                    year={year}
                                    month={month}
                                    day={day}
                                    maxValue={maxValue ? moment(maxValue).format('YYYY-MM-DD') : null}
                                    minValue={minValue ? moment(minValue).format('YYYY-MM-DD') : null}
                                    onChange={this.monthPickerChangeHandle}
                                    previousClick={this.datePickerChangeHandle}
                                />
                                : (
                                datePickerLevel == 'year' ?
                                    <YearPicker
                                        value={value}
                                        year={year}
                                        month={month}
                                        day={day}
                                        maxValue={maxValue ? moment(maxValue).format('YYYY-MM-DD') : null}
                                        minValue={minValue ? moment(minValue).format('YYYY-MM-DD') : null}
                                        onChange={this.yearPickerChangeHandle}
                                    />
                                    :
                                    null
                            )

                        )
                    }
                    {
                        <TimeList className={`time-picker-body ${datePickerLevel == 'time' ? '' : 'hidden'}`}
                                  dateFormat={dateFormat.split(' ')[1]}
                                  popupVisible={datePickerLevel == 'time' ? true : false}
                                  hour={hour}
                                  minute={minute}
                                  second={second}
                                  isRequired={(minValue && textValue.split(' ')[0] == minValue.split(' ')[0]) || (maxValue && textValue.split(' ')[0] == maxValue.split(' ')[0]) ? true : false}
                                  maxValue={maxValue && textValue.split(' ')[0] == maxValue.split(' ')[0] ? moment(maxValue).format('HH:mm:ss') : null}
                                  minValue={minValue && textValue.split(' ')[0] == minValue.split(' ')[0] ? moment(minValue).format('HH:mm:ss') : null}
                                  onChange={this.timePickerChangeHandle}
                        />
                    }
                    {
                        isFooter ?

                                    {
                                        (minValue && moment(this.props.value).isBefore(minValue)) || (maxValue && moment(maxValue).isBefore(this.props.value)) ?

                                                Now

                                            :

                                                Now

                                    }
                                    {
                                        datePickerLevel == 'time' ?
                                             {
                                                this.chooseDateAndTimeHandle('day');
                                            }}>
                                                Select date

                                            :
                                             {
                                                this.chooseDateAndTimeHandle('time');
                                            }}>
                                                Select time

                                    }

                                    <RaisedButton
                                        className={year && month && day && hour && minute && second ? 'active' : ''}
                                        value="Ok"
                                        theme={Theme.HIGHLIGHT}
                                    />

                            :
                            null
                    }

                </Popup>

        );
    }
};

DateTimePicker.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    style: PropTypes.object,

    /**
     * Date picker input name.
     */
    name: PropTypes.string,

    /**
     * This is the initial date value of the component.
     */
    value: PropTypes.string,

    /**
     * The ending of a range of valid dates. The range includes the endDate.
     */
    maxValue: PropTypes.string,

    /**
     * The beginning of a range of valid dates. The range includes the startDate.
     */
    minValue: PropTypes.string,

    /**
     * DateTimePicker textField element placeholder.
     */
    placeholder: PropTypes.string,

    /**
     * Date Time format.
     */
    dateFormat: PropTypes.string,

    /**
     * Callback function that is fired when the date value changes.
     */
    onChange: PropTypes.func

};

DateTimePicker.defaultProps = {
    className: '',
    style: null,
    name: '',
    value: moment().format('YYYY-MM-DD HH:mm:ss'),
    maxValue: '',
    minValue: '',
    placeholder: 'Date',
    dateFormat: 'YYYY-MM-DD HH:mm:ss',
    isFooter: true
};<commit_msg>update DateTimePicker<commit_after>/**
 * @file DateTimePicker component
 * @author sunday(sunday.wei@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import _ from 'lodash';

import TextField from '../TextField';
import DayPicker from '../_DayPicker';
import MonthPicker from '../_MonthPicker';
import YearPicker from '../_YearPicker';
import TimeList from '../_TimeList';
import RaisedButton from '../RaisedButton';
import Popup from '../Popup';
import Theme from 'src/Theme';

export default class DateTimePicker extends Component {

    static propTypes = {

        /**
         * The CSS class name of the root element.
         */
        className: PropTypes.string,

        /**
         * Override the styles of the root element.
         */
        style: PropTypes.object,

        /**
         * Date picker input name.
         */
        name: PropTypes.string,

        /**
         * This is the initial date value of the component.
         */
        value: PropTypes.string,

        /**
         * The ending of a range of valid dates. The range includes the endDate.
         */
        maxValue: PropTypes.string,

        /**
         * The beginning of a range of valid dates. The range includes the startDate.
         */
        minValue: PropTypes.string,

        /**
         * DateTimePicker textField element placeholder.
         */
        placeholder: PropTypes.string,

        /**
         * Date Time format.
         */
        dateFormat: PropTypes.string,

        /**
         * Callback function that is fired when the date value changes.
         */
        onChange: PropTypes.func

    };
    static defaultProps = {
        className: '',
        style: null,
        name: '',
        value: moment().format('YYYY-MM-DD HH:mm:ss'),
        maxValue: '',
        minValue: '',
        placeholder: 'Date',
        dateFormat: 'YYYY-MM-DD HH:mm:ss',
        isFooter: true
    };

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.validValue = true;
        this.state = {
            value: props.value,
            popupVisible: false,
            triggerEl: null,
            year: moment(props.value).format('YYYY'),
            month: moment(props.value).format('MM'),
            day: moment(props.value).format('DD'),
            hour: moment(props.value).format('HH'),
            minute: moment(props.value).format('mm'),
            second: moment(props.value).format('ss'),
            datePickerLevel: 'day'
        };

        this.textFieldChangeHandle = ::this.textFieldChangeHandle;
        this.togglePopup = ::this.togglePopup;
        this.closePopup = ::this.closePopup;
        this.datePickerChangeHandle = ::this.datePickerChangeHandle;
        this.yearPickerChangeHandle = ::this.yearPickerChangeHandle;
        this.monthPickerChangeHandle = ::this.monthPickerChangeHandle;
        this.dayPickerChangeHandle = ::this.dayPickerChangeHandle;
        this.timePickerChangeHandle = ::this.timePickerChangeHandle;
        this.chooseDateAndTimeHandle = ::this.chooseDateAndTimeHandle;
        this.nowHandle = ::this.nowHandle;
        this.selectDateTimeHandle = ::this.selectDateTimeHandle;
    }

    datePickerChangeHandle(selectLevel) {
        this.setState({
            datePickerLevel: selectLevel
        });
    }

    textFieldChangeHandle(text) {
        const {minValue, maxValue, dateFormat} = this.props;
        if (text && text.length) {
            const flag = moment(text, dateFormat, true).isValid();
            if (flag) {
                if (minValue && moment(text).isBefore(minValue) || maxValue && moment(text).isAfter(maxValue)) {

                } else {
                    const select_year = moment(text).format('YYYY'),
                        select_month = moment(text).format('MM'),
                        select_day = moment(text).format('DD'),
                        hour = moment(text).format('HH'),
                        minute = moment(text).format('mm'),
                        second = moment(text).format('ss');
                    this.setState({
                        value: moment(text, dateFormat),
                        year: select_year,
                        month: select_month,
                        day: select_day,
                        hour: hour,
                        minute: minute,
                        second: second
                    });
                }
            }
        } else {
            this.setState({
                value: ''
            });
        }
    }

    dayPickerChangeHandle(date) {
        const {dateFormat} = this.props;
        this.setState({
            value: moment(date.time, dateFormat),
            year: date.year,
            month: date.month,
            day: date.day
        });
    }

    monthPickerChangeHandle(date) {
        this.setState({
            datePickerLevel: 'day',
            year: date.year,
            month: date.month
        });
    }

    yearPickerChangeHandle(year) {
        this.setState({
            datePickerLevel: 'month',
            year: year
        });
    }

    timePickerChangeHandle(obj) {
        let state = _.cloneDeep(this.state);
        state.hour = obj.hour;
        state.minute = obj.minute;
        state.second = obj.second;
        let timer = moment([state.year, +state.month - 1, state.day, state.hour, state.minute, state.second]).format(this.props.dateFormat);
        timer = moment(timer, this.props.dateFormat);
        this.setState({
            hour: obj.hour,
            minute: obj.minute,
            second: obj.second,
            value: timer
        });
    }

    chooseDateAndTimeHandle(value) {
        this.setState({
            datePickerLevel: value
        });
    }

    selectDateTimeHandle() {
        let state = _.cloneDeep(this.state);
        state.popupVisible = false;
        state.datePickerLevel = 'day';
        !this.props.disabled && this.setState(state, () => {
            this.props.onChange && this.props.onChange(state.value && moment(state.value).format(this.props.dateFormat));
        });
    }

    nowHandle() {
        const year = moment().format('YYYY'),
            month = moment().format('MM'),
            day = moment().format('DD'),
            hour = moment().format('HH'),
            minute = moment().format('mm'),
            second = moment().format('ss');

        let timer = moment(moment(), this.props.dateFormat);
        this.setState({
            value: timer,
            year: year,
            month: month,
            day: day,
            hour: hour,
            minute: minute,
            second: second
        });
    }

    togglePopup(e) {
        if (this.validValue) {
            this.setState({
                popupVisible: !this.state.popupVisible,
                triggerEl: e.target
            });
        }
    }

    closePopup() {
        const {value} = this.state;
        !this.props.disabled && this.setState({
            popupVisible: false
        }, () => {
            this.props.onChange && this.props.onChange(value && moment(value).format(this.props.dateFormat));
        });
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.value !== this.props.value || nextProps.dateFormat !== this.props.dateFormat) {
            const value = moment(nextProps.value, nextProps.dateFormat);
            this.setState({
                value: value,
                dateFormat: nextProps.dateFormat,
                year: moment(nextProps.value).format('YYYY'),
                month: moment(nextProps.value).format('MM'),
                day: moment(nextProps.value).format('DD'),
                hour: moment(nextProps.value).format('HH'),
                minute: moment(nextProps.value).format('mm'),
                second: moment(nextProps.value).format('ss')
            });
        }
    }

    componentDidMount() {
        // debugger
        const {value, dateFormat} = this.props;
        let state = _.cloneDeep(this.state);
        if (value) {
            if (moment(value, dateFormat).isValid()) {
                const select_year = moment(value).format('YYYY'),
                    select_month = moment(value).format('MM'),
                    select_day = moment(value).format('DD');
                state.value = moment(value, dateFormat);
                state.year = select_year;
                state.month = select_month;
                state.day = select_day;
                this.setState(state);
            } else {
                console.error('Invalid date');
                this.validValue = false;
            }
        }
    }

    render() {
        const {className, style, name, placeholder, dateFormat, maxValue, minValue, isFooter, disabled} = this.props;
        const {value, popupVisible, datePickerLevel, year, month, day, hour, minute, second, triggerEl} = this.state;
        let textValue = value && moment(value).format(dateFormat);
        return (
            <div className={`date-time-picker ${className}`}
                 ref="datePicker"
                 style={style}>

                <TextField ref="trigger"
                           className="date-picker-field"
                           name={name}
                           placeholder={placeholder}
                           value={textValue}
                           readOnly={true}
                           disabled={disabled}
                           clearButtonVisible={false}
                           isFocusedSelectAll={false}
                           onTouchTap={e => {
                               this.togglePopup(e);
                           }}
                />
                <Popup className={`date-time-picker-popup`}
                       visible={popupVisible}
                       triggerEl={triggerEl}
                       hasTriangle={false}
                       onRequestClose={() => {
                           this.closePopup();
                       }}>

                        <TextField className='calendar-input'
                                   placeholder={'Select Date'}
                                   clearButtonVisible={false}
                                   value={textValue}
                                   onChange={this.textFieldChangeHandle}/>

                    {
                        datePickerLevel == 'day' ?
                            <DayPicker
                                value={value}
                                dateFormat={dateFormat}
                                year={year}
                                month={month}
                                day={day}
                                hour={hour}
                                minute={minute}
                                second={second}
                                maxValue={maxValue ? moment(maxValue).format('YYYY-MM-DD') : null}
                                minValue={minValue ? moment(minValue).format('YYYY-MM-DD') : null}
                                isFooter={true}
                                onChange={this.dayPickerChangeHandle}
                                previousClick={this.datePickerChangeHandle}
                            />
                            : (
                                datePickerLevel == 'month' ?
                                    <MonthPicker
                                        value={value}
                                        year={year}
                                        month={month}
                                        day={day}
                                        maxValue={maxValue ? moment(maxValue).format('YYYY-MM-DD') : null}
                                        minValue={minValue ? moment(minValue).format('YYYY-MM-DD') : null}
                                        onChange={this.monthPickerChangeHandle}
                                        previousClick={this.datePickerChangeHandle}
                                    />
                                    : (
                                        datePickerLevel == 'year' ?
                                            <YearPicker
                                                value={value}
                                                year={year}
                                                month={month}
                                                day={day}
                                                maxValue={maxValue ? moment(maxValue).format('YYYY-MM-DD') : null}
                                                minValue={minValue ? moment(minValue).format('YYYY-MM-DD') : null}
                                                onChange={this.yearPickerChangeHandle}
                                            />
                                            :
                                            null
                                    )

                            )
                    }
                    {
                        <TimeList className={`time-picker-body ${datePickerLevel == 'time' ? '' : 'hidden'}`}
                                  dateFormat={dateFormat.split(' ')[1]}
                                  popupVisible={datePickerLevel == 'time' ? true : false}
                                  hour={hour}
                                  minute={minute}
                                  second={second}
                                  isRequired={(minValue && textValue.split(' ')[0] == minValue.split(' ')[0]) || (maxValue && textValue.split(' ')[0] == maxValue.split(' ')[0]) ? true : false}
                                  maxValue={maxValue && textValue.split(' ')[0] == maxValue.split(' ')[0] ? moment(maxValue).format('HH:mm:ss') : null}
                                  minValue={minValue && textValue.split(' ')[0] == minValue.split(' ')[0] ? moment(minValue).format('HH:mm:ss') : null}
                                  onChange={this.timePickerChangeHandle}
                        />
                    }
                    {
                        isFooter ?

                                    {
                                        (minValue && moment(this.props.value).isBefore(minValue)) || (maxValue && moment(maxValue).isBefore(this.props.value)) ?

                                                Now

                                            :

                                                Now

                                    }
                                    {
                                        datePickerLevel == 'time' ?
                                             {
                                                this.chooseDateAndTimeHandle('day');
                                            }}>
                                                Select date

                                            :
                                             {
                                                this.chooseDateAndTimeHandle('time');
                                            }}>
                                                Select time

                                    }

                                    <RaisedButton
                                        className={year && month && day && hour && minute && second ? 'active' : ''}
                                        value="Ok"
                                        theme={Theme.HIGHLIGHT}
                                    />

                            :
                            null
                    }

                </Popup>

        );
    }
};<|endoftext|>


<commit_before>var exec = require('child_process').exec,
	_ = require('underscore'),
	fs = require('fs'),
	config = require('./config').Config;

/**
 * Initialize the Thumbnailer
 */
function Thumbnailer(opts) {
	// for the benefit of testing
	// perform dependency injection.
	_.extend(this, {
		tmp: require('tmp')
	}, opts);
}

/**
 * Execute the image conversion command
 *
 * @param object description The job description
 * @param localPath The local path to the image
 * @param function onComplete The callback function
 */
Thumbnailer.prototype.execute = function(description, localPath, onComplete) {
	var _this = this;

	// parameters for a single execution
	// of the thumbnailer.
	_.extend(this, {
		localPath: localPath,
		width: description.width,
		height: description.height,
		format: (description.format || 'jpg'),
		strategy: (description.strategy || 'bounded'),
		background: (description.background || 'black'),
		quality: (description.quality || null),
		onComplete: onComplete,
		thumbnailTimeout: 20000
	});

	this.createConversionPath(function(err) {

		if (err) {
			_this.onComplete(err);
			return;
		}

		// apply the thumbnail creation strategy.
		if (!_this[_this.strategy]) {
			_this.onComplete('could not find strategy ' + _this.strategy);
		} else {
			_this[_this.strategy]();
		}
	});
};

/**
 * Create a temp file for the converted image
 *
 * @param function callback The callback function
 */
Thumbnailer.prototype.createConversionPath = function(callback) {
	var _this = this;

	this.tmp.file({dir: config.get('tmpDir'), postfix: "." + this.format}, function(err, convertedPath, fd) {
		fs.closeSync(fd); // close immediately, we do not use this file handle.
		_this.convertedPath = convertedPath;
		callback(err);
	});
};

/**
 * Execute the conversion command
 *
 * @param string command The command
 */
Thumbnailer.prototype.execCommand = function(command) {
	var _this = this;

	exec(command, {timeout: this.thumbnailTimeout}, function(err, stdout, stderr) {

		console.log('running command ', command);

		if (err) {
			_this.onComplete(err);
			return;
		}

		// make sure the conversion was successful.
		fs.stat(_this.convertedPath, function(err, stat) {
			if (err || stat.size === 0) {
				err =  'zero byte thumbnail created';
				_this.onComplete(err);
				return;
			}
			_this.onComplete(null, _this.convertedPath);
		});

	});
};

/**
 * Convert the image using the matted strategy
 */
Thumbnailer.prototype.matted = function() {
	var qualityString = (this.quality ? '-quality ' + this.quality : ''),
		thumbnailCommand = config.get('convertCommand') + ' "' + this.localPath + '[0]" -thumbnail ' + (this.width * this.height) + '@ -gravity center -background ' + this.background + ' -extent ' + this.width + 'X' + this.height + ' ' + qualityString + ' ' + this.convertedPath;

	this.execCommand(thumbnailCommand);
};

/**
 * Convert the image using the bounded strategy
 */
Thumbnailer.prototype.bounded = function() {
	var dimensionsString = this.width + 'X' + this.height,
		qualityString = (this.quality ? '-quality ' + this.quality + ' ' : ''),
		thumbnailCommand = config.get('convertCommand') + ' "' + this.localPath + '[0]" -thumbnail ' + dimensionsString + ' ' + qualityString + this.convertedPath;

	this.execCommand(thumbnailCommand);
};

/**
 * Convert the image using the fill strategy
 */
Thumbnailer.prototype.fill = function() {
	var dimensionsString = this.width + 'X' + this.height,
		qualityString = (this.quality ? '-quality ' + this.quality : ''),
		thumbnailCommand = config.get('convertCommand') + ' "' + this.localPath + '[0]" -resize ' + dimensionsString + '^ -gravity center -extent ' + dimensionsString + ' ' + qualityString + ' ' + this.convertedPath;

	this.execCommand(thumbnailCommand);
};

exports.Thumbnailer = Thumbnailer;
<commit_msg>added custom strategy<commit_after>var exec = require('child_process').exec,
	_ = require('underscore'),
	fs = require('fs'),
	config = require('./config').Config;

/**
 * Initialize the Thumbnailer
 */
function Thumbnailer(opts) {
	// for the benefit of testing
	// perform dependency injection.
	_.extend(this, {
		tmp: require('tmp')
	}, opts);
}

/**
 * Execute the image conversion command
 *
 * @param object description The job description
 * @param localPath The local path to the image
 * @param function onComplete The callback function
 */
Thumbnailer.prototype.execute = function(description, localPath, onComplete) {
	var _this = this;

	// parameters for a single execution
	// of the thumbnailer.
	_.extend(this, {
		localPath: localPath,
		width: description.width,
		height: description.height,
		format: (description.format || 'jpg'),
		strategy: (description.strategy || 'bounded'),
		background: (description.background || 'black'),
		quality: (description.quality || null),
		options: (description.options || null),
		onComplete: onComplete,
		thumbnailTimeout: 20000
	});

	this.createConversionPath(function(err) {

		if (err) {
			_this.onComplete(err);
			return;
		}

		// apply the thumbnail creation strategy.
		if (!_this[_this.strategy]) {
			_this.onComplete('could not find strategy ' + _this.strategy);
		} else {
			_this[_this.strategy]();
		}
	});
};

/**
 * Create a temp file for the converted image
 *
 * @param function callback The callback function
 */
Thumbnailer.prototype.createConversionPath = function(callback) {
	var _this = this;

	this.tmp.file({dir: config.get('tmpDir'), postfix: "." + this.format}, function(err, convertedPath, fd) {
		fs.closeSync(fd); // close immediately, we do not use this file handle.
		_this.convertedPath = convertedPath;
		callback(err);
	});
};

/**
 * Execute the conversion command
 *
 * @param string command The command
 */
Thumbnailer.prototype.execCommand = function(command) {
	var _this = this;

	exec(command, {timeout: this.thumbnailTimeout}, function(err, stdout, stderr) {

		console.log('running command ', command);

		if (err) {
			_this.onComplete(err);
			return;
		}

		// make sure the conversion was successful.
		fs.stat(_this.convertedPath, function(err, stat) {
			if (err || stat.size === 0) {
				err =  'zero byte thumbnail created';
				_this.onComplete(err);
				return;
			}
			_this.onComplete(null, _this.convertedPath);
		});

	});
};

/**
 * Convert the image using the manual strategy
 */
Thumbnailer.prototype.manual = function() {
	var thumbnailCommand = config.get('convertCommand') + ' "' + this.localPath + '[0]" ' + this.options + ' ' + this.convertedPath;

	this.execCommand(thumbnailCommand);
};

/**
 * Convert the image using the matted strategy
 */
Thumbnailer.prototype.matted = function() {
	var qualityString = (this.quality ? '-quality ' + this.quality : ''),
		thumbnailCommand = config.get('convertCommand') + ' "' + this.localPath + '[0]" -thumbnail ' + (this.width * this.height) + '@ -gravity center -background ' + this.background + ' -extent ' + this.width + 'X' + this.height + ' ' + qualityString + ' ' + this.convertedPath;

	this.execCommand(thumbnailCommand);
};

/**
 * Convert the image using the bounded strategy
 */
Thumbnailer.prototype.bounded = function() {
	var dimensionsString = this.width + 'X' + this.height,
		qualityString = (this.quality ? '-quality ' + this.quality + ' ' : ''),
		thumbnailCommand = config.get('convertCommand') + ' "' + this.localPath + '[0]" -thumbnail ' + dimensionsString + ' ' + qualityString + this.convertedPath;

	this.execCommand(thumbnailCommand);
};

/**
 * Convert the image using the fill strategy
 */
Thumbnailer.prototype.fill = function() {
	var dimensionsString = this.width + 'X' + this.height,
		qualityString = (this.quality ? '-quality ' + this.quality : ''),
		thumbnailCommand = config.get('convertCommand') + ' "' + this.localPath + '[0]" -resize ' + dimensionsString + '^ -gravity center -extent ' + dimensionsString + ' ' + qualityString + ' ' + this.convertedPath;

	this.execCommand(thumbnailCommand);
};

exports.Thumbnailer = Thumbnailer;
<|endoftext|>


<commit_before><commit_msg>Commited from lenh at Thu, Jul 06, 2017  9:50:40 AM<commit_after><|endoftext|>


<commit_before>var queryMethod = require("./helpers").queryMethod
var EventProxy = require('./event-proxy')
var StateMachine = require('./state-machine')
var QueryAdapter = require('./query-adapter')

module.exports = Transaction

require('util').inherits(Transaction, EventProxy)

function Transaction () {
	this.handleError = _handleError.bind(this)

	StateMachine.call(this, 'pending', {
		'query': {
			'pending':     queueQuery,
			'opening':     queueQuery,
			'dequeueing':  queueQuery,
			'open':        doQuery,
			'rolled back': rejectQuery,
			'committed':   rejectQuery,
			'errored':     rejectQuery,
		},
		// Allow rollback to be called repeatedly
		'rollback': {
			'rolled back': function () {}
		}
	}, {
		'pending':      [ 'opening' ],
		'opening':      [ 'dequeueing' ],
		'dequeueing':   [ 'open', 'rolled back', 'committed' ],
		'open':         [ 'open', 'rolled back', 'committed' ],
	}, this.handleError)

	this._queue = []
	this.query = queueQuery
	this.log = false
}

function _handleError (err, callback) {
	var propagate = callback || this.emit.bind(this, 'error')
	if (this.state() != 'rolled back') this.rollback(function (rollbackErr) {
		if (rollbackErr) {
			err = new Error('Failed to rollback transaction: ' + rollbackErr
			                + '\nError causing rollback: ' + err)
		}
		propagate(err)
	})
	else process.nextTick(propagate)
}

Transaction.prototype.begin = function (conn, callback) {
	if (!this.state('opening', callback)) return this
	var self = this
	if (this.log) this.log('starting transaction')
	conn.query('begin', function (err) {
		if (err) return self.handleError(err, callback)
		self._connection = conn
		self.proxyEvent(conn, 'error')
		self._runQueue(callback)
	})
	return this
}

Transaction.prototype._runQueue = function (callback) {
	if (!this.state('dequeueing', callback)) return
	var i = 0
	  , self = this
		, next
	;(next = (function () {
		var conn = this._connection
		var args = this._queue[i++]
		if (args) {
			this.log && this.log(args[0])
			var qa = conn.query.apply(conn, args)
			qa.listeners('end').unshift(next)
			// If no callback was given, the Transaction handles any errors
			if (!args[2]) qa.on('error', self.handleError)
		} else {
			// The queue is empty, queries can now go directly to the connection.
			this._queue = null
			if (this.state('open', callback) && callback) callback(null, this)
		}
	}).bind(this))()
}

var queueQuery = queryMethod(function (stmt, params, callback) {
	var qa = new QueryAdapter()
	this._queue.push([stmt, params, callback, qa])
	return qa
})

var doQuery = queryMethod(function (stmt, params, callback) {
	return this._connection.query(stmt, params, callback || this.handleError)
})

var rejectQuery = queryMethod(function (stmt, params, callback) {
	var self = this
	  , qa = new QueryAdapter
	  , msg = "Cannot perform query in '" + this.state() + "' state. Query: " + stmt
	  , err = new Error(msg)
	process.nextTick(function () {
		if (callback) callback(err)
		else qa.emit('error', err)
	})
	return qa
})

Transaction.prototype.commit = sqlTransition('committed', 'commit')
Transaction.prototype.rollback = sqlTransition('rolled back', 'rollback')

function sqlTransition (newState, stmt) {
	return function (callback) {
		var self = this
		if (this.state(newState, callback)) {
			this._connection.query(stmt, callback)
		}
		return this
	}
}
<commit_msg>Don't use transaction.handleError as a normal callback<commit_after>var queryMethod = require("./helpers").queryMethod
var EventProxy = require('./event-proxy')
var StateMachine = require('./state-machine')
var QueryAdapter = require('./query-adapter')

module.exports = Transaction

require('util').inherits(Transaction, EventProxy)

function Transaction () {
	this.handleError = _handleError.bind(this)

	StateMachine.call(this, 'pending', {
		'query': {
			'pending':     queueQuery,
			'opening':     queueQuery,
			'dequeueing':  queueQuery,
			'open':        doQuery,
			'rolled back': rejectQuery,
			'committed':   rejectQuery,
			'errored':     rejectQuery,
		},
		// Allow rollback to be called repeatedly
		'rollback': {
			'rolled back': function () {}
		}
	}, {
		'pending':      [ 'opening' ],
		'opening':      [ 'dequeueing' ],
		'dequeueing':   [ 'open', 'rolled back', 'committed' ],
		'open':         [ 'open', 'rolled back', 'committed' ],
	}, this.handleError)

	this._queue = []
	this.query = queueQuery
	this.log = false
}

function _handleError (err, callback) {
	var propagate = callback || this.emit.bind(this, 'error')
	if (this.state() != 'rolled back') this.rollback(function (rollbackErr) {
		if (rollbackErr) {
			err = new Error('Failed to rollback transaction: ' + rollbackErr
			                + '\nError causing rollback: ' + err)
		}
		propagate(err)
	})
	else process.nextTick(propagate)
}

Transaction.prototype.begin = function (conn, callback) {
	if (!this.state('opening', callback)) return this
	var self = this
	if (this.log) this.log('starting transaction')
	conn.query('begin', function (err) {
		if (err) return self.handleError(err, callback)
		self._connection = conn
		self.proxyEvent(conn, 'error')
		self._runQueue(callback)
	})
	return this
}

Transaction.prototype._runQueue = function (callback) {
	if (!this.state('dequeueing', callback)) return
	var i = 0
	  , self = this
		, next
	;(next = (function () {
		var conn = this._connection
		var args = this._queue[i++]
		if (args) {
			this.log && this.log(args[0])
			var qa = conn.query.apply(conn, args)
			qa.listeners('end').unshift(next)
			// If no callback was given, the Transaction handles any errors
			if (!args[2]) qa.on('error', self.handleError)
		} else {
			// The queue is empty, queries can now go directly to the connection.
			this._queue = null
			if (this.state('open', callback) && callback) callback(null, this)
		}
	}).bind(this))()
}

var queueQuery = queryMethod(function (stmt, params, callback) {
	var qa = new QueryAdapter()
	this._queue.push([stmt, params, callback, qa])
	return qa
})

var doQuery = queryMethod(function (stmt, params, callback) {
	var qa = this._connection.query(stmt, params, callback)
	if (!callback) qa.on('error', this.handleError)
	return qa
})

var rejectQuery = queryMethod(function (stmt, params, callback) {
	var self = this
	  , qa = new QueryAdapter
	  , msg = "Cannot perform query in '" + this.state() + "' state. Query: " + stmt
	  , err = new Error(msg)
	process.nextTick(function () {
		if (callback) callback(err)
		else qa.emit('error', err)
	})
	return qa
})

Transaction.prototype.commit = sqlTransition('committed', 'commit')
Transaction.prototype.rollback = sqlTransition('rolled back', 'rollback')

function sqlTransition (newState, stmt) {
	return function (callback) {
		var self = this
		if (this.state(newState, callback)) {
			this._connection.query(stmt, callback)
		}
		return this
	}
}
<|endoftext|>


<commit_before>//Check value of page
function onLoad() {
	if (localStorage.getItem("valve") == "1"){
		toFRC();
		}
	if (localStorage.getItem("valve") == "0"){
		toFTC();
		}
		}
//Set page to FTC
function toFTC() {
    var team = document.getElementsByClassName("team");
	team[1].style.display="none";
	team[0].style.display="initial";
    team[0].style.textIndent="initial";
	var e=document.getElementById("left");
		e.className="off";
	var e=document.getElementById("right");
		e.className="on";
		localStorage.setItem("valve", "0");
	document.title = "C5CC - FTC " + page;
}

//Set page to FRC
function toFRC() {
	var team = document.getElementsByClassName("team");
    team[0].style.display="none";
    team[1].style.display="initial";
    team[1].style.textIndent="initial";
	var e=document.getElementById("right");
		e.className="off";
	var e=document.getElementById("left");
		e.className="on";
		localStorage.setItem("valve", "1");
	document.title = "C5CC - FRC " + page;
}
<commit_msg>Added files via upload<commit_after>//Check value of page
function onLoad() {
	if (localStorage.getItem("valve") == "4"){
		to4();
		}
	if (localStorage.getItem("valve") == "3"){
		to3();
		}
	if (localStorage.getItem("valve") == "2"){
		to2();
		}
	if (localStorage.getItem("valve") == "1"){
		to1();
		}
	if (localStorage.getItem("valve") == "0"){
		to0();
		}
	if (localStorage.getItem("valve") === null){
		to0();
		}
		}

function to0() {
    var graph = document.getElementsByClassName("Body");
	graph[0].style.display="initial";
	graph[1].style.display="none";
	graph[2].style.display="none";
	graph[3].style.display="none";
	graph[4].style.display="none";
	localStorage.setItem("valve", "0");
}
function to1() {
    var graph = document.getElementsByClassName("Body");
	graph[0].style.display="none";
	graph[1].style.display="initial";
	graph[2].style.display="none";
	graph[3].style.display="none";
	graph[4].style.display="none";
	localStorage.setItem("valve", "1");
}
function to2() {
    var graph = document.getElementsByClassName("Body");
	graph[0].style.display="none";
	graph[1].style.display="none";
	graph[2].style.display="initial";
	graph[3].style.display="none";
	graph[4].style.display="none";
	localStorage.setItem("valve", "2");
}
function to3() {
    var graph = document.getElementsByClassName("Body");
	graph[0].style.display="none";
	graph[1].style.display="none";
	graph[2].style.display="none";
	graph[3].style.display="initial";
	graph[4].style.display="none";
	localStorage.setItem("valve", "3");
}
function to4() {
    var graph = document.getElementsByClassName("Body");
	graph[0].style.display="none";
	graph[1].style.display="none";
	graph[2].style.display="none";
	graph[3].style.display="none";
	graph[4].style.display="initial";
	localStorage.setItem("valve", "4");
}
function prevG() {
	var valve = localStorage.getItem("valve");
	if(valve >= 1){
		valve--;
		localStorage.setItem("valve", valve);
		onLoad();
	}
}
function nextG() {
	var valve = localStorage.getItem("valve");
	if(valve <= 3){
		valve++;
		localStorage.setItem("valve", valve);
		onLoad();
	}
}<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  User = mongoose.model('User'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

/**
 * Show the current user
 */
exports.read = function (req, res) {
  res.json(req.model);
};

/**
 * Update a User
 */
exports.update = function (req, res) {
  var user = req.model;

  //For security purposes only merge these parameters
  user.firstName = req.body.firstName;
  user.lastName = req.body.lastName;
  user.displayName = user.firstName + ' ' + user.lastName;
  user.roles = req.body.roles;
  user.station = mongoose.Types.ObjectId(req.body.station._id);

  user.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    }

    res.json(user);
  });
};

/**
 * Delete a user
 */
exports.delete = function (req, res) {
  var user = req.model;

  user.remove(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    }

    res.json(user);
  });
};

/**
 * List of Users
 */
exports.list = function (req, res) {
  User.find({}, '-salt -password').sort('-created').populate('user', 'displayName').exec(function (err, users) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    }

    res.json(users);
  });
};

/**
 * User middleware
 */
exports.userByID = function (req, res, next, id) {
  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'User is invalid'
    });
  }

  User.findById(id, '-salt -password').exec(function (err, user) {
    if (err) {
      return next(err);
    } else if (!user) {
      return next(new Error('Failed to load user ' + id));
    }

    req.model = user;
    next();
  });
};
<commit_msg>fixed station reference!<commit_after>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  User = mongoose.model('User'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

/**
 * Show the current user
 */
exports.read = function (req, res) {
  res.json(req.model);
};

/**
 * Update a User
 */
exports.update = function (req, res) {
  var user = req.model;

  //For security purposes only merge these parameters
  user.firstName = req.body.firstName;
  user.lastName = req.body.lastName;
  user.displayName = user.firstName + ' ' + user.lastName;
  user.roles = req.body.roles;

  var station = JSON.parse(req.body.station);
  user.station = mongoose.Types.ObjectId(station._id);

  user.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    }

    res.json(user);
  });
};

/**
 * Delete a user
 */
exports.delete = function (req, res) {
  var user = req.model;

  user.remove(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    }

    res.json(user);
  });
};

/**
 * List of Users
 */
exports.list = function (req, res) {
  User.find({}, '-salt -password').sort('-created').populate('user', 'displayName').exec(function (err, users) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    }

    res.json(users);
  });
};

/**
 * User middleware
 */
exports.userByID = function (req, res, next, id) {
  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'User is invalid'
    });
  }

  User.findById(id, '-salt -password').exec(function (err, user) {
    if (err) {
      return next(err);
    } else if (!user) {
      return next(new Error('Failed to load user ' + id));
    }

    req.model = user;
    next();
  });
};
<|endoftext|>


<commit_before>#!/usr/bin/env node

var ennenn = require("./index");

var parser = new ennenn.RequestParser(function on_request(request) {
  console.log("[Request started] " + request.command + ": " + request.arguments.join(", "));

/*
  request.on("data", function on_data(chunk) {
    console.log("[Request data] " + chunk.length);
  });

  request.on("end", function on_end() {
    console.log("[Request ended]");
  });
*/
});

parser.write("GET a b c\r\n");
<commit_msg>removed commented code from request example<commit_after>#!/usr/bin/env node

var ennenn = require("./index");

var parser = new ennenn.RequestParser(function on_request(request) {
  console.log("[Request] " + request.command + ": " + request.arguments.join(", "));
});

parser.write("GET a b c\r\n");
<|endoftext|>


<commit_before>const hapi = require('hapi')
const nes = require('nes')
const server = new hapi.Server()

server.connection({
  host: 'localhost',
  port: 3000
})

server.register(nes, (err) => {
  if (err) { throw err }

  server.subscription('/greet')

  server.route({
    method: 'POST',
    path: '/h',
    config: {
      id: 'hello',
      handler: function (request, reply) {
        // in the publish response we assign meta.id to the request payload id
        server.publish('/greet', { hello: 'world', meta: { id: request.payload.id } })
        return reply('world!')
      }
    }
  })
})

server.start((err) => {
  if (err) throw err
  console.log('now listening on localhost:3000')
})
<commit_msg>update example server<commit_after>'use strict'

const hapi = require('hapi')
const nes = require('nes')
const server = new hapi.Server()

server.connection({
  host: 'localhost',
  port: 3000
})

server.register(nes, (err) => {
  if (err) { throw err }

  server.subscription('/greet')

  server.route({
    method: 'POST',
    path: '/h',
    config: {
      id: 'hello',
      handler: function (request, reply) {
        // in the publish response we assign meta.id to the request payload id
        server.publish('/greet', { hello: 'world', meta: { id: request.payload.id } })
        return reply('world!')
      }
    }
  })
})

server.start((err) => {
  if (err) throw err
  console.log('now listening on localhost:3000')
})
<|endoftext|>


<commit_before>if (wysihtml5.browser.supported()) {
  module("wysihtml5.quirks.cleanPastedHTML", {
    setup: function() {
      this.refNode = document.createElement("div");
      this.refNode.style.fontSize = "24px";
      this.refNode.style.color = "rgba(0,0,0)";
    },

    teardown: function() {
    }

  });

  test("Basic test", function(assert) {
    var rules = {
      tags: {
        "u": {},
        "a": {
          "check_attributes": {
            "href": "href",
            "rel": "any",
            "target": "any"
          }
        },
        "b": {}
      },
      selectors: {
        "a u": "unwrap"
      }
    };

    var options = {
      "referenceNode": this.refNode,
      "rules": [{"set":rules}],
      "uneditableClass": "wysihtml5-uneditable-container"
    };

    assert.htmlEqual(
      wysihtml5.quirks.cleanPastedHTML("See: best search engine", options),
      "See: best search engine",
      "Correctly removed  within "
    );
  });

  test("Non-breakable space test", function(assert) {
    var options = {
      "referenceNode": this.refNode,
      "rules": [{"set": {}}],
      "uneditableClass": "wysihtml5-uneditable-container"
    };

    equal(
      wysihtml5.quirks.cleanPastedHTML("test     ", options),
      "test     ",
      "Correctly split nonbreakable spaces"
    );
  });
}
<commit_msg>Add paste cleanup tests<commit_after>if (wysihtml5.browser.supported()) {
  module("wysihtml5.quirks.cleanPastedHTML", {
    setup: function() {
      this.refNode = document.createElement("div");
      this.refNode.style.fontSize = "24px";
      this.refNode.style.color = "rgba(0,0,0)";
      this.uneditableClass = "wysihtml5-uneditable-container";
    },

    teardown: function() {

    }

  });

  test("Basic test", function(assert) {
    var rules = {
      tags: {
        "u": {},
        "a": {
          "check_attributes": {
            "href": "href",
            "rel": "any",
            "target": "any"
          }
        },
        "b": {}
      },
      selectors: {
        "a u": "unwrap"
      }
    };

    var options = {
      "referenceNode": this.refNode,
      "rules": [{"set":rules}],
      "uneditableClass": this.uneditableClass
    };

    assert.htmlEqual(
      wysihtml5.quirks.cleanPastedHTML("See: best search engine", options),
      "See: best search engine",
      "Correctly removed  within "
    );
  });

  test("Non-breakable space test", function(assert) {
    var options = {
      "referenceNode": this.refNode,
      "rules": [{"set": {}}],
      "uneditableClass": this.uneditableClass
    };

    assert.htmlEqual(
      wysihtml5.quirks.cleanPastedHTML("test     ", options),
      "test     ",
      "Correctly split nonbreakable spaces"
    );
  });

  test("Ruleset picking tests", function(assert) {
    var options = {
      "referenceNode": this.refNode,
      "rules": [
        {
          "condition": /class="?Mso/i,
          "set": {
            "tags": {
            }
          }
        },
        {
          "set": {
            "classes": "any",
            "comments": 1,
            "tags": {
              "p": {},
              "span": {}
            }
          }
        }
      ],
      "uneditableClass": this.uneditableClass
    };

    assert.htmlEqual(
      wysihtml5.quirks.cleanPastedHTML('
test
', options),
      "test",
      "Picked correctly to first ruleset"
    );
    assert.htmlEqual(
      wysihtml5.quirks.cleanPastedHTML('
test
', options),
      "test",
      "First ruleset removes comments correctly"
    );

    assert.htmlEqual(
      wysihtml5.quirks.cleanPastedHTML('
test
', options),
      '
test
',
      "Picked correctly to second ruleset"
    );
    assert.htmlEqual(
      wysihtml5.quirks.cleanPastedHTML('
test
', options),
      '
test
',
      "Second ruleset keeps comments correctly"
    );
  });

  test("Root color and font-size removal tests", function(assert) {
    var options = {
      "referenceNode": this.refNode,
      "rules": [{"set": {
        "tags": {
          "span": {
            "keep_styles": {
              "color": 1,
              "fontSize": 1
            }
          }
        }
      }}],
      "uneditableClass": this.uneditableClass
    };

    assert.htmlEqual(
      wysihtml5.quirks.cleanPastedHTML('test', options),
      'test',
      "Correctly removed defult styles"
    );

    assert.htmlEqual(
      wysihtml5.quirks.cleanPastedHTML('test', options),
      'test',
      "Correctly kept different style"
    );

    assert.htmlEqual(
      wysihtml5.quirks.cleanPastedHTML('test', options),
      'test',
      "Correctly moved one and kept another"
    );

    assert.htmlEqual(
      wysihtml5.quirks.cleanPastedHTML('test', options),
      'test',
      "Correctly kept all styles"
    );
  });

}
<|endoftext|>


<commit_before><commit_msg>git workflow complete<commit_after>
// Basic Git Workflow

1. ``` git init ``` // initializes new repo

2.  ```Git project with Working Directory, Staging Area and a repository.```

3. ``` git status ``` // track files and modifications
   ``` git add <filename> ``` // adds file to staging Area
   ``` git diff <filename> ``` // shows the changes in file
   ``` git commit -m "Complete first line of dialouge"``` // -m for msg to commit message
   ``` git log ``` // shows history of commits

   ``` git push origin <branch> ``` // pushes commits to branch names
<|endoftext|>


<commit_before>var chain = require('../dist').chain;

function base() {
  console.log('BASE');
}

function child() {
  console.log('CHILD');
}

var base = chain(base, { child : child } );

base(); // Prints BASE
base().child(); // Prints CHILD
<commit_msg>Linted examples<commit_after>var chain = require('../dist').chain;

function base() {
  console.log('BASE');
}

function child() {
  console.log('CHILD');
}

var baseWrapped = chain(base, { child : child });

baseWrapped(); // Prints BASE
baseWrapped().child(); // Prints CHILD
<|endoftext|>


<commit_before>require("should");
var dataUtil = require("../../data-util/sales/production-order-data-util");
var fpSCdataUtil = require("../../data-util/sales/finishing-printing-sales-contract-data-util");
var processTypeDataUtil = require("../../data-util/master/process-type-data-util");
var buyerDataUtil = require("../../data-util/master/buyer-data-util");
var accountDataUtil = require("../../data-util/auth/account-data-util");
var dailyOperationUtil = require("../../data-util/production/finishing-printing/daily-operation-data-util");
var fabricQualityControlUtil = require("../../data-util/production/finishing-printing/fabric-quality-control-data-util");
var helper = require("../../helper");
var validate = require("dl-models").validator;
var codeGenerator = require('../../../src/utils/code-generator');

var ProcessTypeManager = require("../../../src/managers/master/process-type-manager");
var fpSCManager = require("../../../src/managers/sales/finishing-printing-sales-contract-manager");
var BuyerManager = require("../../../src/managers/master/buyer-manager");
var AccountManager = require("../../../src/managers/auth/account-manager");
var ProductionOrderManager = require("../../../src/managers/sales/production-order-manager");
var manager = null;
var processTypeManager = null;
var buyerManager = null;
var accountManager = null;

before('#00. connect db', function (done) {
    helper.getDb()
        .then(db => {
            manager = new ProductionOrderManager(db, { username: 'dev' });
            processTypeManager = new ProcessTypeManager(db, { username: 'dev' });
            buyerManager = new BuyerManager(db, { username: 'dev' });
            accountManager = new AccountManager(db, { username: 'dev' });
            fpSCManager = new fpSCManager(db, { username: 'dev' });
            done();
        })
        .catch(e => {
            done(e);
        });
});
var dataBuyer1;
var dataBuyer2;
var dataProcessType1;
var dataProcessType2;
var dataAccount1;
var dataAccount2;
var fpSC;

it("#01. should success when create new support data (buyer, account, process type)", function (done) {
    var processType1 = processTypeDataUtil.getNewData();
    var buyer1 = buyerDataUtil.getNewData();
    var account1 = accountDataUtil.getNewData();
    Promise.all([processType1, buyer1, account1])
        .then(data1 => {
            var processType2 = processTypeDataUtil.getNewData();
            var buyer2 = buyerDataUtil.getNewData();
            var account2 = accountDataUtil.getNewData();
            Promise.all([processType2, buyer2, account2])
                .then(data2 => {
                    Promise.all([processTypeManager.create(data1[0]), processTypeManager.create(data2[0]), buyerManager.create(data1[1]), buyerManager.create(data2[1]), accountManager.create(data1[2]), accountManager.create(data2[2])])
                        .then(id => {
                            Promise.all([processTypeManager.getSingleById(id[0]), processTypeManager.getSingleById(id[1]), buyerManager.getSingleById(id[2]), buyerManager.getSingleById(id[3]), accountManager.getSingleById(id[4]), accountManager.getSingleById(id[5])])
                                .then(results => {
                                    validate.master.processType(results[0]);
                                    dataProcessType1 = results[0];
                                    validate.master.processType(results[1]);
                                    dataProcessType2 = results[1];
                                    validate.master.buyer(results[2]);
                                    dataBuyer1 = results[2];
                                    validate.master.buyer(results[3]);
                                    dataBuyer2 = results[3];
                                    validate.auth.account(results[4]);
                                    dataAccount1 = results[4];
                                    validate.auth.account(results[5]);
                                    dataAccount2 = results[5];
                                    done();
                                })
                                .catch(e => {
                                    done(e);
                                });
                        })
                        .catch(e => {
                            done(e);
                        });
                })
                .catch(e => {
                    done(e);
                });
        })
        .catch(e => {
            done(e);
        });
});

var createdSCId;
var createdSCdata;
it("#01.5. should success when create SalesContract", function (done) {
    fpSCdataUtil.getNewData()
        .then((data) => {
            createdSCdata = data;
            fpSCManager.create(data)
                .then((id) => {
                    return fpSCManager.getSingleById(id);
                })
                .then(sc => {
                    createdSCdata = sc;
                    done();
                })
                .catch((e) => {
                    done(e);
                });
        });
})

it("#02. should success when delete all exist data production order", function (done) {
    manager.read({ size: 100 })
        .then(results => {
            if (results.data.length === 0) {
                done();
            } else {
                var destroyData = [];
                for (var pOrder of results.data) {
                    var des = manager.destroy(pOrder._id);
                    destroyData.push(des);
                }
                if (destroyData.length === 0) {
                    done();
                } else {
                    Promise.all(destroyData)
                        .then(data => {
                            data.should.be.instanceof(Array);
                            for (var a of data)
                                a.should.equal(true);
                            done();
                        })
                        .catch(e => {
                            done(e);
                        });
                }
            }
        })
        .catch(e => {
            done(e);
        });
});

it("#03. should success get all data Production Order (0 data) when searh report without parameter", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/json",
        filter: {}
    };
    manager.getReport(query)
        .then(docs => {
            var data = docs.data;
            data.should.be.instanceof(Array);
            // data.length.should.equal(0);
            done();
        })
        .catch(e => {
            done(e);
        });
});

var scId = [];
var selesContractNo;
var orderNo;
it("#04. should success when create new 10 data Production Order with 2 detail color in each data production order", function (done) {
    var dataReport = [];
    for (var a = 0; a < 5; a++) {
        var data = dataUtil.getNewData({ buyer: dataBuyer1, process: dataProcessType1, account: dataAccount1, salesContract: createdSCdata });
        dataReport.push(data);
    }
    for (var a = 0; a < 5; a++) {
        var data = dataUtil.getNewData({ buyer: dataBuyer2, process: dataProcessType2, account: dataAccount2, salesContract: createdSCdata });
        dataReport.push(data);
    }
    Promise.all(dataReport)
        .then(dataResults => {
            var createData = [];
            var numberIndex = 0;
            for (var a of dataResults) {
                numberIndex++;
                var code = codeGenerator();
                a.salesContractNo = createdSCdata.salesContractNo;
                a.salesContractId = createdSCdata._id;
                a.orderNo = `${code}${numberIndex}`;
                var dataProdOrder = manager.create(a);
                createData.push(dataProdOrder);
                salesContractNo = a.salesContractNo;
                orderNo = a.orderNo;
            }
            Promise.all(createData)
                .then(created => {
                    scId = created;
                    done();
                })
                .catch(e => {
                    done(e);
                });
        })
        .catch(e => {
            done(e);
        });
});

it("#05. should success get all data Production Order when searh report without parameter", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/json",
        filter: {}
    };
    manager.getReport(query)
        .then(docs => {
            var data = docs.data;
            data.should.be.instanceof(Array);
            data.length.should.equal(20);
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#06. should success get all data Production Order (2 data) when searh report with Sales Contract No parameter", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/json",
        filter: { salesContractNo: salesContractNo }
    };
    manager.getReport(query)
        .then(docs => {
            var data = docs.data;
            data.should.be.instanceof(Array);
            data.length.should.equal(20);
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#07. should success get all data Production Order (2 data) when searh report with Order No parameter", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/json",
        orderNo: orderNo
    };
    manager.getReport(query)
        .then(docs => {
            var data = docs.data;
            data.should.be.instanceof(Array);
            data.length.should.equal(2);
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#08. should success get all data Production Order (20 data) when searh report with Order Type parameter", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/json",
        orderTypeId: dataProcessType1.orderTypeId
    };
    manager.getReport(query)
        .then(docs => {
            var data = docs.data;
            data.should.be.instanceof(Array);
            data.length.should.equal(20);
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#09. should success get all data Production Order (10 data) when searh report with Process Type parameter", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/json",
        processTypeId: dataProcessType1._id
    };
    manager.getReport(query)
        .then(docs => {
            var data1 = docs.data;
            data1.should.be.instanceof(Array);
            data1.length.should.equal(10);
            manager.getReport({ processTypeId: dataProcessType2._id })
                .then(docs => {
                    var data2 = docs.data;
                    data2.should.be.instanceof(Array);
                    // data2.length.should.equal(10);
                    done();
                })
                .catch(e => {
                    done(e);
                });
        })
        .catch(e => {
            done(e);
        });
});

it("#10. should success get all data Production Order (10 data) when searh report with buyer parameter", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/json",
        buyerId: dataBuyer1._id
    };
    manager.getReport(query)
        .then(docs => {
            var data1 = docs.data;
            data1.should.be.instanceof(Array);
            data1.length.should.equal(10);
            manager.getReport({ buyerId: dataBuyer2._id })
                .then(docs => {
                    var data2 = docs.data;
                    data2.should.be.instanceof(Array);
                    // data2.length.should.equal(10);
                    done();
                })
                .catch(e => {
                    done(e);
                });
        })
        .catch(e => {
            done(e);
        });
});

it("#11. should success get all data Production Order (10 data) when searh report with account parameter", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/json",
        accountId: dataAccount1._id
    };
    manager.getReport(query)
        .then(docs => {
            var data1 = docs.data;
            data1.should.be.instanceof(Array);
            data1.length.should.equal(10);
            manager.getReport({ accountId: dataAccount2._id })
                .then(docs => {
                    var data2 = docs.data;
                    data2.should.be.instanceof(Array);
                    // data2.length.should.equal(10);
                    done();
                })
                .catch(e => {
                    done(e);
                });
        })
        .catch(e => {
            done(e);
        });
});

it("#12. should success get all data Sales Monthly when searh report with No parameter", function (done) {
    var query = {
        header: "application/json",
        orderNo: orderNo
    };
    manager.getSalesMonthlyReport(query)
        .then(docs => {
            var data = docs.data;
            data.should.be.instanceof(Array);
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#13. should success get all data Sales Monthly when searh report with Account parameter", function (done) {
    var query = {
        header: "application/json",
        accountId: dataAccount1._id
    };
    manager.getSalesMonthlyReport(query)
        .then(docs => {
            var data = docs.data;
            data.should.be.instanceof(Array);
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#14. should success get all data Sales Monthly when searh report with Order Type parameter", function (done) {
    var query = {
        header: "application/json",
        orderTypeId: dataProcessType1.orderTypeId
    };
    manager.getSalesMonthlyReport(query)
        .then(docs => {
            var data = docs.data;
            data.should.be.instanceof(Array);
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#15. should success when destroy all data Production Order", function (done) {
    var destroyData = [];
    for (var id of scId) {
        var data = manager.destroy(id);
        destroyData.push(data);
    }
    Promise.all(destroyData)
        .then(results => {
            results.should.be.instanceof(Array);
            for (var result of results)
                result.should.equal(true);
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#16. should success when create daily operation", function (done) {
    var data = dailyOperationUtil.getNewTestData("input");
    Promise.all([data])
        .then(results => {
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#17. should success get all data Production Order when search report without parameter", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/json",
        filter: {}
    };
    manager.getReport(query)
        .then(docs => {
            var data = docs.data;
            data.should.be.instanceof(Array);
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#18. should success get all data Production Order when search report without parameter (header : application/xls)", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/xls",
        salesContractNo: "",
        orderNo: "",
        orderTypeId: "",
        processTypeId: "",
        buyerId: "",
        accountId: "",
        sdate: "",
        edate: "",
        filter: {}

    };
    manager.getReport(query)
        .then(docs => {
            var data = docs.data;
            data.should.be.instanceof(Array);
            done();
        })
        .catch(e => {
            done(e);
        });
});

<commit_msg>Update Unit Test Production Order<commit_after>require("should");
var dataUtil = require("../../data-util/sales/production-order-data-util");
var fpSCdataUtil = require("../../data-util/sales/finishing-printing-sales-contract-data-util");
var processTypeDataUtil = require("../../data-util/master/process-type-data-util");
var buyerDataUtil = require("../../data-util/master/buyer-data-util");
var accountDataUtil = require("../../data-util/auth/account-data-util");
var dailyOperationUtil = require("../../data-util/production/finishing-printing/daily-operation-data-util");
var fabricQualityControlUtil = require("../../data-util/production/finishing-printing/fabric-quality-control-data-util");
var helper = require("../../helper");
var validate = require("dl-models").validator;
var codeGenerator = require('../../../src/utils/code-generator');

var ProcessTypeManager = require("../../../src/managers/master/process-type-manager");
var fpSCManager = require("../../../src/managers/sales/finishing-printing-sales-contract-manager");
var BuyerManager = require("../../../src/managers/master/buyer-manager");
var AccountManager = require("../../../src/managers/auth/account-manager");
var ProductionOrderManager = require("../../../src/managers/sales/production-order-manager");
var manager = null;
var processTypeManager = null;
var buyerManager = null;
var accountManager = null;

before('#00. connect db', function (done) {
    helper.getDb()
        .then(db => {
            manager = new ProductionOrderManager(db, { username: 'dev' });
            processTypeManager = new ProcessTypeManager(db, { username: 'dev' });
            buyerManager = new BuyerManager(db, { username: 'dev' });
            accountManager = new AccountManager(db, { username: 'dev' });
            fpSCManager = new fpSCManager(db, { username: 'dev' });
            done();
        })
        .catch(e => {
            done(e);
        });
});
var dataBuyer1;
var dataBuyer2;
var dataProcessType1;
var dataProcessType2;
var dataAccount1;
var dataAccount2;
var fpSC;

it("#01. should success when create new support data (buyer, account, process type)", function (done) {
    var processType1 = processTypeDataUtil.getNewData();
    var buyer1 = buyerDataUtil.getNewData();
    var account1 = accountDataUtil.getNewData();
    Promise.all([processType1, buyer1, account1])
        .then(data1 => {
            var processType2 = processTypeDataUtil.getNewData();
            var buyer2 = buyerDataUtil.getNewData();
            var account2 = accountDataUtil.getNewData();
            Promise.all([processType2, buyer2, account2])
                .then(data2 => {
                    Promise.all([processTypeManager.create(data1[0]), processTypeManager.create(data2[0]), buyerManager.create(data1[1]), buyerManager.create(data2[1]), accountManager.create(data1[2]), accountManager.create(data2[2])])
                        .then(id => {
                            Promise.all([processTypeManager.getSingleById(id[0]), processTypeManager.getSingleById(id[1]), buyerManager.getSingleById(id[2]), buyerManager.getSingleById(id[3]), accountManager.getSingleById(id[4]), accountManager.getSingleById(id[5])])
                                .then(results => {
                                    validate.master.processType(results[0]);
                                    dataProcessType1 = results[0];
                                    validate.master.processType(results[1]);
                                    dataProcessType2 = results[1];
                                    validate.master.buyer(results[2]);
                                    dataBuyer1 = results[2];
                                    validate.master.buyer(results[3]);
                                    dataBuyer2 = results[3];
                                    validate.auth.account(results[4]);
                                    dataAccount1 = results[4];
                                    validate.auth.account(results[5]);
                                    dataAccount2 = results[5];
                                    done();
                                })
                                .catch(e => {
                                    done(e);
                                });
                        })
                        .catch(e => {
                            done(e);
                        });
                })
                .catch(e => {
                    done(e);
                });
        })
        .catch(e => {
            done(e);
        });
});

var createdSCId;
var createdSCdata;
it("#01.5. should success when create SalesContract", function (done) {
    fpSCdataUtil.getNewData()
        .then((data) => {
            createdSCdata = data;
            fpSCManager.create(data)
                .then((id) => {
                    return fpSCManager.getSingleById(id);
                })
                .then(sc => {
                    createdSCdata = sc;
                    done();
                })
                .catch((e) => {
                    done(e);
                });
        });
})

it("#02. should success when delete all exist data production order", function (done) {
    manager.read({ size: 100 })
        .then(results => {
            if (results.data.length === 0) {
                done();
            } else {
                var destroyData = [];
                for (var pOrder of results.data) {
                    var des = manager.destroy(pOrder._id);
                    destroyData.push(des);
                }
                if (destroyData.length === 0) {
                    done();
                } else {
                    Promise.all(destroyData)
                        .then(data => {
                            data.should.be.instanceof(Array);
                            for (var a of data)
                                a.should.equal(true);
                            done();
                        })
                        .catch(e => {
                            done(e);
                        });
                }
            }
        })
        .catch(e => {
            done(e);
        });
});

it("#03. should success get all data Production Order (0 data) when searh report without parameter", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/json",
        filter: {}
    };
    manager.getReport(query)
        .then(docs => {
            var data = docs.data;
            console.log(data);
            data.should.be.instanceof(Array);
            done();
        })
        .catch(e => {
            done(e);
        });
});

var scId = [];
var selesContractNo;
var orderNo;
it("#04. should success when create new 10 data Production Order with 2 detail color in each data production order", function (done) {
    var dataReport = [];
    for (var a = 0; a < 5; a++) {
        var data = dataUtil.getNewData({ buyer: dataBuyer1, process: dataProcessType1, account: dataAccount1, salesContract: createdSCdata });
        dataReport.push(data);
    }
    for (var a = 0; a < 5; a++) {
        var data = dataUtil.getNewData({ buyer: dataBuyer2, process: dataProcessType2, account: dataAccount2, salesContract: createdSCdata });
        dataReport.push(data);
    }
    Promise.all(dataReport)
        .then(dataResults => {
            var createData = [];
            var numberIndex = 0;
            for (var a of dataResults) {
                numberIndex++;
                var code = codeGenerator();
                a.salesContractNo = createdSCdata.salesContractNo;
                a.salesContractId = createdSCdata._id;
                a.orderNo = `${code}${numberIndex}`;
                var dataProdOrder = manager.create(a);
                createData.push(dataProdOrder);
                salesContractNo = a.salesContractNo;
                orderNo = a.orderNo;
            }
            Promise.all(createData)
                .then(created => {
                    scId = created;
                    done();
                })
                .catch(e => {
                    done(e);
                });
        })
        .catch(e => {
            done(e);
        });
});

it("#05. should success get all data Production Order when searh report without parameter", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/json",
        filter: {}
    };
    manager.getReport(query)
        .then(docs => {
            var data = docs.data;
            data.should.be.instanceof(Array);
            data.length.should.equal(20);
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#06. should success get all data Production Order (2 data) when searh report with Sales Contract No parameter", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/json",
        filter: { salesContractNo: salesContractNo }
    };
    manager.getReport(query)
        .then(docs => {
            var data = docs.data;
            data.should.be.instanceof(Array);
            data.length.should.equal(20);
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#07. should success get all data Production Order (2 data) when searh report with Order No parameter", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/json",
        orderNo: orderNo
    };
    manager.getReport(query)
        .then(docs => {
            var data = docs.data;
            data.should.be.instanceof(Array);
            data.length.should.equal(2);
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#08. should success get all data Production Order (20 data) when searh report with Order Type parameter", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/json",
        orderTypeId: dataProcessType1.orderTypeId
    };
    manager.getReport(query)
        .then(docs => {
            var data = docs.data;
            data.should.be.instanceof(Array);
            data.length.should.equal(20);
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#09. should success get all data Production Order (10 data) when searh report with Process Type parameter", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/json",
        processTypeId: dataProcessType1._id
    };
    manager.getReport(query)
        .then(docs => {
            var data1 = docs.data;
            data1.should.be.instanceof(Array);
            data1.length.should.equal(10);
            manager.getReport({ processTypeId: dataProcessType2._id })
                .then(docs => {
                    var data2 = docs.data;
                    data2.should.be.instanceof(Array);
                    // data2.length.should.equal(10);
                    done();
                })
                .catch(e => {
                    done(e);
                });
        })
        .catch(e => {
            done(e);
        });
});

it("#10. should success get all data Production Order (10 data) when searh report with buyer parameter", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/json",
        buyerId: dataBuyer1._id
    };
    manager.getReport(query)
        .then(docs => {
            var data1 = docs.data;
            data1.should.be.instanceof(Array);
            data1.length.should.equal(10);
            manager.getReport({ buyerId: dataBuyer2._id })
                .then(docs => {
                    var data2 = docs.data;
                    data2.should.be.instanceof(Array);
                    // data2.length.should.equal(10);
                    done();
                })
                .catch(e => {
                    done(e);
                });
        })
        .catch(e => {
            done(e);
        });
});

it("#11. should success get all data Production Order (10 data) when searh report with account parameter", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/json",
        accountId: dataAccount1._id
    };
    manager.getReport(query)
        .then(docs => {
            var data1 = docs.data;
            data1.should.be.instanceof(Array);
            data1.length.should.equal(10);
            manager.getReport({ accountId: dataAccount2._id })
                .then(docs => {
                    var data2 = docs.data;
                    data2.should.be.instanceof(Array);
                    // data2.length.should.equal(10);
                    done();
                })
                .catch(e => {
                    done(e);
                });
        })
        .catch(e => {
            done(e);
        });
});

it("#12. should success get all data Sales Monthly when searh report with No parameter", function (done) {
    var query = {
        header: "application/json",
        orderNo: orderNo
    };
    manager.getSalesMonthlyReport(query)
        .then(docs => {
            var data = docs.data;
            data.should.be.instanceof(Array);
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#13. should success get all data Sales Monthly when searh report with Account parameter", function (done) {
    var query = {
        header: "application/json",
        accountId: dataAccount1._id
    };
    manager.getSalesMonthlyReport(query)
        .then(docs => {
            var data = docs.data;
            data.should.be.instanceof(Array);
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#14. should success get all data Sales Monthly when searh report with Order Type parameter", function (done) {
    var query = {
        header: "application/json",
        orderTypeId: dataProcessType1.orderTypeId
    };
    manager.getSalesMonthlyReport(query)
        .then(docs => {
            var data = docs.data;
            data.should.be.instanceof(Array);
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#15. should success when destroy all data Production Order", function (done) {
    var destroyData = [];
    for (var id of scId) {
        var data = manager.destroy(id);
        destroyData.push(data);
    }
    Promise.all(destroyData)
        .then(results => {
            results.should.be.instanceof(Array);
            for (var result of results)
                result.should.equal(true);
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#16. should success when create daily operation", function (done) {
    var data = dailyOperationUtil.getNewTestData("input");
    Promise.all([data])
        .then(results => {
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#17. should success get all data Production Order when search report without parameter", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/json",
        filter: {}
    };
    manager.getReport(query)
        .then(docs => {
            var data = docs.data;
            data.should.be.instanceof(Array);
            done();
        })
        .catch(e => {
            done(e);
        });
});

it("#18. should success get all data Production Order when search report without parameter (header : application/xls)", function (done) {
    var query = {
        page: 1,
        size: 20,
        header: "application/xls",
        salesContractNo: "",
        orderNo: "",
        orderTypeId: "",
        processTypeId: "",
        buyerId: "",
        accountId: "",
        sdate: "",
        edate: "",
        filter: {}

    };
    manager.getReport(query)
        .then(docs => {
            var data = docs.data;
            data.should.be.instanceof(Array);
            done();
        })
        .catch(e => {
            done(e);
        });
});

<|endoftext|>


<commit_before>var prana  = require('prana');
var mkdirp = require('mkdirp');
var lodash = require('lodash');

/**
 * Create a directory recursivelly.
 *
 * @param dir Directory to create.
 * @param [mode] Permissions string, default to 0777 & umask.
 * @param callback Function to call.
 */
prana.utils.mkdir = mkdirp;

// Wrap lodash arround Prana utils.
lodash.extend(prana.utils, lodash);
<commit_msg>Remove dumb whitespace;<commit_after>var prana = require('prana');
var mkdirp = require('mkdirp');
var lodash = require('lodash');

/**
 * Create a directory recursivelly.
 *
 * @param dir Directory to create.
 * @param [mode] Permissions string, default to 0777 & umask.
 * @param callback Function to call.
 */
prana.utils.mkdir = mkdirp;

// Wrap lodash arround Prana utils.
lodash.extend(prana.utils, lodash);
<|endoftext|>


<commit_before>'use strict';

var git = require('../')

console.log('git.short() => ' + git.short());
// 75bf4ee

console.log('git.long() => ' + git.long());
// 75bf4eea9aa1a7fd6505d0d0aa43105feafa92ef

console.log('git.branch() => ' + git.branch());
// master

console.log('git.tag() => ' + git.tag());
// master
<commit_msg>clarify example comments<commit_after>'use strict';

var git = require('../')

console.log('git.short() => ' + git.short());
// e.g. 75bf4ee

console.log('git.long() => ' + git.long());
// e.g. 75bf4eea9aa1a7fd6505d0d0aa43105feafa92ef

console.log('git.branch() => ' + git.branch());
// e.g. master

console.log('git.tag() => ' + git.tag());
// e.g. v1.4.0
<|endoftext|>