<commit_before>var v = require( '../../src/validation' )();

describe( 'validation/index.js', function () {
    describe( 'validateField', function () {
        var fldID   = 'test';
        var fldMeta = { renderer: 'text', validators: [] };

        it2( 'should return `null` instead of errors array if ',
            '`validators` are unset', function () {
            expect( v.validateField( fldID, fldMeta, null ) )
                .toEqual({ 'test': null });
        });

        it2( 'should return array with errors if `validators` ',
             'are set and value is not valid', function () {
            var validators = [{ rule: 'required', message: 'err' }];
            fldMeta.validators = validators;

            expect( v.validateField( fldID, fldMeta, null ) )
                .toEqual({ 'test': validators });
        });

        it2( 'should return array with errors only ',
             'from failed validators', function () {
            var validators = [{ rule: 'required', message: 'err1' },
                              { rule: 'length', value: 5, message: 'err2' }];
            fldMeta.validators = validators;

            expect( v.validateField( fldID, fldMeta, 'test' ) )
                .toEqual({ 'test': [ validators[1] ] });

            expect( v.validateField( fldID, fldMeta, null ) )
                .toEqual({ 'test': validators });
        });
    });

    describe( 'validateForm', function () {
        var formMeta = {
            fields: {
                field1: { renderer: 'text', validators: [] }
            }
        };

        var fldMeta = formMeta.fields.field1;

        it2( 'should return `null` instead of errors array if ',
            '`validators` are unset', function () {
            expect( v.validateForm( formMeta, null ) )
                .toEqual({ 'field1': null });

            expect( v.validateForm( formMeta, { field1: '42' } ) )
                .toEqual({ 'field1': null });
        });

        it2( 'should return array with errors if `validators` ',
             'are set and value is not valid', function () {
            var validators = [{ rule: 'required', message: 'err' }];
            fldMeta.validators = validators;

            expect( v.validateForm( formMeta, null ) )
                .toEqual({ 'field1': validators });
        });

        it2( 'should return array with errors only ',
             'from failed validators', function () {
            var validators = [{ rule: 'required', message: 'err1' },
                              { rule: 'length', value: 5, message: 'err2' }];
            fldMeta.validators = validators;

            expect( v.validateForm( formMeta, { field1: '42' } ) )
                .toEqual({ 'field1': [ validators[1] ] });

            expect( v.validateForm( formMeta, { field1: null } ) )
                .toEqual({ 'field1': validators });
        });
    });

});

function ms () {
    return Array.prototype.join.call( arguments, '' );
}

function it2 () {
    var ss = Array.prototype.slice.call( arguments, 0, -1 );
    var fn = Array.prototype.slice.call( arguments, -1 )[ 0 ];

    return it(ms.apply( null, ss ), fn );
}
<commit_msg>Update unit-tests for validation<commit_after>var v = require( '../../src/validation' )();

describe( 'validation/index.js', function () {
    describe( 'validateField', function () {
        var fldID   = 'test';
        var fldMeta = { renderer: 'text', validators: [] };

        it2( 'should return `null` instead of errors array if ',
            '`validators` are unset', function () {
            expect( v.validateField( fldID, fldMeta, null ) )
                .toEqual({ 'test': null });
        });

        it2( 'should return array with errors if `validators` ',
             'are set and value is not valid', function () {
            var validators = [{ rule: 'required', message: 'err' }];
            fldMeta.validators = validators;

            expect( v.validateField( fldID, fldMeta, null ) )
                .toEqual({ 'test': validators });
        });

        it2( 'should return array with errors only ',
             'from failed validators', function () {
            var validators = [{ rule: 'required', message: 'err1' },
                              { rule: 'length', value: 5, message: 'err2' }];
            fldMeta.validators = validators;

            expect( v.validateField( fldID, fldMeta, 'test' ) )
                .toEqual({ 'test': [ validators[1] ] });

            expect( v.validateField( fldID, fldMeta, null ) )
                .toEqual({ 'test': validators });
        });
    });

    describe( 'validateForm', function () {
        var formMeta = {
            fields: {
                field1: { renderer: 'text', validators: [] }
            }
        };

        var fldMeta = formMeta.fields.field1;

        it2( 'should return `null` instead of errors array if ',
            '`validators` are unset', function () {
            expect( v.validateForm( formMeta, null ) )
                .toEqual({ 'field1': null });

            expect( v.validateForm( formMeta, { field1: '42' } ) )
                .toEqual({ 'field1': null });
        });

        it2( 'should return array with errors if `validators` ',
             'are set and value is not valid', function () {
            var validators = [{ rule: 'required', message: 'err' }];
            fldMeta.validators = validators;

            expect( v.validateForm( formMeta, null ) )
                .toEqual({ 'field1': validators });
        });

        it2( 'should return array with errors only ',
             'from failed validators', function () {
            var validators = [{ rule: 'required', message: 'err1' },
                              { rule: 'length', value: 5, message: 'err2' }];
            fldMeta.validators = validators;

            expect( v.validateForm( formMeta, { field1: '42' } ) )
                .toEqual({ 'field1': [ validators[1] ] });

            expect( v.validateForm( formMeta, { field1: null } ) )
                .toEqual({ 'field1': validators });
        });
    });

    describe( 'isFormValid', function () {
        it( 'should return `true` if array of errors is null', function () {
            expect( v.isFormValid(null) ).toEqual( true );
        });

        it( 'should return `true` if array of errors is empty', function () {
            expect( v.isFormValid({}) ).toEqual( true );
        });

        it2( 'should return `true` if array of errors ',
             'contains only empty keys', function () {
            expect( v.isFormValid({ test: [] }) ).toEqual( true );
        });

        it2( 'should return `false` if array of errors ',
             'contains non-empty keys', function () {
            expect( v.isFormValid({ test: [1] }) ).toEqual( false );
        });
    });

});

function ms () {
    return Array.prototype.join.call( arguments, '' );
}

function it2 () {
    var ss = Array.prototype.slice.call( arguments, 0, -1 );
    var fn = Array.prototype.slice.call( arguments, -1 )[ 0 ];

    return it(ms.apply( null, ss ), fn );
}
<|endoftext|>


<commit_before>var MapModel = require('../models/map');
var _ = require('underscore');

module.exports = {
	post: function(req, res) {
		var map = {
			name: req.body.name,
			game: req.body.game,
			imageURL: req.body.imageURL,
			top: req.body.top,
			bottom: req.body.bottom
			left: req.body.left,
			right: req.body.right
		}

		var mapModel = new MapModel(map);

		mapModel.save(function(err) {
			if (err) {
				console.log(err);
			} else {
				return console.log('saved');
			}
		});

		res.send('added');
	},
	get: function(req, res) {
		return MapModel.find({}, function(err, maps){
			if (err) {
				console.log(err);
			} else {
				return res.send(maps);
			}
		})
	},
	put: function(req, res) {
		console.log(req.params.id);
		return MapModel.findById(req.params.id, function(err, map){

			map.name = req.body.name;
			map.game = req.body.game;
			map.imageURL = req.body.imageURL;
			map.top = req.body.top;
			map.bottom = req.body.bottom;
			map.left = req.body.left;
			map.right = req.body.right;

			return map.save(function(err) {
				if (err) {
					console.log(err);
				} else {
					console.log('map updated')
				}
				return res.send(map);
			});
		});
	},
	delete: function(req, res) {
        return MapModel.findById(req.params.id, function(err, map) {
            return map.remove(function(err) {
                if (err) {
                    console.log(err);
                } else {
                    res.send('Deleted Map ' + req.params.id);
                }
            });
        })
    },

}<commit_msg>Fix comma<commit_after>var MapModel = require('../models/map');
var _ = require('underscore');

module.exports = {
	post: function(req, res) {
		var map = {
			name: req.body.name,
			game: req.body.game,
			imageURL: req.body.imageURL,
			top: req.body.top,
			bottom: req.body.bottom,
			left: req.body.left,
			right: req.body.right
		}

		var mapModel = new MapModel(map);

		mapModel.save(function(err) {
			if (err) {
				console.log(err);
			} else {
				return console.log('saved');
			}
		});

		res.send('added');
	},
	get: function(req, res) {
		return MapModel.find({}, function(err, maps){
			if (err) {
				console.log(err);
			} else {
				return res.send(maps);
			}
		})
	},
	put: function(req, res) {
		console.log(req.params.id);
		return MapModel.findById(req.params.id, function(err, map){

			map.name = req.body.name;
			map.game = req.body.game;
			map.imageURL = req.body.imageURL;
			map.top = req.body.top;
			map.bottom = req.body.bottom;
			map.left = req.body.left;
			map.right = req.body.right;

			return map.save(function(err) {
				if (err) {
					console.log(err);
				} else {
					console.log('map updated')
				}
				return res.send(map);
			});
		});
	},
	delete: function(req, res) {
        return MapModel.findById(req.params.id, function(err, map) {
            return map.remove(function(err) {
                if (err) {
                    console.log(err);
                } else {
                    res.send('Deleted Map ' + req.params.id);
                }
            });
        })
    },

}<|endoftext|>


<commit_before>var React = require("react")
var Dispatcher = require('flux').Dispatcher

var classNames = require('classnames')

// TODO: split these POC components into separate modules like the flux todomvc example

function get(url,params) {
    return new Promise(function(resolve,reject){
        if (params) {
            url += '?' + Object.keys(params).map((key) => {
                return key + "="+params[key]
            }) .join("&")
        }

        var xhr =  new XMLHttpRequest()
        xhr.open("GET",url,true)
        xhr.responseType = 'json'

        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4)

                switch (xhr.status) {
                    case 200:
                        // hack to detect if session has expired
                        if (xhr.responseURL.match('/accounts/login/')) {
                            return document.location.href = '/accounts/login/?next='+document.location.pathname
                        }

                        return resolve(xhr.response)
                    case 500:
                        alert('Internal server error')
                        // fall...
                    default:
                        console.log(xhr.status,xhr)
                        reject(xhr.status)
                }
        }

        xhr.onerror = function(error) {
            console.log(error)
            reject(error)
        }

        xhr.send()
    })
}

class Loading extends React.Component {
    render() {
        return (

        )
    }
}

class SearchBox extends React.Component {
    componentDidMount() {
        this.refs.search.getDOMNode.focus()
    }
    render() {
        return
            <form>
                <input ref="search" type="text" placeholder="Search..."/>
            </form>

    }
}

class Album extends React.Component {
    // square placeholder is used for non-deterministic height -- stops many reflows on load.
    constructor() {
        this.state = {'loaded':false}
        // automate this: http://www.newmediacampaigns.com/blog/refactoring-react-components-to-es6-classes
        this.swapImg = this.swapImg.bind(this) // TODO this elsewhere instead of passing parent this
    }

    swapImg() {
        this.setState({loaded:true})
    }

    render() {
        var imgstyle = {display:this.state.loaded?'block':'none'}
        var plcstyle = {display:this.state.loaded?'none':'block'}

        return (

{this.props.name}

{this.props.artist}

        )
    }
}

class AZ extends React.Component {
    // TODO use purecss.io primitives for this
    constructor(props) {
        this.alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
    }

    updateChar(char) {
        this.props.onCharChange(char)
    }

    render() {
        return (

                    {
                        this.alphabet.map((char,i) => {
                            var classes = classNames('pure-menu-item',{
                                'pure-menu-selected' : char == this.props.selected,
                            })
                            return

                                {char}

                        })
                    }

        )
    }

}

class Browser extends React.Component {
    constructor(props) {
        super(props)
        this.state = {albums:[]}
        // override 'this' when used as callback fired from child Component
        this.updateChar = this.updateChar.bind(this)
    }

    componentDidMount() {
        this.loadFromAPI({order_by:'name'})
    }

    updateChar(char) {
        // TODO change query based on property, see comments
        this.setState({char:char})
        this.loadFromAPI({
            name__istartswith : char,
            order_by : 'name',
            //artist_istartswith=A,
            //order_by=artist
        })
    }

    loadFromAPI(query) {
        // what's that fat arrow?
        // for lexical this
        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
        this.setState({
            loading:true,
            albums:[]
        })
        get('/albums',query).then((albums) => {
            this.setState({
                albums: albums,
                loading: false,
            })
        })
    }

    render() {
        // TODO passing parent 'this' is strange. Flux time?
        return (

                <AZ onCharChange={this.updateChar} selected={this.state.char} parent={this} />
                { this.state.loading? <Loading /> :''}
                { !this.state.albums.length && !this.state.loading ? 'No results.' : ''}

                    {
                        this.state.albums.map((props) => {
                            return <Album {...props} key={props.id} />
                        })
                    }

        )
    }
}

React.render(
    //<Albums name__startswith="B" />,
    //<AZ onClick={(char)=>{console.log(char)}}/>,
    <Browser />,
    document.getElementById('main')
)

//window.onload = function() {
//    return
//    get('/albums').then(function(albums) {
//        console.log(albums)
//    })
//}
<commit_msg>start repeat query mech<commit_after>var React = require("react")
var Dispatcher = require('flux').Dispatcher

var classNames = require('classnames')

// TODO: split these POC components into separate modules like the flux todomvc example

function get(url,params) {
    return new Promise(function(resolve,reject){
        if (params) {
            url += '?' + Object.keys(params).map((key) => {
                return key + "="+params[key]
            }) .join("&")
        }

        var xhr =  new XMLHttpRequest()
        xhr.open("GET",url,true)
        xhr.responseType = 'json'

        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4)

                switch (xhr.status) {
                    case 200:
                        // hack to detect if session has expired
                        if (xhr.responseURL.match('/accounts/login/')) {
                            return document.location.href = '/accounts/login/?next='+document.location.pathname
                        }

                        return resolve(xhr.response)
                    case 500:
                        alert('Internal server error')
                        // fall...
                    default:
                        console.log(xhr.status,xhr)
                        reject(xhr.status)
                }
        }

        xhr.onerror = function(error) {
            console.log(error)
            reject(error)
        }

        xhr.send()
    })
}

class Loading extends React.Component {
    render() {
        return (

        )
    }
}

class SearchBox extends React.Component {
    componentDidMount() {
        this.refs.search.getDOMNode.focus()
    }
    render() {
        return
            <form>
                <input ref="search" type="text" placeholder="Search..."/>
            </form>

    }
}

class Album extends React.Component {
    // square placeholder is used for non-deterministic height -- stops many reflows on load.
    constructor() {
        this.state = {'loaded':false}
        // automate this: http://www.newmediacampaigns.com/blog/refactoring-react-components-to-es6-classes
        this.swapImg = this.swapImg.bind(this) // TODO this elsewhere instead of passing parent this
    }

    swapImg() {
        this.setState({loaded:true})
    }

    render() {
        var imgstyle = {display:this.state.loaded?'block':'none'}
        var plcstyle = {display:this.state.loaded?'none':'block'}

        return (

{this.props.name}

{this.props.artist}

        )
    }
}

class AZ extends React.Component {
    // TODO use purecss.io primitives for this
    constructor(props) {
        this.alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
    }

    updateChar(char) {
        this.props.onCharChange(char)
    }

    render() {
        return (

                    {
                        this.alphabet.map((char,i) => {
                            var classes = classNames('pure-menu-item',{
                                'pure-menu-selected' : char == this.props.selected,
                            })
                            return

                                {char}

                        })
                    }

        )
    }

}

class AlbumBrowser extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            albums:[],
            loading:true,
            exhausted:false,
            current_query:{},
            current_page:0,
        }
        // override 'this' when used as callback fired from child Component
        this.updateChar = this.updateChar.bind(this)
        this.autoScroll = this.autoScroll.bind(this)
    }

    componentDidMount() {
        this.loadFromAPI({order_by:'name'})
    }

    updateChar(char) {
        // TODO change query based on property, see comments
        this.setState({
            char:char,
            albums:[],
        })
        this.loadFromAPI({
            name__istartswith : char,
            order_by : 'name',
            //artist_istartswith=A,
            //order_by=artist
        })
    }

    autoScroll() {
        if (this.state.loading || this.state.exhausted)
            return

        this.loadFromAPI(this.state.current_query)
    }

    loadFromAPI(query) {
        // what's that fat arrow?
        // for lexical this
        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
        this.setState({
            loading:true,
            current_query:query,
        })
        get('/albums',query).then((albums) => {
            this.setState({
                albums: this.state.albums.concat(albums),
                loading: false,
                exhausted: !!albums.length,
            })
        })
    }

    render() {
        // TODO passing parent 'this' is strange. Flux time?
        return (

                <AZ onCharChange={this.updateChar} selected={this.state.char} parent={this} />
                { this.state.loading? <Loading /> :''}
                { !this.state.albums.length && !this.state.loading ? 'No results.' : ''}

                    {
                        this.state.albums.map((props) => {
                            return <Album {...props} key={props.id} />
                        })
                    }

        )
    }
}

React.render(
    //<Albums name__startswith="B" />,
    //<AZ onClick={(char)=>{console.log(char)}}/>,
    <AlbumBrowser />,
    document.getElementById('main')
)

//window.onload = function() {
//    return
//    get('/albums').then(function(albums) {
//        console.log(albums)
//    })
//}
<|endoftext|>


<commit_before>/**
 * BarrelController
 *
 * @description :: Server-side logic for managing Barrels
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {

    /**
     * @api {get} /barrel
     * @apiName find
     * @apiGroup Barrel
     * @apiDescription Get the list of all barrel according to permissions.
     *
     * @apiSuccess {Array} An array of barrel
     *
     * @apiUse forbiddenError
     */
    find: (req, res) => {

        // Check permissions
        if (!(Team.can(req, 'barrel/admin') || Team.can(req, 'barrel/restricted'))) {
            return res.error(403, 'forbidden', 'You are not authorized to read barrels.');
        }

        // read filters
        let where = {};
        if (req.allParams().filters) {
            where = req.allParams().filters;
        }
        // if the requester is not admin, show only his team's barrels
        if (!(Team.can(req, 'barrel/admin'))) {
            where.place = req.team.id;
        }

        // Find barrels
        Barrel.find(where)
            .exec((error, barrels) => {
                if (error) {
                    return res.negotiate(error);
                }

                Barrel.subscribe(req, _.pluck(barrels, 'id'));
                Barrel.watch(req);

                return res.ok(barrels);
            });

    },

    /**
     * @api {put} /barrel/:id
     * @apiName update
     * @apiGroup Barrel
     * @apiDescription Update the given barrel
     *
     * @apiParam {string} id : Id of the barrel to edit (required)
     * @apiParam {string} state : The new barrel state (required)
     *
     * @apiSuccess {Barrel} The barrel that you've just updated
     *
     * @apiUse forbiddenError
     * @apiUse notFoundError
     */
    update: (req, res) => {

        let checkState = false;

        // check permissions and parameters
        if (Team.can(req, 'barrel/admin')) {
            // an admin can update both place and state
            if (req.param('state') === undefined && req.param('place') === undefined) {
                return res.error(400, 'BadRequest', "You must send attributes to update.");
            }
        } else if (Team.can(req, 'barrel/restricted')) {
            // can only update the barrel's state
            if (req.param('state') === undefined) {
                return res.error(400, 'BadRequest', "Missing barrel's state.");
            }
        } else if (!Team.can(req, 'barrel/admin')) {
            return res.error(403, 'forbidden', 'You are not authorized to update barrels.');
        }

        Barrel.findOne({id: req.param('id')})
            .exec((error, barrel) => {
                if (error) {
                    return res.negotiate(error);
                }
                if (!barrel) {
                    return res.error(404, 'notFound', 'The requested barrel cannot be found');
                }

                // if the requester is not admin, check if the barrel belongs to his team
                if (!Team.can(req, 'barrel/admin') && (req.team.id !== barrel.place)) {
                    return res.error(403, 'forbidden', 'You are not authorized to update this barrel.');
                }

                // if the requester sent a new value for the 'state' attribute
                if (req.param('state') !== undefined) {
                    // check if the state can be set with this new value (next or previous state).
                    // because it's not allowed to move from new to empty for example
                    if (!isStateValid(req.param('state'), barrel.state)) {
                        return res.error(400, 'BadRequest', "You are not allowed to set the state with this value.");
                    }
                    // check if an alert has to be sent or removed
                    if ((barrel.state === "new" && req.param("state") === "opened") || (barrel.state === "opened" && req.param("state") === "new")) {
                        checkState = true;
                    }
                    // set the state
                    barrel.state = req.param('state');
                }

                // if admin and send a new value for the 'place' attribute
                if (req.param('place') !== undefined && Team.can(req, 'barrel/admin')) {
                    // the place can be null
                    if (req.param('place') === "null" || req.param('place') === null) {
                        barrel.place = null;
                        return updateBarrel(barrel, req, res, checkState);
                    }
                    // if not null, check if the team exists
                    Team.findOne({id: req.param('place')})
                        .exec((error, team) => {
                            if (error) {
                                return res.negotiate(error);
                            }
                            if(!team) {
                                return res.error(404, 'notfound', 'The requested team cannot be found');
                            }

                            // the team exists, save the barrel with this new place
                            barrel.place = team;
                            return updateBarrel(barrel, req, res, checkState);
                        });
                } else {
                    return updateBarrel(barrel, req, res, checkState);
                }

            });

    },

    /**
     * @api {delete} /barrel/:id
     * @apiName destroy
     * @apiGroup Barrel
     * @apiDescription Delete the given Barrel
     *
     * @apiParam {string} id : Id of the barrel to delete
     *
     * @apiUse forbiddenError
     * @apiUse notFoundError
     */
    destroy: function (req, res) {

        // Check permissions
        if(!Team.can(req, 'barrel/admin')) {
            return res.error(403, 'forbidden', 'You are not authorized to delete a barrel.');
        }

        // Find the barrel
        Barrel.findOne({id: req.param('id')})
            .exec((error, barrel) => {
                if (error) {
                    return res.negotiate(error);
                }
                if(!barrel) {
                    return res.error(404, 'notfound', 'The requested barrel cannot be found');
                }

                Barrel.destroy({id: barrel.id}).exec((error) => {
                    if (error) {
                        return res.negotiate(error);
                    }

                    Barrel.publishDestroy(barrel.id);

                    return res.ok();
                });
            });
    },

    /**
     * @api {put} /barrel/location
     * @apiName updateLocation
     * @apiGroup Barrel
     * @apiDescription update the location of a list of barrels
     *
     * @apiParam {Array} barrels: The barrels to update
     * @apiParem {string} location: the new location
     *
     * @apiUse forbiddenError
     * @apiUse notFoundError
     */
    setLocation: function (req, res) {

        // check permissions
        if (!(Team.can(req, 'barrel/admin'))) {
            return res.error(403, 'forbidden', "You are not authorized to update barrels's location.");
        }

        // check team
        Team.findOne({id: req.param('location')})
            .then(team => {
                // if the location is not the log (null) and the asked team can't be found, return error
                if (req.param('location') !== null && req.param('location') !== "null" && !team) {
                    return res.error(403, 'forbidden', "The location is not valid.");
                }

                // prepare each update
                let promises = [];
                for (let i in req.param('barrels')) {
                    promises.push(new Promise((resolve, reject) => {
                        Barrel.findOne({id: req.param('barrels')[i].id})
                            .then(barrel => {
                                // update his location and save it
                                barrel.place = req.param('location');
                                barrel.save(error => {
                                    if (error) return reject(error);

                                    // log the barrel state
                                    BarrelHistory.pushToHistory(barrel, (error, barrelHistory) => {
                                        if (error) return reject(error);

                                        Barrel.publishUpdate(barrel.id, barrel);
                                        Barrel.subscribe(req, [barrel.id]);

                                        checkTeamStocks(barrel);

                                        return resolve(barrel);

                                    });
                                })
                            })
                            .catch(error => reject(error));
                    }));
                }

                // run all promises
                Promise.all(promises)
                    .then(_ => res.ok())
                    .catch(error => res.negotiate(error));

            })
            .catch(error => res.negotiate(error));

    }

};

/**
 * Check the remaining barrels of this type for the concerned bar.
 * If 1 : send warning alert
 * If 0 : send serious alert
 *
 * @param barrel
 */
function checkTeamStocks(barrel) {

    // if there is a team, get all his barrels of this type
    if (barrel.place) {

        BarrelType.findOne({
            id: barrel.type
        })
            .exec((error, type) => {
                if (error) return;

                // count how many new barrel of this type this the team still have
                Barrel.count({
                    place: barrel.place,
                    type: type.id,
                    state: "new"
                })
                    .exec((error, count) => {
                        if (error) return;

                        // if state is new, check if there is an alert to remove (if a missClick triggered an alert)
                        if (barrel.state === "new") {
                            // count how many barrels are news
                            // if 2 or 1, an alert was created
                            if (count < 3) {
                                // Find the alert sent
                                Alert.findOne({
                                    severity: count === 2 ? "warning" : "serious",
                                    category: "Manque auto",
                                    sender: barrel.place
                                })
                                    .limit(1).sort({$natural:-1})
                                    .exec((error, alert) => {
                                        if (error || !alert) return;

                                        Alert.destroy({id: alert.id}).exec((error) => {
                                            if (error) return;

                                            Alert.publishDestroy(alert.id);
                                        });
                                    });
                            }
                        } else {
                            // if 1 or 0 remaining, create alert
                            if (count < 2) {
                                Alert.create({
                                    sender: barrel.place,
                                    severity: count === 1 ? "warning" : "serious",
                                    title: "Stock : " + type.name,
                                    category: "Manque auto"
                                })
                                    .exec((error, alert) => {
                                        if (error) return;

                                        // push this modification in the alert history
                                        AlertHistory.pushToHistory(alert, (error, result) => {
                                            if (error) return;

                                            Alert.publishCreate(alert);
                                            Alert.subscribe(req, [alert.id]);
                                        });

                                    });
                            }
                        }
                    })

            });
    }
}

/**
 * Save a barrel and push it to the history
 *
 * @param {object} barrel: the barrel to save
 * @param {object} req: the request
 * @param {object} res: the response
 * @param {boolean} checkState: true if the barrel's team stocks have to be check
 */
function updateBarrel(barrel, req, res, checkState) {

    barrel.save((error) => {
        if (error) {
            return res.negotiate(error);
        }

        // log the new barrel state
        BarrelHistory.pushToHistory(barrel, (error, barrelHistory) => {
            if (error) {
                return res.negotiate(error);
            }

            Barrel.publishUpdate(barrel.id, barrel);
            Barrel.subscribe(req, [barrel.id]);

            if (checkState) {
                checkTeamStocks(barrel);
            }

            return res.ok(barrel);

        });
    });
}

/**
 * If only the state is passed in parameter, check if
 * the value of state is valid (in the states array)
 *
 * If currentState too is set, check if it's allowed to move
 * from currentState to state.
 *
 * @param {string} state
 * @param {string|null} currentState
 * @returns {boolean}
 */
function isStateValid(state, currentState) {
    const states = ["new", "opened", "empty"];

    // if no current state, only check if state is in the array
    if (!currentState) {
        return states.indexOf(state) !== -1;
    } else {
        // return false if the state is wrong
        if (states.indexOf(state) === -1) {
            return false;
        }
    }

    // check if it's allowed to set the barrel state with this value (same or neighbor)
    const d = Math.abs(states.indexOf(currentState) - states.indexOf(state))
    return d === 1 || d === 0;
}
<commit_msg>method to update the location of many barrels<commit_after>/**
 * BarrelController
 *
 * @description :: Server-side logic for managing Barrels
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {

    /**
     * @api {get} /barrel
     * @apiName find
     * @apiGroup Barrel
     * @apiDescription Get the list of all barrel according to permissions.
     *
     * @apiSuccess {Array} An array of barrel
     *
     * @apiUse forbiddenError
     */
    find: (req, res) => {

        // Check permissions
        if (!(Team.can(req, 'barrel/admin') || Team.can(req, 'barrel/restricted'))) {
            return res.error(403, 'forbidden', 'You are not authorized to read barrels.');
        }

        // read filters
        let where = {};
        if (req.allParams().filters) {
            where = req.allParams().filters;
        }
        // if the requester is not admin, show only his team's barrels
        if (!(Team.can(req, 'barrel/admin'))) {
            where.place = req.team.id;
        }

        // Find barrels
        Barrel.find(where)
            .exec((error, barrels) => {
                if (error) {
                    return res.negotiate(error);
                }

                Barrel.subscribe(req, _.pluck(barrels, 'id'));
                Barrel.watch(req);

                return res.ok(barrels);
            });

    },

    /**
     * @api {put} /barrel/:id
     * @apiName update
     * @apiGroup Barrel
     * @apiDescription Update the given barrel
     *
     * @apiParam {string} id : Id of the barrel to edit (required)
     * @apiParam {string} state : The new barrel state (required)
     *
     * @apiSuccess {Barrel} The barrel that you've just updated
     *
     * @apiUse forbiddenError
     * @apiUse notFoundError
     */
    update: (req, res) => {

        let checkState = false;

        // check permissions and parameters
        if (Team.can(req, 'barrel/admin')) {
            // an admin can update both place and state
            if (req.param('state') === undefined && req.param('place') === undefined) {
                return res.error(400, 'BadRequest', "You must send attributes to update.");
            }
        } else if (Team.can(req, 'barrel/restricted')) {
            // can only update the barrel's state
            if (req.param('state') === undefined) {
                return res.error(400, 'BadRequest', "Missing barrel's state.");
            }
        } else if (!Team.can(req, 'barrel/admin')) {
            return res.error(403, 'forbidden', 'You are not authorized to update barrels.');
        }

        Barrel.findOne({id: req.param('id')})
            .exec((error, barrel) => {
                if (error) {
                    return res.negotiate(error);
                }
                if (!barrel) {
                    return res.error(404, 'notFound', 'The requested barrel cannot be found');
                }

                // if the requester is not admin, check if the barrel belongs to his team
                if (!Team.can(req, 'barrel/admin') && (req.team.id !== barrel.place)) {
                    return res.error(403, 'forbidden', 'You are not authorized to update this barrel.');
                }

                // if the requester sent a new value for the 'state' attribute
                if (req.param('state') !== undefined) {
                    // check if the state can be set with this new value (next or previous state).
                    // because it's not allowed to move from new to empty for example
                    if (!isStateValid(req.param('state'), barrel.state)) {
                        return res.error(400, 'BadRequest', "You are not allowed to set the state with this value.");
                    }
                    // check if an alert has to be sent or removed
                    if ((barrel.state === "new" && req.param("state") === "opened") || (barrel.state === "opened" && req.param("state") === "new")) {
                        checkState = true;
                    }
                    // set the state
                    barrel.state = req.param('state');
                }

                // if admin and send a new value for the 'place' attribute
                if (req.param('place') !== undefined && Team.can(req, 'barrel/admin')) {
                    // the place can be null
                    if (req.param('place') === "null" || req.param('place') === null) {
                        barrel.place = null;
                        return updateBarrel(barrel, req, res, checkState);
                    }
                    // if not null, check if the team exists
                    Team.findOne({id: req.param('place')})
                        .exec((error, team) => {
                            if (error) {
                                return res.negotiate(error);
                            }
                            if(!team) {
                                return res.error(404, 'notfound', 'The requested team cannot be found');
                            }

                            // the team exists, save the barrel with this new place
                            barrel.place = team;
                            return updateBarrel(barrel, req, res, checkState);
                        });
                } else {
                    return updateBarrel(barrel, req, res, checkState);
                }

            });

    },

    /**
     * @api {delete} /barrel/:id
     * @apiName destroy
     * @apiGroup Barrel
     * @apiDescription Delete the given Barrel
     *
     * @apiParam {string} id : Id of the barrel to delete
     *
     * @apiUse forbiddenError
     * @apiUse notFoundError
     */
    destroy: function (req, res) {

        // Check permissions
        if(!Team.can(req, 'barrel/admin')) {
            return res.error(403, 'forbidden', 'You are not authorized to delete a barrel.');
        }

        // Find the barrel
        Barrel.findOne({id: req.param('id')})
            .exec((error, barrel) => {
                if (error) {
                    return res.negotiate(error);
                }
                if(!barrel) {
                    return res.error(404, 'notfound', 'The requested barrel cannot be found');
                }

                Barrel.destroy({id: barrel.id}).exec((error) => {
                    if (error) {
                        return res.negotiate(error);
                    }

                    Barrel.publishDestroy(barrel.id);

                    return res.ok();
                });
            });
    },

    /**
     * @api {put} /barrel/location
     * @apiName updateLocation
     * @apiGroup Barrel
     * @apiDescription update the location of a list of barrels
     *
     * @apiParam {Array} barrels: The barrels to update
     * @apiParem {string} location: the new location
     *
     * @apiUse forbiddenError
     * @apiUse notFoundError
     */
    setLocation: function (req, res) {

        // check permissions
        if (!(Team.can(req, 'barrel/admin'))) {
            return res.error(403, 'forbidden', "You are not authorized to update barrels's location.");
        }

        // check team
        Team.findOne({id: req.param('location')})
            .exec((error, team) => {
                if (error) return res.negotiate(error);

                // if the location is not the log (null) and the asked team can't be found, return error
                if (req.param('location') !== null && req.param('location') !== "null" && !team) {
                    return res.error(403, 'forbidden', "The location is not valid.");
                }

                // prepare each update
                let promises = [];
                for (let i in req.param('barrels')) {
                    promises.push(new Promise((resolve, reject) => {
                        Barrel.findOne({id: req.param('barrels')[i].id})
                            .then(barrel => {
                                // update his location and save it
                                barrel.place = req.param('location');
                                barrel.save(error => {
                                    if (error) return reject(error);

                                    // log the barrel state
                                    BarrelHistory.pushToHistory(barrel, (error, barrelHistory) => {
                                        if (error) return reject(error);

                                        Barrel.publishUpdate(barrel.id, barrel);

                                        checkTeamStocks(barrel);

                                        return resolve(barrel.id);

                                    });
                                })
                            })
                            .catch(error => reject(error));
                    }));
                }

                // run all promises
                Promise.all(promises)
                    .then(ids => {

                        Barrel.subscribe(req, ids);

                        return res.ok();
                    })
                    .catch(error => res.negotiate(error));
            });

    }

};

/**
 * Check the remaining barrels of this type for the concerned bar.
 * If 1 : send warning alert
 * If 0 : send serious alert
 *
 * @param barrel
 */
function checkTeamStocks(barrel) {

    // if there is a team, get all his barrels of this type
    if (barrel.place) {

        BarrelType.findOne({
            id: barrel.type
        })
            .exec((error, type) => {
                if (error) return;

                // count how many new barrel of this type this the team still have
                Barrel.count({
                    place: barrel.place,
                    type: type.id,
                    state: "new"
                })
                    .exec((error, count) => {
                        if (error) return;

                        // if state is new, check if there is an alert to remove (if a missClick triggered an alert)
                        if (barrel.state === "new") {
                            // count how many barrels are news
                            // if 2 or 1, an alert was created
                            if (count < 3) {
                                // Find the alert sent
                                Alert.findOne({
                                    severity: count === 2 ? "warning" : "serious",
                                    category: "Manque auto",
                                    sender: barrel.place
                                })
                                    .limit(1).sort({$natural:-1})
                                    .exec((error, alert) => {
                                        if (error || !alert) return;

                                        Alert.destroy({id: alert.id}).exec((error) => {
                                            if (error) return;

                                            Alert.publishDestroy(alert.id);
                                        });
                                    });
                            }
                        } else {
                            // if 1 or 0 remaining, create alert
                            if (count < 2) {
                                Alert.create({
                                    sender: barrel.place,
                                    severity: count === 1 ? "warning" : "serious",
                                    title: "Stock : " + type.name,
                                    category: "Manque auto"
                                })
                                    .exec((error, alert) => {
                                        if (error) return;

                                        // push this modification in the alert history
                                        AlertHistory.pushToHistory(alert, (error, result) => {
                                            if (error) return;

                                            Alert.publishCreate(alert);
                                            Alert.subscribe(req, [alert.id]);
                                        });

                                    });
                            }
                        }
                    })

            });
    }
}

/**
 * Save a barrel and push it to the history
 *
 * @param {object} barrel: the barrel to save
 * @param {object} req: the request
 * @param {object} res: the response
 * @param {boolean} checkState: true if the barrel's team stocks have to be check
 */
function updateBarrel(barrel, req, res, checkState) {

    barrel.save((error) => {
        if (error) {
            return res.negotiate(error);
        }

        // log the new barrel state
        BarrelHistory.pushToHistory(barrel, (error, barrelHistory) => {
            if (error) {
                return res.negotiate(error);
            }

            Barrel.publishUpdate(barrel.id, barrel);
            Barrel.subscribe(req, [barrel.id]);

            if (checkState) {
                checkTeamStocks(barrel);
            }

            return res.ok(barrel);

        });
    });
}

/**
 * If only the state is passed in parameter, check if
 * the value of state is valid (in the states array)
 *
 * If currentState too is set, check if it's allowed to move
 * from currentState to state.
 *
 * @param {string} state
 * @param {string|null} currentState
 * @returns {boolean}
 */
function isStateValid(state, currentState) {
    const states = ["new", "opened", "empty"];

    // if no current state, only check if state is in the array
    if (!currentState) {
        return states.indexOf(state) !== -1;
    } else {
        // return false if the state is wrong
        if (states.indexOf(state) === -1) {
            return false;
        }
    }

    // check if it's allowed to set the barrel state with this value (same or neighbor)
    const d = Math.abs(states.indexOf(currentState) - states.indexOf(state))
    return d === 1 || d === 0;
}
<|endoftext|>


<commit_before>'use strict';

var requestProxy = require('express-request-proxy'),
  express = require('express'),
  port = process.env.PORT || 3000,
  app = express();

var proxyNYTimes = function(request, response) {
  console.log('Routing NY times request for', request.params[0]);
  (requestProxy({
    url: 'https://api.nytimes.com' + request.params[0],
    headers: { Authorization: 'token ' + process.env.NYT_TOKEN }
  }))(request, response);
};

app.get('/nytimes/*', proxyNYTimes);

app.use(express.static('./'));

app.get('*', function(request, response) {
  console.log('New request:', request.url);
  response.sendFile('index.html', { root: '.' });
});

app.listen(port, function() {
  console.log('Server started on port ' + port + '!');
});

// https://api.nytimes.com/svc/topstories/v2/home.json
<commit_msg>fixed static path in server.js<commit_after>'use strict';

var requestProxy = require('express-request-proxy'),
  express = require('express'),
  port = process.env.PORT || 3000,
  app = express();

var proxyNYTimes = function(request, response) {
  console.log('Routing NY times request for', request.params[0]);
  (requestProxy({
    url: 'https://api.nytimes.com' + request.params[0],
    headers: { Authorization: 'token ' + process.env.NYT_TOKEN }
  }))(request, response);
};

app.get('/nytimes/*', proxyNYTimes);

app.use(express.static('./public'));

app.get('*', function(request, response) {
  console.log('New request:', request.url);
  response.sendFile('index.html', { root: '.' });
});

app.listen(port, function() {
  console.log('Server started on port ' + port + '!');
});

// https://api.nytimes.com/svc/topstories/v2/home.json
<|endoftext|>


<commit_before>const express = require("express");
const app = express();
const bodyParser = require("body-parser");

const website = `

            <title>Test</title>

            test

`;

app.use(bodyParser.json());

app.get("/api/:id/:message", (req, res) => {
    try {
        const arg1 = new Buffer(4);
        arg1.writeInt32LE(parseInt(req.params.id));

        const arg2 = new Buffer(4);
        arg2.writeInt32LE(0xFFFFFF);

        const arg3 = new Buffer(req.params.message + "\0");
        result = process.binding("samp").invokeNative("SendClientMessage", "dds", arg1, arg2, arg3);
        res.json({ result: result});
    } catch(e) {
        console.log(`EXCEPTION: ${e}`);
        res.end("exception bla " + e);
    }
});

app.get("/pos/:id", (req, res) => {
    try {
        const arg1 = new Buffer(4);
        arg1.writeInt32LE(parseInt(req.params.id));

        const arg2 = new Buffer(4);
        const arg3 = new Buffer(4);
        const arg4 = new Buffer(4);

        result = process.binding("samp").invokeNative("GetPlayerPos", "dRRR", arg1, arg2, arg3, arg4);

        res.json({ result: result, x: arg2.readFloatLE(), y: arg3.readFloatLE(), z: arg4.readFloatLE() });
        res.end();
    } catch(e) {
        res.end("EXCEPTION: " + e);
    }
});

app.get("/", (req, res) => {
    res.setHeader("Content-Type", "text/html");
    res.end(website);
});

app.listen(8080);

<commit_msg>add example: invoke public via CallRemoteFunction<commit_after>const express = require("express");
const app = express();
const bodyParser = require("body-parser");

const website = `

            <title>Test</title>

            test

`;

app.use(bodyParser.json());

app.get("/api/:id/:message", (req, res) => {
    try {
        const arg1 = new Buffer(4);
        arg1.writeInt32LE(parseInt(req.params.id));

        const arg2 = new Buffer(4);
        arg2.writeInt32LE(0xFFFFFF);

        const arg3 = new Buffer(req.params.message + "\0");
        result = process.binding("samp").invokeNative("SendClientMessage", "dds", arg1, arg2, arg3);
        res.json({ result: result});
    } catch(e) {
        console.log(`EXCEPTION: ${e}`);
        res.end("exception bla " + e);
    }
});

app.get("/pos/:id", (req, res) => {
    try {
        const arg1 = new Buffer(4);
        arg1.writeInt32LE(parseInt(req.params.id));

        const arg2 = new Buffer(4);
        const arg3 = new Buffer(4);
        const arg4 = new Buffer(4);

        result = process.binding("samp").invokeNative("GetPlayerPos", "dRRR", arg1, arg2, arg3, arg4);
        console.log("Test " + process.binding("samp").invokeNative("CallRemoteFunction", "ssd", new Buffer("OnPlayerUpdate\0"), new Buffer("d\0"), arg1));
        console.log("Test " + process.binding("samp").invokeNative("CallRemoteFunction", "ss", new Buffer("OnGameModeInit\0"), new Buffer("\0"), arg1));

        res.json({ result: result, x: arg2.readFloatLE(), y: arg3.readFloatLE(), z: arg4.readFloatLE() });
        res.end();
    } catch(e) {
        res.end("EXCEPTION: " + e);
    }
});

app.get("/", (req, res) => {
    res.setHeader("Content-Type", "text/html");
    res.end(website);
});

app.listen(8080);

<|endoftext|>


<commit_before>module.exports = {
    index: function(req, res) {
        if(!req.user.hasPermission('system.rights.view')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            User.find().populate('permission_groups').then(function(users) {
                var minifiedUsers = users.map(function(user) {
                    return user.strip();
                });

                PermissionGroup.find().populate('users_in_group').then(function(groups) {
                    var minifiedGroups = groups.map(function(group) {
                        return group.strip();
                    });
                    res.view('rights/index', { users: minifiedUsers, groups: minifiedGroups });
                });
            });
        }
    },

    userShow: function(req, res) {
        if(!req.user.hasPermission('system.rights.view')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            var userid = req.param('id');
            User.findOne(userid).populate('permission_groups').then(function(user) {
                if(!user) {
                    return res.notFound('Error.Resource.NotFound');
                }

                res.view('rights/user', { user: user.strip() });
            }).catch(function(err) {
                res.serverError(err);
            });
        }
    },

    groupShow: function(req, res) {
        if(!req.user.hasPermission('system.rights.view')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            var groupid = req.param('id');
            PermissionGroup.findOne(groupid).populate('users_in_group').then(function(group) {
                if(!group) {
                    return res.notFound('Error.Resource.NotFound');
                }

                res.view('rights/group', { group: group.strip() });
            }).catch(function(err) {
                res.serverError(err);
            });
        }
    },

    groupNew: function(req, res) {
        if(!req.user.hasPermission('system.rights.group.create')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            res.view('rights/groupedit');
        }
    },

    groupCreate: function(req, res) {
        if(!req.user.hasPermission('system.rights.group.create')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            var name = req.param('name');
            var permissions = req.param('permissions[]');
            if(!Array.isArray(permissions)) {
                permissions = [ permissions ];
            }

            PermissionGroup.create({
                name: name,
                permissions: permissions
            }).then(function(group) {
                res.redirect('/rights/group/' + group.id);
            });
        }
    },

    groupEdit: function(req, res) {
        if(!req.user.hasPermission('system.rights.group.edit')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            var groupid = req.param('id');
            PermissionGroup.findOne(groupid).then(function(group) {
                if(!group) {
                    return res.notFound('Error.Resource.NotFound');
                }

                res.view('rights/groupedit', { group: group });
            });
        }
    },

    userEdit: function(req, res) {
        if(!req.user.hasPermission('system.rights.user.edit')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            var userid = req.param('id');
            User.findOne(userid).then(function(user) {
                if(!user) {
                    return res.notFound('Error.Resource.NotFound');
                }

                res.view('rights/useredit', { user: user.strip() });
            });
        }
    },

    groupUpdate: function(req, res) {
        if(!req.user.hasPermission('system.rights.group.edit')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            var id = req.param('id');
            var name = req.param('name');
            var permissions = req.param('permissions[]');
            if(!Array.isArray(permissions)) {
                permissions = [ permissions ];
            }

            PermissionGroup.update(id, {
                name: name,
                permissions: permissions
            }).then(function(groups) {
                sails.controllers.rights.groupShow(req, res);
            });
        }
    },

    userUpdate: function(req, res) {
        if(!req.user.hasPermission('system.rights.user.edit')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            var id = req.param('id');
            var permissions = req.param('permissions[]');
            if(!Array.isArray(permissions)) {
                permissions = [ permissions ];
            }

            User.update(id, {
                permissions: permissions
            }).then(function(users) {
                sails.controllers.rights.userShow(req, res);
            });
        }
    },

    groupDelete: function(req, res) {
        if(!req.user.hasPermission('system.rights.group.delete')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            var id = req.param('id');
            PermissionGroup.destroy(id).then(function() {
                res.redirect('/rights');
            }).catch(function(err) {
                console.log(err);
            });
        }
    }
};
<commit_msg>Filter out empty permissions.<commit_after>module.exports = {
    index: function(req, res) {
        if(!req.user.hasPermission('system.rights.view')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            User.find().populate('permission_groups').then(function(users) {
                var minifiedUsers = users.map(function(user) {
                    return user.strip();
                });

                PermissionGroup.find().populate('users_in_group').then(function(groups) {
                    var minifiedGroups = groups.map(function(group) {
                        return group.strip();
                    });
                    res.view('rights/index', { users: minifiedUsers, groups: minifiedGroups });
                });
            });
        }
    },

    userShow: function(req, res) {
        if(!req.user.hasPermission('system.rights.view')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            var userid = req.param('id');
            User.findOne(userid).populate('permission_groups').then(function(user) {
                if(!user) {
                    return res.notFound('Error.Resource.NotFound');
                }

                res.view('rights/user', { user: user.strip() });
            }).catch(function(err) {
                res.serverError(err);
            });
        }
    },

    groupShow: function(req, res) {
        if(!req.user.hasPermission('system.rights.view')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            var groupid = req.param('id');
            PermissionGroup.findOne(groupid).populate('users_in_group').then(function(group) {
                if(!group) {
                    return res.notFound('Error.Resource.NotFound');
                }

                res.view('rights/group', { group: group.strip() });
            }).catch(function(err) {
                res.serverError(err);
            });
        }
    },

    groupNew: function(req, res) {
        if(!req.user.hasPermission('system.rights.group.create')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            res.view('rights/groupedit');
        }
    },

    groupCreate: function(req, res) {
        if(!req.user.hasPermission('system.rights.group.create')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            var name = req.param('name');
            var permissions = req.param('permissions[]');
            if(!Array.isArray(permissions)) {
                permissions = [ permissions ];
            }

            PermissionGroup.create({
                name: name,
                permissions: _.filter(permissions, function(permission) { return permission.length > 0 })
            }).then(function(group) {
                res.redirect('/rights/group/' + group.id);
            });
        }
    },

    groupEdit: function(req, res) {
        if(!req.user.hasPermission('system.rights.group.edit')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            var groupid = req.param('id');
            PermissionGroup.findOne(groupid).then(function(group) {
                if(!group) {
                    return res.notFound('Error.Resource.NotFound');
                }

                res.view('rights/groupedit', { group: group });
            });
        }
    },

    userEdit: function(req, res) {
        if(!req.user.hasPermission('system.rights.user.edit')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            var userid = req.param('id');
            User.findOne(userid).then(function(user) {
                if(!user) {
                    return res.notFound('Error.Resource.NotFound');
                }

                res.view('rights/useredit', { user: user.strip() });
            });
        }
    },

    groupUpdate: function(req, res) {
        if(!req.user.hasPermission('system.rights.group.edit')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            var id = req.param('id');
            var name = req.param('name');
            var permissions = req.param('permissions[]');
            if(!Array.isArray(permissions)) {
                permissions = [ permissions ];
            }

            PermissionGroup.update(id, {
                name: name,
                permissions: _.filter(permissions, function(permission) { return permission.length > 0 })
            }).then(function(groups) {
                sails.controllers.rights.groupShow(req, res);
            });
        }
    },

    userUpdate: function(req, res) {
        if(!req.user.hasPermission('system.rights.user.edit')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            var id = req.param('id');
            var permissions = req.param('permissions[]');
            if(!Array.isArray(permissions)) {
                permissions = [ permissions ];
            }

            User.update(id, {
                permissions: _.filter(permissions, function(permission) { return permission.length > 0 })
            }).then(function(users) {
                sails.controllers.rights.userShow(req, res);
            });
        }
    },

    groupDelete: function(req, res) {
        if(!req.user.hasPermission('system.rights.group.delete')) {
            res.forbidden('Error.Authorization.NoRights', '403');
        } else {
            var id = req.param('id');
            PermissionGroup.destroy(id).then(function() {
                res.redirect('/rights');
            }).catch(function(err) {
                console.log(err);
            });
        }
    }
};
<|endoftext|>


<commit_before>"use strict";

if(process.env.ENV === 'development')require('dotenv').config();

const PORT        = process.env.PORT || 8080;
const ENV         = process.env.ENV || "development";
const express     = require("express");
const bodyParser  = require("body-parser");
const sass        = require("node-sass-middleware");
const app         = express();

const knexConfig  = require("./knexfile");
const knex        = require("knex")(knexConfig[ENV]);
const morgan      = require('morgan');
const knexLogger  = require('knex-logger');

// Seperated Routes for each Resource
const usersRoutes = require("./routes/users");

// const accountSid = process.env.TWILIO_KEY;
// const authToken =  process.env.TWILIO_SECRET;
// const client = require('twilio')(accountSid, authToken);

app.post('/sms', function(req, res) {
  var twilio = require('twilio');
  var twiml = new twilio.TwimlResponse();
  twiml.message('The Robots are coming! Head for the hills!');
  res.writeHead(200, {'Content-Type': 'text/xml'});
  res.end(twiml.toString());
});

app.post("/order", (req, res) => {
  client.messages.create({
      to: '+16477619205',
      from: '+14508230998',
      body: `Your order has been placed. Thank you for choosing Zuckerburger.
            `,
  }, function(err,message){
    if(err)console.error(err)
        console.log(message);
      });
});

app.use(morgan('dev'));

// Log knex SQL queries to STDOUT as well
app.use(knexLogger(knex));

app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/styles", sass({
  src: __dirname + "/styles",
  dest: __dirname + "/public/styles",
  debug: true,
  outputStyle: 'expanded'
}));
app.use(express.static("public"));

// Mount all resource routes

app.use("/api/users", usersRoutes(knex));

// Home page
app.get("/", (req, res) => {
  res.redirect('/menu');
});

app.get("/menu", (req, res) => {
 knex.select('name','price','type').from('dishes').asCallback((err,rows)=>{
    if (err) return console.error(err);
      let templateVars = {
        dishes:rows,
        addons:{},
      }
      knex.select('*').from('dishes').where('name','Billionaire Burger').asCallback((err,row)=>{
         if (err) return console.error(err);
         templateVars.dish = row;
         knex.select('name',"pic","price").from('dishes').where('type','sides').asCallback((err,sides)=>{
          templateVars.adddons = sides;
          console.log(templateVars);
          res.render('index',templateVars)
        });
    })
  });

app.get("/menu/:name",(req, res) => {
  console.log(req.params.name);
  knex.select('*').from('dishes').where('name',req.params.name).asCallback((err,row)=>{
     if (err) return console.error(err);
       res.json({
         dish:row[0]
       });
     })
   });
});

app.post("/cart",(req, res) => {
  if(!req.body.name)return console.error('param does not exist');
  console.log(req.body.name);

  knex('menu_cart').insert({
    cart_id: knex.select('id').from('cart').where('owner','Kyle'),
    menu_id: knex.select('id').from('dishes').where('name',req.body.name),
    quantity: req.body.quantity
  }).asCallback((err)=>{
    if (err) return console.error(err);
    knex.countDistinct("menu_id").from('menu_cart').where('cart_id',knex.select('id').from('cart').where('owner','Kyle')).asCallback((err,row)=>{
      if (err) return console.error(err);
          res.json({
            items: row[0]
          });
        });
      });
    });

app.get("/cart", (req, res) => {
  knex('dishes')
  .leftJoin('menu_cart','dishes.id','menu_cart.menu_id')
  .leftJoin('cart','menu_cart.cart_id','cart.id')
  .select('name','price', 'menu_cart.quantity as quantity').distinct()
  .whereNotNull('quantity')
  .asCallback((err,rows)=>{
    console.log(rows)
    let templateVars = {
      // cart: [{name: 'Face Burger',
      //     pic: '/images/faceBurger.jpg',
      //     price:17.00,
      //     description:' Face Burger is our signiture dish. Mark created this burger when he was at Harvard, and it soon became very popular among various Ivy league schools.',
      //     type:'main'}]
      cart : rows
    }
     res.json(templateVars);
  })
});

app.listen(PORT, () => {
  console.log("Example app listening on port " + PORT);
});
<commit_msg>console debugging<commit_after>"use strict";

if(process.env.ENV === 'development')require('dotenv').config();

const PORT        = process.env.PORT || 8080;
const ENV         = process.env.ENV || "development";
const express     = require("express");
const bodyParser  = require("body-parser");
const sass        = require("node-sass-middleware");
const app         = express();

const knexConfig  = require("./knexfile");
const knex        = require("knex")(knexConfig[ENV]);
const morgan      = require('morgan');
const knexLogger  = require('knex-logger');

// Seperated Routes for each Resource
const usersRoutes = require("./routes/users");

// const accountSid = process.env.TWILIO_KEY;
// const authToken =  process.env.TWILIO_SECRET;
// const client = require('twilio')(accountSid, authToken);

app.post('/sms', function(req, res) {
  var twilio = require('twilio');
  var twiml = new twilio.TwimlResponse();
  twiml.message('The Robots are coming! Head for the hills!');
  res.writeHead(200, {'Content-Type': 'text/xml'});
  res.end(twiml.toString());
});

app.post("/order", (req, res) => {
  client.messages.create({
      to: '+16477619205',
      from: '+14508230998',
      body: `Your order has been placed. Thank you for choosing Zuckerburger.
            `,
  }, function(err,message){
    if(err)console.error(err)
        console.log(message);
      });
});

app.use(morgan('dev'));

// Log knex SQL queries to STDOUT as well
app.use(knexLogger(knex));

app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/styles", sass({
  src: __dirname + "/styles",
  dest: __dirname + "/public/styles",
  debug: true,
  outputStyle: 'expanded'
}));
app.use(express.static("public"));

// Mount all resource routes

app.use("/api/users", usersRoutes(knex));

// Home page
app.get("/", (req, res) => {
  res.redirect('/menu');
});

app.get("/menu", (req, res) => {
 knex.select('name','price','type').from('dishes').asCallback((err,rows)=>{
    if (err) return console.error(err);
      let templateVars = {
        dishes:rows,
        addons:{},
      }
      knex.select('*').from('dishes').where('name','Billionaire Burger').asCallback((err,row)=>{
         if (err) return console.error(err);
         templateVars.dish = row;
         knex.select('name',"pic","price").from('dishes').where('type','sides').asCallback((err,sides)=>{
           if(err)console.error(err);
          templateVars.adddons = sides;
          console.log(templateVars);
          res.render('index',templateVars)
        });
    })
  });

app.get("/menu/:name",(req, res) => {
  console.log(req.params.name);
  knex.select('*').from('dishes').where('name',req.params.name).asCallback((err,row)=>{
     if (err) return console.error(err);
       res.json({
         dish:row[0]
       });
     })
   });
});

app.post("/cart",(req, res) => {
  if(!req.body.name)return console.error('param does not exist');
  console.log(req.body.name);

  knex('menu_cart').insert({
    cart_id: knex.select('id').from('cart').where('owner','Kyle'),
    menu_id: knex.select('id').from('dishes').where('name',req.body.name),
    quantity: req.body.quantity
  }).asCallback((err)=>{
    if (err) return console.error(err);
    knex.countDistinct("menu_id").from('menu_cart').where('cart_id',knex.select('id').from('cart').where('owner','Kyle')).asCallback((err,row)=>{
      if (err) return console.error(err);
          res.json({
            items: row[0]
          });
        });
      });
    });

app.get("/cart", (req, res) => {
  knex('dishes')
  .leftJoin('menu_cart','dishes.id','menu_cart.menu_id')
  .leftJoin('cart','menu_cart.cart_id','cart.id')
  .select('name','price', 'menu_cart.quantity as quantity').distinct()
  .whereNotNull('quantity')
  .asCallback((err,rows)=>{
    console.log(rows)
    let templateVars = {
      // cart: [{name: 'Face Burger',
      //     pic: '/images/faceBurger.jpg',
      //     price:17.00,
      //     description:' Face Burger is our signiture dish. Mark created this burger when he was at Harvard, and it soon became very popular among various Ivy league schools.',
      //     type:'main'}]
      cart : rows
    }
     res.json(templateVars);
  })
});

app.listen(PORT, () => {
  console.log("Example app listening on port " + PORT);
});
<|endoftext|>


<commit_before>(function()
{
	//Setting white-space to normal to override gridster's inherited value
	freeboard.addStyle('table.list-table', "width: 100%; white-space: normal !important; ");
	freeboard.addStyle('table.list-table td, table.list-table th', "padding: 2px 2px 2px 2px; vertical-align: top; ");

	var tableWidget = function (settings) {
	        var self = this;
	        var titleElement = $('

');
	        var stateElement = $('

');
	        var currentSettings = settings;
		//store our calculated values in an object
		var stateObject = {};

		function updateState() {
			stateElement.find('thead').empty();
			stateElement.find('tbody').remove();
			var bodyHTML = $('
');
			var classObject = {};
			var classCounter = 0;

		    var replaceValue = (_.isUndefined(currentSettings.replace_value) ? '' : currentSettings.replace_value);

		// This function handles arrays and objects
		function eachRecursive(obj)
		{
		    for (var k in obj)
		    {
		        if (typeof obj[k] == "object" && obj[k] !== null)
		            eachRecursive(obj[k]);
		        else
		            var tr = "
";
		     		tr += "" + k  + "	" + "" + obj[k] + "
";
		    		tbody.innerHTML += tr;
		    }
		}

		console.log('object:', stateObject);
		if (stateObject.value) {
			var tabledata = { value: {} };
			tabledata.value.data = [stateObject.value];
			tabledata.value.header = [];
			for(var k in stateObject.value) tabledata['value']['header'].unshift(k);
			console.log(tabledata);
		}

			//only proceed if we have a valid JSON object
		if (tabledata && tabledata.value && tabledata.value.header && tabledata.value.data) {

		console.log('ok');
				var headerRow = $('
');
				var templateRow = $('
');
				var rowHTML;

				//Loop through the 'header' array, building up our header row and also a template row
				try {
					$.each(tabledata.value.header, function(headerKey, headerName){
						classObject[headerName] = 'td-' + classCounter;
						headerRow.append($('').html(headerName));
						templateRow.append($('').addClass('td-' + classCounter).html(replaceValue));
						classCounter++;
					})
				} catch (e) {
					console.log(e);
				}

				//Loop through each 'data' object, cloning the templateRow and using the class to set the value in the correct
				try {
					$.each(tabledata.value.data, function(k, v){
						rowHTML = templateRow.clone();
						$.each(v, function(dataKey, dataValue){
							rowHTML.find('.' + classObject[dataKey]).html(dataValue);
						})
						bodyHTML.append(rowHTML);
					})
				} catch (e) {
					console.log(e)
				}

				//Append the header and body
				stateElement.find('thead').append(headerRow);
				stateElement.find('table').append(bodyHTML);

				//show or hide the header based on the setting
				if (currentSettings.show_header) {
					stateElement.find('thead').show();
				} else {
					stateElement.find('thead').hide();
				}
			}
        }

        this.render = function (element) {
            $(element).append(titleElement).append(stateElement);
        }

        this.onSettingsChanged = function (newSettings) {
            currentSettings = newSettings;
            titleElement.html((_.isUndefined(newSettings.title) ? "" : newSettings.title));
            updateState();
        }

        this.onCalculatedValueChanged = function (settingName, newValue) {
            //whenver a calculated value changes, stored them in the variable 'stateObject'
			stateObject[settingName] = newValue;
            updateState();
        }

        this.onDispose = function () {
        }

        this.getHeight = function () {
			var height = Math.ceil(stateElement.height() / 55);
			return (height > 0 ? height : 1);
        }

        this.onSettingsChanged(settings);
    };

    freeboard.loadWidgetPlugin({
        type_name: "list",
        display_name: "Table",
        settings: [
            {
                name: "title",
                display_name: "Title",
                type: "text"
            },
			{
                name: "show_header",
                display_name: "Show Headers",
				default_value: true,
                type: "boolean"
            },
			{
                name: "replace_value",
                display_name: "Replace blank values",
                type: "text"
            },
			{
                name: "value",
                display_name: "Value",
                type: "calculated"
            }
        ],
        newInstance: function (settings, newInstanceCallback) {
            newInstanceCallback(new tableWidget(settings));
        }
    });
}());
<commit_msg>Attempt to autodetect byte fields<commit_after>(function()
{
	//Setting white-space to normal to override gridster's inherited value
	freeboard.addStyle('table.list-table', "width: 100%; white-space: normal !important; ");
	freeboard.addStyle('table.list-table td, table.list-table th', "padding: 2px 2px 2px 2px; vertical-align: top; ");

	var tableWidget = function (settings) {
	        var self = this;
	        var titleElement = $('

');
	        var stateElement = $('

');
	        var currentSettings = settings;
		//store our calculated values in an object
		var stateObject = {};

		function updateState() {
			stateElement.find('thead').empty();
			stateElement.find('tbody').remove();
			var bodyHTML = $('
');
			var classObject = {};
			var classCounter = 0;

		    var replaceValue = (_.isUndefined(currentSettings.replace_value) ? '' : currentSettings.replace_value);

		// This function handles arrays and objects
		function eachRecursive(obj)
		{
		    for (var k in obj)
		    {
		        if (typeof obj[k] == "object" && obj[k] !== null)
		            eachRecursive(obj[k]);
		        else
		            var tr = "
";
		     		tr += "" + k  + "	" + "" + obj[k] + "
";
		    		tbody.innerHTML += tr;
		    }
		}

		console.log('object:', stateObject);
		if (stateObject.value) {
			var tabledata = { value: {} };
			tabledata.value.data = [stateObject.value];
			tabledata.value.header = [];
			for(var k in stateObject.value) tabledata['value']['header'].unshift(k);
			console.log(tabledata);
		}

			//only proceed if we have a valid JSON object
		if (tabledata && tabledata.value && tabledata.value.header && tabledata.value.data) {

		console.log('ok');
				var headerRow = $('
');
				var templateRow = $('
');
				var rowHTML;

				//Loop through the 'header' array, building up our header row and also a template row
				try {
					$.each(tabledata.value.header, function(headerKey, headerName){
						classObject[headerName] = 'td-' + classCounter;
						headerRow.append($('').html(headerName));
						templateRow.append($('').addClass('td-' + classCounter).html(replaceValue));
						classCounter++;
					})
				} catch (e) {
					console.log(e);
				}

				//Loop through each 'data' object, cloning the templateRow and using the class to set the value in the correct
				try {
					$.each(tabledata.value.data, function(k, v){
						rowHTML = templateRow.clone();
						$.each(v, function(dataKey, dataValue){
						   if(dataKey.toLowerCase().indexOf("byte") !=-1) {
                                                        var i = Math.floor( Math.log(dataValue) / Math.log(1024) );
                                                        dataValue = ( dataValue / Math.pow(1024, i) ).toFixed(2) * 1 + ' ' + ['B', 'kB', 'MB', 'GB', 'TB'][i];
                                                        rowHTML.find('.' + classObject[dataKey]).html(dataValue);
                                                   } else {
                                                        rowHTML.find('.' + classObject[dataKey]).html(dataValue);
                                                   }

						})
						bodyHTML.append(rowHTML);
					})
				} catch (e) {
					console.log(e)
				}

				//Append the header and body
				stateElement.find('thead').append(headerRow);
				stateElement.find('table').append(bodyHTML);

				//show or hide the header based on the setting
				if (currentSettings.show_header) {
					stateElement.find('thead').show();
				} else {
					stateElement.find('thead').hide();
				}
			}
        }

        this.render = function (element) {
            $(element).append(titleElement).append(stateElement);
        }

        this.onSettingsChanged = function (newSettings) {
            currentSettings = newSettings;
            titleElement.html((_.isUndefined(newSettings.title) ? "" : newSettings.title));
            updateState();
        }

        this.onCalculatedValueChanged = function (settingName, newValue) {
            //whenver a calculated value changes, stored them in the variable 'stateObject'
			stateObject[settingName] = newValue;
            updateState();
        }

        this.onDispose = function () {
        }

        this.getHeight = function () {
			var height = Math.ceil(stateElement.height() / 55);
			return (height > 0 ? height : 1);
        }

        this.onSettingsChanged(settings);
    };

    freeboard.loadWidgetPlugin({
        type_name: "list",
        display_name: "Table",
        settings: [
            {
                name: "title",
                display_name: "Title",
                type: "text"
            },
			{
                name: "show_header",
                display_name: "Show Headers",
				default_value: true,
                type: "boolean"
            },
			{
                name: "replace_value",
                display_name: "Replace blank values",
                type: "text"
            },
			{
                name: "value",
                display_name: "Value",
                type: "calculated"
            }
        ],
        newInstance: function (settings, newInstanceCallback) {
            newInstanceCallback(new tableWidget(settings));
        }
    });
}());
<|endoftext|>


<commit_before>/* global Connector, sails */

/**
 * ResearchEntityController
 *
 * @description :: Server-side logic for managing Researchentities
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

var actionUtil = require('sails/lib/hooks/blueprints/actionUtil');

module.exports = {
    createDraft: function (req, res) {
        var researchEntityId = req.params.researchEntityId;
        var draftData = req.body;
        var Model = getModel(req);
        return res.halt(Model.createDraft(Model, researchEntityId, draftData));
    },
    unverifyDocument: function (req, res) {
        var researcEntityId = req.params.researchEntityId;
        var documentId = req.params.documentId;
        var Model = getModel(req);
        res.halt(Model.unverifyDocument(Model, researcEntityId, documentId));
    },
    verifyDraft: function (req, res) {
        const researchEntityId = req.params.researchEntityId;
        const draftId = req.params.draftId;
        const position = req.body.position;
        const corresponding = req.body.corresponding;
        const affiliationInstituteIds = req.body.affiliations;
        const Model = getModel(req);
        res.halt(Model.verifyDraft(Model, researchEntityId, draftId, position, affiliationInstituteIds, corresponding));
    },
    verifyDrafts: function (req, res) {
        var researchEntityId = req.params.researchEntityId;
        var draftIds = req.param('draftIds');
        var Model = getModel(req);
        res.halt(Model.verifyDrafts(Model, researchEntityId, draftIds));
    },
    verifyDocument: function (req, res) {
        const researchEntityId = req.params.researchEntityId;
        const documentId = req.body.id;
        const position = req.body.position;
        const affiliationInstituteIds = req.body.affiliations;
        const corresponding = req.body.corresponding;
        const Model = getModel(req);
        // TODO in case of failed verify give response with details instead of 400
        res.halt(Model.verifyDocument(Model, researchEntityId, documentId, position, affiliationInstituteIds, corresponding));
    },
    verifyDocuments: function (req, res) {
        var researchEntityId = req.params.researchEntityId;
        var documentIds = req.param('documentIds');
        var Model = getModel(req);
        res.halt(Model.verifyDocuments(Model, researchEntityId, documentIds));
    },
    discardDocument: function (req, res) {
        var researchEntityId = req.params.researchEntityId;
        var documentId = req.param('documentId');
        var Model = getModel(req);
        res.halt(Model.discardDocument(researchEntityId, documentId));
    },
    discardDocuments: function (req, res) {
        var researchEntityId = req.params.researchEntityId;
        var documentIds = req.param('documentIds');
        var Model = getModel(req);
        res.halt(Model.discardDocuments(Model, researchEntityId, documentIds));
    },
    createDrafts: function (req, res) {
        var researchEntityId = req.params.researchEntityId;
        var documents = req.param('documents');
        var Model = getModel(req);
        res.halt(Model.createDrafts(Model, researchEntityId, documents));
    },
    updateDraft: function (req, res) {
        var draftId = req.params.id;
        var draftData = req.body;
        var Model = getModel(req);
        res.halt(Model.updateDraft(Model, draftId, draftData));
    },
    getExternalDocuments: function (req, res) {
        var researchEntityId = req.params.researchEntityId;
        var query = getQuery(req);
        var Model = getModel(req);
        res.halt(Connector.getDocuments(Model, researchEntityId, query));
    },
    getChartsData: function (req, res) {
        var modelName = req.options.model || req.options.controller;
        var id = req.params.researchEntityId;
        res.halt(Chart.getChartsData(id, modelName));
    },
    setAuthorhips: function (req, res) {
        var researchEntityId = req.params.researchEntityId;
        var draftId = req.params.documentId;
        var authorshipsData = req.body;
        var Model = getModel(req);
        res.halt(Model.setAuthorships(Model, researchEntityId, draftId, authorshipsData));
    },
    updateProfile: function (req, res) {
        const researchEntityId = req.params.researchEntityId;
        const Model = getModel(req);
        const researchEntityData = req.body;
        res.halt(Model.updateProfile(Model, researchEntityId, researchEntityData));
    },
    deleteDrafts: function (req, res) {
        const Model = getModel(req);
        var draftIds = req.param('draftIds');
        res.halt(Model.deleteDrafts(Model, draftIds));
    }
};

function getModel(req) {
    var model_name = req.options.model || req.options.controller;
    var Model = req._sails.models[model_name];
    return Model;
}

function getPopulateFields(req) {
    var populate = req.query.populate;
    if (_.isString(populate))
        populate = [populate];
    return populate;
}

function getQuery(req) {
    var query = {
        limit: actionUtil.parseLimit(req),
        skip: actionUtil.parseSkip(req),
        where: JSON.parse(req.query.where || '{}')
    };
    return query;
}

<commit_msg>Fixed small error.<commit_after>/* global Connector, sails */

/**
 * ResearchEntityController
 *
 * @description :: Server-side logic for managing Researchentities
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

var actionUtil = require('sails/lib/hooks/blueprints/actionUtil');

module.exports = {
    createDraft: function (req, res) {
        var researchEntityId = req.params.researchEntityId;
        var draftData = req.body;
        var Model = getModel(req);
        return res.halt(Model.createDraft(Model, researchEntityId, draftData));
    },
    unverifyDocument: function (req, res) {
        var researcEntityId = req.params.researchEntityId;
        var documentId = req.params.documentId;
        var Model = getModel(req);
        res.halt(Model.unverifyDocument(Model, researcEntityId, documentId));
    },
    verifyDraft: function (req, res) {
        const researchEntityId = req.params.researchEntityId;
        const draftId = req.params.draftId;
        const position = req.body.position;
        const corresponding = req.body.corresponding;
        const affiliationInstituteIds = req.body.affiliations;
        const Model = getModel(req);
        res.halt(Model.verifyDraft(Model, researchEntityId, draftId, position, affiliationInstituteIds, corresponding));
    },
    verifyDrafts: function (req, res) {
        var researchEntityId = req.params.researchEntityId;
        var draftIds = req.param('draftIds');
        var Model = getModel(req);
        res.halt(Model.verifyDrafts(Model, researchEntityId, draftIds));
    },
    verifyDocument: function (req, res) {
        const researchEntityId = req.params.researchEntityId;
        const documentId = req.body.id;
        const position = req.body.position;
        const affiliationInstituteIds = req.body.affiliations;
        const corresponding = req.body.corresponding;
        const Model = getModel(req);
        // TODO in case of failed verify give response with details instead of 400
        res.halt(Model.verifyDocument(Model, researchEntityId, documentId, position, affiliationInstituteIds, corresponding));
    },
    verifyDocuments: function (req, res) {
        var researchEntityId = req.params.researchEntityId;
        var documentIds = req.param('documentIds');
        var Model = getModel(req);
        res.halt(Model.verifyDocuments(Model, researchEntityId, documentIds));
    },
    discardDocument: function (req, res) {
        var researchEntityId = req.params.researchEntityId;
        var documentId = req.param('documentId');
        var Model = getModel(req);
        res.halt(Model.discardDocument(Model, researchEntityId, documentId));
    },
    discardDocuments: function (req, res) {
        var researchEntityId = req.params.researchEntityId;
        var documentIds = req.param('documentIds');
        var Model = getModel(req);
        res.halt(Model.discardDocuments(Model, researchEntityId, documentIds));
    },
    createDrafts: function (req, res) {
        var researchEntityId = req.params.researchEntityId;
        var documents = req.param('documents');
        var Model = getModel(req);
        res.halt(Model.createDrafts(Model, researchEntityId, documents));
    },
    updateDraft: function (req, res) {
        var draftId = req.params.id;
        var draftData = req.body;
        var Model = getModel(req);
        res.halt(Model.updateDraft(Model, draftId, draftData));
    },
    getExternalDocuments: function (req, res) {
        var researchEntityId = req.params.researchEntityId;
        var query = getQuery(req);
        var Model = getModel(req);
        res.halt(Connector.getDocuments(Model, researchEntityId, query));
    },
    getChartsData: function (req, res) {
        var modelName = req.options.model || req.options.controller;
        var id = req.params.researchEntityId;
        res.halt(Chart.getChartsData(id, modelName));
    },
    setAuthorhips: function (req, res) {
        var researchEntityId = req.params.researchEntityId;
        var draftId = req.params.documentId;
        var authorshipsData = req.body;
        var Model = getModel(req);
        res.halt(Model.setAuthorships(Model, researchEntityId, draftId, authorshipsData));
    },
    updateProfile: function (req, res) {
        const researchEntityId = req.params.researchEntityId;
        const Model = getModel(req);
        const researchEntityData = req.body;
        res.halt(Model.updateProfile(Model, researchEntityId, researchEntityData));
    },
    deleteDrafts: function (req, res) {
        const Model = getModel(req);
        var draftIds = req.param('draftIds');
        res.halt(Model.deleteDrafts(Model, draftIds));
    }
};

function getModel(req) {
    var model_name = req.options.model || req.options.controller;
    var Model = req._sails.models[model_name];
    return Model;
}

function getPopulateFields(req) {
    var populate = req.query.populate;
    if (_.isString(populate))
        populate = [populate];
    return populate;
}

function getQuery(req) {
    var query = {
        limit: actionUtil.parseLimit(req),
        skip: actionUtil.parseSkip(req),
        where: JSON.parse(req.query.where || '{}')
    };
    return query;
}

<|endoftext|>