<commit_before>(function() {

    angular
        .module('app')
        .controller('MyProfileController', [
            '$mdDialog',
            '$scope',
            'tokenService',
            '$stateParams',
            '$state',
            MyProfileController
        ]);

    function MyProfileController($mdDialog, $scope, tokenService, $stateParams, $state) {
        var vm = this;
        $scope.username = $stateParams.username;
        $scope.editAbout = false;
        $scope.loading == true;
        $scope.BookmarkedContents = [];
        $scope.CreativeContents = [];
        $scope.studentAbout = {};

        tokenService.get("myProfile")
            .then(function(student) {
                $scope.student = student.data;
                $scope.studentAbout.about = student.data.subtitle;
                $scope.student.BookmarkedContents.data.forEach(function(content, index) {
                    $scope.student.BookmarkedContents.data[index].created.at = new Date(Date.parse($scope.student.BookmarkedContents.data[index].created.at.replace('-', '/', 'g'))); //replace mysql date to js date format
                });
                $scope.student.CreativeContents.data.forEach(function(content, index) {
                    $scope.student.CreativeContents.data[index].created.at = new Date(Date.parse($scope.student.CreativeContents.data[index].created.at.replace('-', '/', 'g'))); //replace mysql date to js date format
                });
                $scope.tab = $stateParams.tab;
                $scope.loading == false;
                console.log($scope.student);
            });

        $scope.showAdvanced = function(ev) {
            $mdDialog.show({
                controller: DialogController,
                templateUrl: 'app/views/partials/completeProfile.html',
                parent: angular.element(document.body),
                targetEvent: ev,
                clickOutsideToClose: true,
                fullscreen: true // Only for -xs, -sm breakpoints.
            })
        };
        $scope.cancelRsvp = function(ev, event, index) {
            // Appending dialog to document.body to cover sidenav in docs app
            var confirm = $mdDialog.confirm()
                .title('Not attending ' + event.title + "?")
                .textContent('')
                .targetEvent(ev)
                .clickOutsideToClose(true)
                .ok('Not attending')
                .cancel('Cancel');
            $mdDialog.show(confirm).then(function() {
                tokenService.delete('rsvpEvent/' + event.id, '').then(function(result) {
                    if (result.status != 'error') {
                        console.log(result.status);
                        $scope.student.AttendingEvents.data.splice(index, 1);
                    } else {
                        console.log(result);
                    }
                });
            }, function() {
                console.log('cancel');
            });
        };
        $scope.openSocialAccounts = function(ev) {
            $mdDialog.show({
                controller: SocialController,
                templateUrl: 'app/views/partials/socialLinks.html',
                parent: angular.element(document.body),
                targetEvent: ev,
                clickOutsideToClose: true,
                fullscreen: true // Only for -xs, -sm breakpoints.
            });
        };
        $scope.showParticipants = function(ev, eventId) {
            $mdDialog.show({
                controller: 'ParticipantsController',
                templateUrl: 'app/views/partials/showParticipants.html',
                parent: angular.element(document.body),
                targetEvent: ev,
                locals: {
                    eventId: eventId

                },
                clickOutsideToClose: true,
                fullscreen: true // Only for -xs, -sm breakpoints.
            })
        };
        $scope.about = function() {
            if ($scope.editAbout) {
                // console.log($scope.studentAbout);
                tokenService.patch("/students/" + $scope.student.username, $scope.studentAbout)
                    .then(function() {
                        $scope.editAbout = false;
                        $scope.student.subtitle = $scope.studentAbout.about;
                    })
                    .catch(function(error) {
                        console.log(error);
                    });

            } else {
                $scope.editAbout = true;
            }
        };
        $scope.follow = function(type, index) {
            // SEND FOLLOWER ID AND FOLLOWING ID IN POST
            if ($scope.student[type].data[index].following) {
                tokenService.post('studentFollow/' + $scope.student[type].data[index].username).then(function(result) {
                    if (result.status != 'error') {
                        console.log(result.status);
                        $scope.student[type].data[index].following = !$scope.student[type].data[index].following;
                    } else {
                        console.log(result);
                    }
                });
            } else {
                // SEND FOLLOWER ID IN DELETE
                tokenService.delete('studentFollow/' + $scope.student[type].data[index].username).then(function(result) {
                    console.log('post request');
                    if (result.status != 'error') {
                        $scope.student[type].data[index].following = !$scope.student[type].data[index].following;
                        console.log(result.status);
                    } else {
                        console.log(result);
                    }
                });
            }
        };
        // SKILLS CHIP SHIT STARTED

        $scope.readonly = true;
        $scope.removable = false;
        $scope.selectedItem = null;
        $scope.searchText = null;
        $scope.querySearch = querySearch;
        numberChips = [];
        numberChips2 = [];
        numberBuffer = '';
        $scope.autocompleteDemoRequireMatch = false;
        $scope.transformChip = transformChip;

        /**
         * Return the proper object when the append is called.
         */
        function transformChip(chip) {
            // If it is an object, it's already a known chip
            if (angular.isObject(chip)) {
                return chip;
            }

            // Otherwise, create a new one
            return { name: chip };
        }

        /**
         * Search for vegetables.
         */
        function querySearch(query) {
            // var results = query ? vegetables.filter(createFilterFor(query)) : [];

            if (query) {
                arrayObjectIndexOf($scope.skills, query);
                results = $scope.skills.filter(arrayObjectIndexOf($scope.skills, query));
                // results = [];
                return results;
            } else {
                results = [];
                return results;
            }
        }

        function arrayObjectIndexOf(myArray, searchTerm) {
            console.log('myArray[i].name.match(searchTerm)');
            for (var i = 0, len = myArray.length; i < len; i++) {
                // if (myArray[i].name == searchTerm) {
                if (myArray[i].name.match(searchTerm) != null) {
                    return i;
                }
            }
            return -1;
        }
        /**
         * Create filter function for a query string
         */
        function createFilterFor(query) {
            var lowercaseQuery = angular.lowercase(query);

            return function filterFn(vegetable) {
                return (vegetable.name.indexOf(lowercaseQuery) === 0)
            };

        }

        // function loadVegetables() {
        //     var veggies = [{
        //         'name': 'Broccoli'
        //     }, {
        //         'name': 'Cabbage'
        //     }, {
        //         'name': 'Carrot'
        //     }, {
        //         'name': 'Lettuce'
        //     }, {
        //         'name': 'Spinach'
        //     }];
        //     return veggies.map(function(veg) {
        //         veg._lowername = veg.name.toLowerCase();
        //         return veg;
        //     });
        // }
        $scope.skillsEdit = function() {
            if ($scope.readonly) {
                $scope.readonly = !$scope.readonly;
                $scope.removable = !$scope.removable;
            } else {
                console.log($scope.student.Skills);
                $scope.newSkills = {};
                $scope.newSkills.skills = $scope.student.Skills;
                tokenService.post("addStudentSkills", $scope.newSkills)
                    .then(function(status) {
                        $scope.readonly = !$scope.readonly;
                        $scope.removable = !$scope.removable;
                    }).catch(function(status) {
                        console.log(status);
                    });

            }
        };

        // SKILLS CHIP SHIT ENDED
        function SocialController() {}

        function DialogController($scope, $mdDialog) {
            $scope.hide = function() {
                $mdDialog.hide();
            };

            $scope.cancel = function() {
                $mdDialog.cancel();
            };

            $scope.answer = function(answer) {
                $mdDialog.hide(answer);
            };
        }

    }

})();
<commit_msg>add skills fixed from front end<commit_after>(function() {

    angular
        .module('app')
        .controller('MyProfileController', [
            '$mdDialog',
            '$scope',
            'tokenService',
            '$stateParams',
            '$state',
            MyProfileController
        ]);

    function MyProfileController($mdDialog, $scope, tokenService, $stateParams, $state) {
        var vm = this;
        $scope.username = $stateParams.username;
        $scope.editAbout = false;
        $scope.loading == true;
        $scope.BookmarkedContents = [];
        $scope.CreativeContents = [];
        $scope.studentAbout = {};

        tokenService.get("myProfile")
            .then(function(student) {
                $scope.student = student.data;
                $scope.studentAbout.about = student.data.subtitle;
                $scope.student.BookmarkedContents.data.forEach(function(content, index) {
                    $scope.student.BookmarkedContents.data[index].created.at = new Date(Date.parse($scope.student.BookmarkedContents.data[index].created.at.replace('-', '/', 'g'))); //replace mysql date to js date format
                });
                $scope.student.CreativeContents.data.forEach(function(content, index) {
                    $scope.student.CreativeContents.data[index].created.at = new Date(Date.parse($scope.student.CreativeContents.data[index].created.at.replace('-', '/', 'g'))); //replace mysql date to js date format
                });
                $scope.tab = $stateParams.tab;
                $scope.loading == false;
                console.log($scope.student);
            });

        $scope.showAdvanced = function(ev) {
            $mdDialog.show({
                controller: DialogController,
                templateUrl: 'app/views/partials/completeProfile.html',
                parent: angular.element(document.body),
                targetEvent: ev,
                clickOutsideToClose: true,
                fullscreen: true // Only for -xs, -sm breakpoints.
            })
        };
        $scope.cancelRsvp = function(ev, event, index) {
            // Appending dialog to document.body to cover sidenav in docs app
            var confirm = $mdDialog.confirm()
                .title('Not attending ' + event.title + "?")
                .textContent('')
                .targetEvent(ev)
                .clickOutsideToClose(true)
                .ok('Not attending')
                .cancel('Cancel');
            $mdDialog.show(confirm).then(function() {
                tokenService.delete('rsvpEvent/' + event.id, '').then(function(result) {
                    if (result.status != 'error') {
                        console.log(result.status);
                        $scope.student.AttendingEvents.data.splice(index, 1);
                    } else {
                        console.log(result);
                    }
                });
            }, function() {
                console.log('cancel');
            });
        };
        $scope.openSocialAccounts = function(ev) {
            $mdDialog.show({
                controller: SocialController,
                templateUrl: 'app/views/partials/socialLinks.html',
                parent: angular.element(document.body),
                targetEvent: ev,
                clickOutsideToClose: true,
                fullscreen: true // Only for -xs, -sm breakpoints.
            });
        };
        $scope.showParticipants = function(ev, eventId) {
            $mdDialog.show({
                controller: 'ParticipantsController',
                templateUrl: 'app/views/partials/showParticipants.html',
                parent: angular.element(document.body),
                targetEvent: ev,
                locals: {
                    eventId: eventId

                },
                clickOutsideToClose: true,
                fullscreen: true // Only for -xs, -sm breakpoints.
            })
        };
        $scope.about = function() {
            if ($scope.editAbout) {
                // console.log($scope.studentAbout);
                tokenService.patch("/students/" + $scope.student.username, $scope.studentAbout)
                    .then(function() {
                        $scope.editAbout = false;
                        $scope.student.subtitle = $scope.studentAbout.about;
                    })
                    .catch(function(error) {
                        console.log(error);
                    });

            } else {
                $scope.editAbout = true;
            }
        };
        $scope.follow = function(type, index) {
            // SEND FOLLOWER ID AND FOLLOWING ID IN POST
            if ($scope.student[type].data[index].following) {
                tokenService.post('studentFollow/' + $scope.student[type].data[index].username).then(function(result) {
                    if (result.status != 'error') {
                        console.log(result.status);
                        $scope.student[type].data[index].following = !$scope.student[type].data[index].following;
                    } else {
                        console.log(result);
                    }
                });
            } else {
                // SEND FOLLOWER ID IN DELETE
                tokenService.delete('studentFollow/' + $scope.student[type].data[index].username).then(function(result) {
                    console.log('post request');
                    if (result.status != 'error') {
                        $scope.student[type].data[index].following = !$scope.student[type].data[index].following;
                        console.log(result.status);
                    } else {
                        console.log(result);
                    }
                });
            }
        };
        // SKILLS CHIP SHIT STARTED

        $scope.readonly = true;
        $scope.removable = false;
        $scope.selectedItem = null;
        $scope.searchText = null;
        $scope.querySearch = querySearch;
        numberChips = [];
        numberChips2 = [];
        numberBuffer = '';
        $scope.autocompleteDemoRequireMatch = false;
        $scope.transformChip = transformChip;

        /**
         * Return the proper object when the append is called.
         */
        function transformChip(chip) {
            // If it is an object, it's already a known chip
            if (angular.isObject(chip)) {
                return chip;
            }

            // Otherwise, create a new one
            return { name: chip };
        }

        /**
         * Search for vegetables.
         */
        function querySearch(query) {
            // var results = query ? vegetables.filter(createFilterFor(query)) : [];

            if (query) {
                arrayObjectIndexOf($scope.skills, query);
                results = $scope.skills.filter(arrayObjectIndexOf($scope.skills, query));
                // results = [];
                return results;
            } else {
                results = [];
                return results;
            }
        }

        function arrayObjectIndexOf(myArray, searchTerm) {
            console.log('myArray[i].name.match(searchTerm)');
            for (var i = 0, len = myArray.length; i < len; i++) {
                // if (myArray[i].name == searchTerm) {
                if (myArray[i].name.match(searchTerm) != null) {
                    return i;
                }
            }
            return -1;
        }
        /**
         * Create filter function for a query string
         */
        function createFilterFor(query) {
            var lowercaseQuery = angular.lowercase(query);

            return function filterFn(vegetable) {
                return (vegetable.name.indexOf(lowercaseQuery) === 0)
            };

        }

        // function loadVegetables() {
        //     var veggies = [{
        //         'name': 'Broccoli'
        //     }, {
        //         'name': 'Cabbage'
        //     }, {
        //         'name': 'Carrot'
        //     }, {
        //         'name': 'Lettuce'
        //     }, {
        //         'name': 'Spinach'
        //     }];
        //     return veggies.map(function(veg) {
        //         veg._lowername = veg.name.toLowerCase();
        //         return veg;
        //     });
        // }
        $scope.skillsEdit = function() {
            if ($scope.readonly) {
                $scope.readonly = !$scope.readonly;
                $scope.removable = !$scope.removable;
            } else {
                $scope.newSkills = {};
                $scope.newSkills.skills = $scope.student.Skills.data;
                tokenService.post("addStudentSkills", $scope.newSkills)
                    .then(function(status) {
                        $scope.readonly = !$scope.readonly;
                        $scope.removable = !$scope.removable;
                    }).catch(function(status) {
                        console.log(status);
                    });

            }
        };

        // SKILLS CHIP SHIT ENDED
        function SocialController() {}

        function DialogController($scope, $mdDialog) {
            $scope.hide = function() {
                $mdDialog.hide();
            };

            $scope.cancel = function() {
                $mdDialog.cancel();
            };

            $scope.answer = function(answer) {
                $mdDialog.hide(answer);
            };
        }

    }

})();
<|endoftext|>


<commit_before>/**
 *	Copyright (C) 2014 3D Repo Ltd
 *
 *	This program is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU Affero General Public License as
 *	published by the Free Software Foundation, either version 3 of the
 *	License, or (at your option) any later version.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU Affero General Public License for more details.
 *
 *	You should have received a copy of the GNU Affero General Public License
 *	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

 // mongoose model factory for different db and collection name for each instance
var mongoose = require('mongoose');
mongoose.Promise = Promise;

module.exports = {

	models: {},

	dbManager: null,

	setDB: function(dbManager){
		this.dbManager = dbManager;
	},

	__checkDb: function(){
		this.dbManager.getAuthDB().then(db =>
			{
				if (!this.db){
					throw new Error('db connection is null');
				}
			});
	},

	get: function (modelName, options){
		'use strict';
		this.__checkDb();

		let Model = mongoose.model(modelName);

		let data  = options && options.data || {};

		let item = new Model(data);

		item.collection = this.dbManager.getCollection(options.account, this.__collectionName(modelName, options));

		item._dbcolOptions = options;

		return item;
	},

	__collectionName: function(modelName, options){
		'use strict';

		let collectionName;

		//collectionName can be a function or a static string
		if (typeof this.models[modelName].collectionName === 'function'){

			collectionName = this.models[modelName].collectionName(options);
		} else {
			collectionName = this.models[modelName].collectionName;
		}

		return collectionName;
	},

	createClass: function(modelName, schema, collectionName) {
		'use strict';

		if (this.models[modelName] && this.models[modelName].mongooseModel){

			return this.models[modelName].mongooseModel;
		}

		let mongooseModel;
		if (mongoose.models[modelName]) {
			mongooseModel = mongoose.model(modelName);
		  } else {
			mongooseModel = mongoose.model(modelName, schema);
		  }

		//let mongooseModel =  mongoose.model(modelName, schema);

		this.models[modelName] = {
			collectionName,
			mongooseModel
		};

		mongooseModel.createInstance = (options, data) => {
			options.data = data;
			return this.get(modelName, options);
		};

		let self = this;

		function staticFunctionProxy(staticFuncName){

			let staticFunc = mongooseModel[staticFuncName];

			return function(options){

				var args = Array.prototype.slice.call(arguments);
				args.shift();

				// resetting the static collection
				if (!options || !options.account){
					throw new Error('account name (db) is missing');
				}

				let collection = self.dbManager.getCollection(options.account, self.__collectionName(modelName, options));
				mongooseModel.collection = collection;
				const applyPromise = staticFunc.apply(this, args).then(items => {
					if (Array.isArray(items)){

						items.forEach((item, index, array) => {
							item.collection = collection;
							item._dbcolOptions = options;
							array[index] = item;
						});

					} else if (typeof items === 'number') {

					} else if (items){

						items.collection = collection;
						items._dbcolOptions = options;
					}

					return Promise.resolve(items);
				});

				return applyPromise.then(items => {
					return items;
				}).catch(err => {
					self.dbManager.disconnect();
					return Promise.reject(err);
				});
			};
		}

		['find', 'findOne', 'count', 'distinct', 'where', 'findOneAndUpdate', 'findOneAndRemove', 'remove'].forEach(staticFuncName => {
			mongooseModel[staticFuncName] = staticFunctionProxy(staticFuncName);
		});

		mongooseModel.findById = function(options, id){

			var args = Array.prototype.slice.call(arguments);
			args.splice(0, 2);

			args.unshift(options, { _id: id});

			return mongooseModel.findOne.apply(mongooseModel, args);
		};

		let update = mongooseModel.update;

		mongooseModel.update = function(options){

			let collection =  self.dbManager.getCollection(options.account, self.__collectionName(modelName, options));
			mongooseModel.collection = collection;

			var args = Array.prototype.slice.call(arguments);
			args.shift();

			return update.apply(mongooseModel, args);
		};

		mongooseModel.prototype.model = modelName => {
			let model = this.models[modelName].mongooseModel;
			return model;
		};

		return mongooseModel;
	}

};
<commit_msg>ISSUE #614 fix typo again<commit_after>/**
 *	Copyright (C) 2014 3D Repo Ltd
 *
 *	This program is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU Affero General Public License as
 *	published by the Free Software Foundation, either version 3 of the
 *	License, or (at your option) any later version.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU Affero General Public License for more details.
 *
 *	You should have received a copy of the GNU Affero General Public License
 *	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

 // mongoose model factory for different db and collection name for each instance
var mongoose = require('mongoose');
mongoose.Promise = Promise;

module.exports = {

	models: {},

	dbManager: null,

	setDB: function(dbManager){
		this.dbManager = dbManager;
	},

	__checkDb: function(){
		this.dbManager.getAuthDB().then(db =>
			{
				if (!db){
					throw new Error('db connection is null');
				}
			});
	},

	get: function (modelName, options){
		'use strict';
		this.__checkDb();

		let Model = mongoose.model(modelName);

		let data  = options && options.data || {};

		let item = new Model(data);

		item.collection = this.dbManager.getCollection(options.account, this.__collectionName(modelName, options));

		item._dbcolOptions = options;

		return item;
	},

	__collectionName: function(modelName, options){
		'use strict';

		let collectionName;

		//collectionName can be a function or a static string
		if (typeof this.models[modelName].collectionName === 'function'){

			collectionName = this.models[modelName].collectionName(options);
		} else {
			collectionName = this.models[modelName].collectionName;
		}

		return collectionName;
	},

	createClass: function(modelName, schema, collectionName) {
		'use strict';

		if (this.models[modelName] && this.models[modelName].mongooseModel){

			return this.models[modelName].mongooseModel;
		}

		let mongooseModel;
		if (mongoose.models[modelName]) {
			mongooseModel = mongoose.model(modelName);
		  } else {
			mongooseModel = mongoose.model(modelName, schema);
		  }

		//let mongooseModel =  mongoose.model(modelName, schema);

		this.models[modelName] = {
			collectionName,
			mongooseModel
		};

		mongooseModel.createInstance = (options, data) => {
			options.data = data;
			return this.get(modelName, options);
		};

		let self = this;

		function staticFunctionProxy(staticFuncName){

			let staticFunc = mongooseModel[staticFuncName];

			return function(options){

				var args = Array.prototype.slice.call(arguments);
				args.shift();

				// resetting the static collection
				if (!options || !options.account){
					throw new Error('account name (db) is missing');
				}

				let collection = self.dbManager.getCollection(options.account, self.__collectionName(modelName, options));
				mongooseModel.collection = collection;
				const applyPromise = staticFunc.apply(this, args).then(items => {
					if (Array.isArray(items)){

						items.forEach((item, index, array) => {
							item.collection = collection;
							item._dbcolOptions = options;
							array[index] = item;
						});

					} else if (typeof items === 'number') {

					} else if (items){

						items.collection = collection;
						items._dbcolOptions = options;
					}

					return Promise.resolve(items);
				});

				return applyPromise.then(items => {
					return items;
				}).catch(err => {
					self.dbManager.disconnect();
					return Promise.reject(err);
				});
			};
		}

		['find', 'findOne', 'count', 'distinct', 'where', 'findOneAndUpdate', 'findOneAndRemove', 'remove'].forEach(staticFuncName => {
			mongooseModel[staticFuncName] = staticFunctionProxy(staticFuncName);
		});

		mongooseModel.findById = function(options, id){

			var args = Array.prototype.slice.call(arguments);
			args.splice(0, 2);

			args.unshift(options, { _id: id});

			return mongooseModel.findOne.apply(mongooseModel, args);
		};

		let update = mongooseModel.update;

		mongooseModel.update = function(options){

			let collection =  self.dbManager.getCollection(options.account, self.__collectionName(modelName, options));
			mongooseModel.collection = collection;

			var args = Array.prototype.slice.call(arguments);
			args.shift();

			return update.apply(mongooseModel, args);
		};

		mongooseModel.prototype.model = modelName => {
			let model = this.models[modelName].mongooseModel;
			return model;
		};

		return mongooseModel;
	}

};
<|endoftext|>


<commit_before>'use strict';

var RingBuffer = require('ringbufferjs');

module.exports = NullStatsd;

function NullStatsd(capacity) {
    if (!(this instanceof NullStatsd)) {
        return new NullStatsd(capacity);
    }

    this._buffer = new RingBuffer(capacity || 50);
}

function NullStatsdRecord(type, name, value, delta, time) {
    this.type = type;
    this.name = name;
    this.value = value || null;
    this.delta = delta || null;
    this.time = time || null;
}

var proto = NullStatsd.prototype;

proto._write = function _write(record) {
    this._buffer.enq(record);
};

proto.gauge = function gauge(name, value) {
    this._write(new NullStatsdRecord('g', name, value));
};

proto.counter = function counter(name, value) {
    this._write(new NullStatsdRecord('c', name, null, value));
};

proto.increment = function increment(name, delta) {
    this._write(new NullStatsdRecord(
        'c',
        name,
        null,
        delta || 1
    ));
};

proto.decrement = function decrement(name, delta) {
    this._write(new NullStatsdRecord(
        'c',
        name,
        null,
        (-1 * Math.abs(delta || 1))
    ));
};

proto.timing = function timing(name, time) {
    this._write(new NullStatsdRecord(
        'ms',
        name,
        null,
        null,
        time
    ));
};

proto.close = function close() {
    for (var i = 0, len = this._buffer.size(); i < len; i++) {
        this._buffer.deq();
    }
};

proto.immediateGauge = function (name, value, cb) {
    this._write(new NullStatsdRecord(
        'g',
        name,
        value
    ));
    process.nextTick(cb);
};

proto.immediateIncrement = function (name, delta, cb) {
    this._write(new NullStatsdRecord(
        'c',
        name,
        null,
        delta || 1
    ));
    process.nextTick(cb);
};

proto.immediateDecrement = function (name, delta, cb) {
    this._write(new NullStatsdRecord(
        'c',
        name,
        null,
        (-1 * Math.abs(delta || 1))
    ));
    process.nextTick(cb);
};

proto.immediateCounter = function (name, value, cb) {
    this._write(new NullStatsdRecord(
        'c',
        name,
        null,
        value
    ));
    process.nextTick(cb);
};

proto.immediateTiming = function (name, time, cb) {
    this._write(new NullStatsdRecord(
        'ms',
        name,
        null,
        null,
        time
    ));
    process.nextTick(cb);
};

proto.getChildClient = function() {
    return new NullStatsd(this._buffer.capacity());
};

<commit_msg>replicate shared buffer behavior in null statsd<commit_after>'use strict';

var RingBuffer = require('ringbufferjs');

module.exports = NullStatsd;

function NullStatsd(opts, _buffer) {
    if (!(this instanceof NullStatsd)) {
        return new NullStatsd(opts, _buffer);
    }
    opts = opts || {};

    this._buffer = _buffer || new RingBuffer(opts.capacity || 50);

    var prefix = opts.prefix;

    this.prefix = prefix ?
        (prefix[prefix.length - 1] === '.' ? prefix : prefix + '.') :
        '';
}

function NullStatsdRecord(type, name, value, delta, time) {
    this.type = type;
    this.name = name;
    this.value = value || null;
    this.delta = delta || null;
    this.time = time || null;
}

var proto = NullStatsd.prototype;

proto._write = function _write(record) {
    this._buffer.enq(record);
};

proto.gauge = function gauge(name, value) {
    this._write(new NullStatsdRecord('g', this.prefix + name, value));
};

proto.counter = function counter(name, value) {
    this._write(new NullStatsdRecord('c', this.prefix + name, null, value));
};

proto.increment = function increment(name, delta) {
    this._write(new NullStatsdRecord(
        'c',
        this.prefix + name,
        null,
        delta || 1
    ));
};

proto.decrement = function decrement(name, delta) {
    this._write(new NullStatsdRecord(
        'c',
        this.prefix + name,
        null,
        (-1 * Math.abs(delta || 1))
    ));
};

proto.timing = function timing(name, time) {
    this._write(new NullStatsdRecord(
        'ms',
        this.prefix + name,
        null,
        null,
        time
    ));
};

proto.close = function close() {
    for (var i = 0, len = this._buffer.size(); i < len; i++) {
        this._buffer.deq();
    }
};

proto.immediateGauge = function (name, value, cb) {
    this._write(new NullStatsdRecord(
        'g',
        this.prefix + name,
        value
    ));
    process.nextTick(cb);
};

proto.immediateIncrement = function (name, delta, cb) {
    this._write(new NullStatsdRecord(
        'c',
        this.prefix + name,
        null,
        delta || 1
    ));
    process.nextTick(cb);
};

proto.immediateDecrement = function (name, delta, cb) {
    this._write(new NullStatsdRecord(
        'c',
        this.prefix + name,
        null,
        (-1 * Math.abs(delta || 1))
    ));
    process.nextTick(cb);
};

proto.immediateCounter = function (name, value, cb) {
    this._write(new NullStatsdRecord(
        'c',
        this.prefix + name,
        null,
        value
    ));
    process.nextTick(cb);
};

proto.immediateTiming = function (name, time, cb) {
    this._write(new NullStatsdRecord(
        'ms',
        this.prefix + name,
        null,
        null,
        time
    ));
    process.nextTick(cb);
};

proto.getChildClient = function(extraPrefix) {
    return new NullStatsd({
        prefix: this.prefix + extraPrefix
    }, this._buffer);
};
<|endoftext|>


<commit_before>// @flow
import React from 'react';
import _ from 'lodash';

import { Dropdown, Input } from 'react-toolbox';

type Props = {
  onChange: (value: string) => any,
  source: { value: string, label: string }[],
  hasData: boolean,
  value: ?string,
};

const DeviceField = ({ onChange, source, hasData, value }: Props) => {
  const entry = _.find(source, { value: value });
  const text = !entry ? 'No device present' : entry.label;
  return source.length > 1
    ? <Dropdown auto label='Device' onChange={onChange} source={source} value={value} />
    : hasData
      ? <Input auto label='Device' readOnly value={text} />
      : <Input auto label='Device' readOnly value='Loading devices ...' />;
};

export default DeviceField;
<commit_msg>show how many users we have<commit_after>// @flow
import React from 'react';
import _ from 'lodash';

import { Dropdown, Input } from 'react-toolbox';

type Props = {
  onChange: (value: string) => any,
  source: { value: string, label: string }[],
  hasData: boolean,
  value: ?string,
};

const DeviceField = ({ onChange, source, hasData, value }: Props) => {
  const entry = _.find(source, { value: value });
  const text = !entry ? 'No users present' : entry.label;
  return source.length > 1
    ? <Dropdown auto label={`Users (${source.length})`} onChange={onChange} source={source} value={value} />
    : hasData
      ? <Input auto label={`Users (${source.length})`} readOnly value={text} />
      : <Input auto label='Users' readOnly value='Loading users ...' />;
};

export default DeviceField;
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { autobind } from 'core-decorators';
import { connect } from 'react-redux';
import { Button, Dialog, EditableText, Spinner, Icon, Intent, Hotkey, Hotkeys, HotkeysTarget, Toaster, Position } from '@blueprintjs/core';
import { gql, graphql, compose } from 'react-apollo';
import DateFormat from 'dateformat';
import { saveState } from '../../../actions/stateActions';
import NotificationToaster from '../NotificationToaster';
import FormInput from '../../../../../lib/react/components/forms/FormInput';
import '../../scss/admin/_user-profile.scss';

const QueryUser = gql`
query GetUserByEmail($email:String!) {
  getUserByEmail(email: $email) {
    firstname lastname
    username email isAdmin
    university studentID
    mobileNumber enabled
    registerDate paidAmount
    raceDetails{ hasSmartphone friends PTProficiency dietaryRequirements }
    roles permissions
  }
}`;

const QueryUserOptions = {
	name: 'QueryUser',
	options: (props) => ({
		variables: { email: props.user.email },
		fetchPolicy: 'cache-and-network'
	})
}

const MutationSetUserPaidAmount = gql`
mutation SetPaidAmount($username:String!, $amount:Float!){
  setUserPaidAmount(username:$username, amount:$amount){
    ok
    failureMessage
  }
}`;

const MutationAddPermission = gql`
mutation AddPermission($permission:String!, $username:String!){
	addPermission(permission:$permission, username:$username){
		ok
	}
}`;

const MutationRemovePermission = gql`
mutation RemovePermission($permission:String!, $username:String!){
	removePermission(permission:$permission, username:$username){
		ok
	}
}`;

@compose(
	graphql(QueryUser, QueryUserOptions),
	graphql(MutationSetUserPaidAmount, {name: 'MutationSetUserPaidAmount'}),
	graphql(MutationAddPermission, {name: 'MutationAddPermission'}),
	graphql(MutationRemovePermission, {name: 'MutationRemovePermission'})
)
@connect()
@autobind
@HotkeysTarget
class UserProfile extends React.Component {
	static propTypes = {
		user: PropTypes.object.isRequired,
		closeProfile: PropTypes.func.isRequired,
		paymentAmount: PropTypes.number.isRequired
	}

	state = {
		paidAmount: null,
		saving: false,
		error: null,
		showAddPermissionDialog: false,
		addPermissionText: '',
		addPermissionLoading: false,
		addPermissionError: null,
		showRemovePermissionDialog: false,
		permissionToRemove: null
	}

	componentDidMount() {
		this._mounted = true;
	}

	componentWillUnmount() {
		this._mounted = false;
	}

	closeProfile() {
		this.props.closeProfile();
	}

	editPaid(value) {
		this.setState({paidAmount: value});
	}

	confirmPaid(value) {
		if (value.length > 0) {
			const regex = /^[0-9]+(\.|)[0-9]{0,2}$/;
			if (regex.exec(value)) {
				this.savePaid();
				return;
			}
		}
		this.setState({paidAmount: this.props.QueryUser.getUserByEmail.paidAmount});
	}

	savePaid() {
		this.setState({ saving: true, error: null });

		let variables = {
			username: this.props.QueryUser.getUserByEmail.username,
			amount: this.state.paidAmount
		};

		this.props.MutationSetUserPaidAmount({ variables })
		.then((result) => {
			if (result.data.setUserPaidAmount.ok) {
				this._refetchUser();
			}
			else {
				if (this._mounted) this.setState({saving: false});
				NotificationToaster.show({
					intent: Intent.DANGER,
					message: result.data.setUserPaidAmount.failureMessage
				});
			}
		})
		.catch((err) => {
			if (this._mounted) this.setState({saving: false});
			NotificationToaster.show({
				intent: Intent.DANGER,
				message: err.toString()
			});
		});
	}

	_refetchUser() {
		if (this._mounted) this.setState({saving: true});
		this.props.QueryUser.refetch()
		.then(() => {
			this.props.dispatch(saveState());
			if (this._mounted) this.setState({saving: false});
		});
	}

	renderHotkeys() {
		return (
			<Hotkeys>
				<Hotkey
					global={true}
					combo='esc'
					label='Close profile'
					onKeyDown={this.closeProfile}
				/>
			</Hotkeys>
		);
	}

	toggleAddPermission() {
		this._toggleDialog('showAddPermissionDialog', 'addPermissionText', 'addPermissionError');
	}

	toggleRemovePermission(permissionToRemove) {
		return () => {
			this.setState({permissionToRemove})
			this._toggleDialog('showRemovePermissionDialog', 'removePermissionText', 'removePermissionError');
		}
	}

	_toggleDialog(name, text, error) {
		this.setState((prevState) => {
			return {
				[name]: !prevState[name],
				[text]: '',
				[error]: null
			 };
		});
	}

	addPermissionChange({ target: { value }}) {
		this.setState({addPermissionText: value});
	}

	submitAddPermission() {
		this._submitPermissionChange('add', 'Add', this.state.addPermissionText);
	}

	submitRemovePermission() {
		this._submitPermissionChange('remove', 'Remove', this.state.permissionToRemove);
	}

	_submitPermissionChange(type, Type, permission) {
		this.setState({[`${type}PermissionLoading`]: true, [`${type}PermissionError`]: null});
		this.props.MutationAddPermission
		this.props[`Mutation${Type}Permission`]({
			variables: {
				username: this.props.user.username,
				permission: permission
			}
		})
		.then((result) => {
			if (result.data[`${type}Permission`].ok) {
				this.setState({
					[`${type}PermissionLoading`]: false,
					[`show${Type}PermissionDialog`]: false,
					saving: true
				});
				this._refetchUser();
			}
			else {
				if (this._mounted) {
					this.setState({
						[`${type}PermissionLoading`]: false,
						[`${type}PermissionError`]: result.data[`${type}Permission`].failureMessage
					});
				}
			}
		})
		.catch((err) => {
			this.setState({
				[`${type}PermissionLoading`]: false,
				[`${type}PermissionError`]: err.toString()
			});
		});
	}

	render() {
		let { firstname, lastname, email, university } = this.props.user;
		let content;
		let showLoadingIndicator = false;

		if (this.props.QueryUser.loading) {
			showLoadingIndicator = true;
		}

		if (this.props.QueryUser.getUserByEmail) {
			let {
				username, mobileNumber, studentID, isAdmin,
				registerDate, paidAmount, permissions,
				raceDetails: {
					PTProficiency, hasSmartphone,
					friends, dietaryRequirements
				}
			} = this.props.QueryUser.getUserByEmail;

			if (this.state.paidAmount === null) {
				setTimeout(() => {
					this.setState({paidAmount});
				}, 0);
			}

			let paidIcon = <Icon iconName='error' intent={Intent.DANGER}/>;
			if (parseFloat(this.state.paidAmount) >= this.props.paymentAmount) {
				paidIcon = <Icon iconName='tick' intent={Intent.SUCCESS}/>;
			}

			if (this.state.saving) {
				showLoadingIndicator = true;
			}

			content = (

								Username
								{username}

								Email
								{email}

								Mobile
								{mobileNumber}

								Paid {paidIcon}

									$<EditableText value={this.state.paidAmount}
										onChange={this.editPaid} selectAllOnFocus
										onConfirm={this.confirmPaid}/>

								Student ID
								{studentID}

								Register date
								{DateFormat(new Date(registerDate), 'mmm dd yyyy hh:MM TT')}

								PT Proficiency
								{PTProficiency}

								Has smartphone
								{hasSmartphone ? 'Yes' : 'No' }

								Friends
								{friends ? friends : 'None'}

								Dietary Requirements
								{dietaryRequirements ? dietaryRequirements : 'None'}

								Admin
								{isAdmin ? 'true':'false'}

									Account Permissions

									<Button style={{marginTop: '0.5rem'}} onClick={this.toggleAddPermission}
										iconName='add' text='Add permission' className='pt-button pt-icon-add pt-small'/>

										{ permissions.map((permission, index) => {
												return (

														<Button iconName='remove' className='pt-small pt-minimal'
															intent={Intent.DANGER} onClick={this.toggleRemovePermission(permission)}
															loading={this.state[permission+'RemoveLoading']}/>
														{permission}

												);
										}) }

			);
		}

		return (

				<Button className='pt-minimal' intent={Intent.DANGER} text='Close' onClick={this.closeProfile} style={{float:'right'}}/>
				{showLoadingIndicator ?

						<Spinner className='pt-small'/>

				: null }

{firstname + ' ' + lastname}

{university}

				{content}

				{/* Add permission dialog */}
				<Dialog title='Add new permission to user'
					isOpen={this.state.showAddPermissionDialog} onClose={this.toggleAddPermission}>

						{this.state.addPermissionError ?

								{this.state.addPermissionError}

							:null}
						<FormInput id='permission' value={this.state.addPermissionText}
							onChange={this.addPermissionChange}
							label='Permission:' disabled={this.state.addPermissionLoading}
							intent={this.state.addPermissionError?Intent.DANGER:Intent.NONE}/>

							<Button className='pt-minimal' onClick={this.toggleAddPermission} disabled={this.state.addPermissionLoading}>Cancel</Button>
							<Button className='pt-intent-primary' onClick={this.submitAddPermission} loading={this.state.addPermissionLoading}>Add</Button>

				</Dialog>

				{/* Remove permission dialog */}
				<Dialog title='Remove user permission'
					isOpen={this.state.showRemovePermissionDialog} onClose={this.toggleRemovePermission(null)}>

						{this.state.removePermissionError ?

								{this.state.removePermissionError}

							:null}

								Are you sure yu want to remove the permission {this.state.permissionToRemove} from the user?

							<Button className='pt-minimal' onClick={this.toggleRemovePermission(null)} disabled={this.state.removePermissionLoading}>Cancel</Button>
							<Button className='pt-intent-danger' onClick={this.submitRemovePermission} loading={this.state.removePermissionLoading}>Remove</Button>

				</Dialog>

		);
	}
}

export default UserProfile;
<commit_msg>[FIX] Remove unused line of code<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { autobind } from 'core-decorators';
import { connect } from 'react-redux';
import { Button, Dialog, EditableText, Spinner, Icon, Intent, Hotkey, Hotkeys, HotkeysTarget, Toaster, Position } from '@blueprintjs/core';
import { gql, graphql, compose } from 'react-apollo';
import DateFormat from 'dateformat';
import { saveState } from '../../../actions/stateActions';
import NotificationToaster from '../NotificationToaster';
import FormInput from '../../../../../lib/react/components/forms/FormInput';
import '../../scss/admin/_user-profile.scss';

const QueryUser = gql`
query GetUserByEmail($email:String!) {
  getUserByEmail(email: $email) {
    firstname lastname
    username email isAdmin
    university studentID
    mobileNumber enabled
    registerDate paidAmount
    raceDetails{ hasSmartphone friends PTProficiency dietaryRequirements }
    roles permissions
  }
}`;

const QueryUserOptions = {
	name: 'QueryUser',
	options: (props) => ({
		variables: { email: props.user.email },
		fetchPolicy: 'cache-and-network'
	})
}

const MutationSetUserPaidAmount = gql`
mutation SetPaidAmount($username:String!, $amount:Float!){
  setUserPaidAmount(username:$username, amount:$amount){
    ok
    failureMessage
  }
}`;

const MutationAddPermission = gql`
mutation AddPermission($permission:String!, $username:String!){
	addPermission(permission:$permission, username:$username){
		ok
	}
}`;

const MutationRemovePermission = gql`
mutation RemovePermission($permission:String!, $username:String!){
	removePermission(permission:$permission, username:$username){
		ok
	}
}`;

@compose(
	graphql(QueryUser, QueryUserOptions),
	graphql(MutationSetUserPaidAmount, {name: 'MutationSetUserPaidAmount'}),
	graphql(MutationAddPermission, {name: 'MutationAddPermission'}),
	graphql(MutationRemovePermission, {name: 'MutationRemovePermission'})
)
@connect()
@autobind
@HotkeysTarget
class UserProfile extends React.Component {
	static propTypes = {
		user: PropTypes.object.isRequired,
		closeProfile: PropTypes.func.isRequired,
		paymentAmount: PropTypes.number.isRequired
	}

	state = {
		paidAmount: null,
		saving: false,
		error: null,
		showAddPermissionDialog: false,
		addPermissionText: '',
		addPermissionLoading: false,
		addPermissionError: null,
		showRemovePermissionDialog: false,
		permissionToRemove: null
	}

	componentDidMount() {
		this._mounted = true;
	}

	componentWillUnmount() {
		this._mounted = false;
	}

	closeProfile() {
		this.props.closeProfile();
	}

	editPaid(value) {
		this.setState({paidAmount: value});
	}

	confirmPaid(value) {
		if (value.length > 0) {
			const regex = /^[0-9]+(\.|)[0-9]{0,2}$/;
			if (regex.exec(value)) {
				this.savePaid();
				return;
			}
		}
		this.setState({paidAmount: this.props.QueryUser.getUserByEmail.paidAmount});
	}

	savePaid() {
		this.setState({ saving: true, error: null });

		let variables = {
			username: this.props.QueryUser.getUserByEmail.username,
			amount: this.state.paidAmount
		};

		this.props.MutationSetUserPaidAmount({ variables })
		.then((result) => {
			if (result.data.setUserPaidAmount.ok) {
				this._refetchUser();
			}
			else {
				if (this._mounted) this.setState({saving: false});
				NotificationToaster.show({
					intent: Intent.DANGER,
					message: result.data.setUserPaidAmount.failureMessage
				});
			}
		})
		.catch((err) => {
			if (this._mounted) this.setState({saving: false});
			NotificationToaster.show({
				intent: Intent.DANGER,
				message: err.toString()
			});
		});
	}

	_refetchUser() {
		if (this._mounted) this.setState({saving: true});
		this.props.QueryUser.refetch()
		.then(() => {
			this.props.dispatch(saveState());
			if (this._mounted) this.setState({saving: false});
		});
	}

	renderHotkeys() {
		return (
			<Hotkeys>
				<Hotkey
					global={true}
					combo='esc'
					label='Close profile'
					onKeyDown={this.closeProfile}
				/>
			</Hotkeys>
		);
	}

	toggleAddPermission() {
		this._toggleDialog('showAddPermissionDialog', 'addPermissionText', 'addPermissionError');
	}

	toggleRemovePermission(permissionToRemove) {
		return () => {
			this.setState({permissionToRemove})
			this._toggleDialog('showRemovePermissionDialog', 'removePermissionText', 'removePermissionError');
		}
	}

	_toggleDialog(name, text, error) {
		this.setState((prevState) => {
			return {
				[name]: !prevState[name],
				[text]: '',
				[error]: null
			 };
		});
	}

	addPermissionChange({ target: { value }}) {
		this.setState({addPermissionText: value});
	}

	submitAddPermission() {
		this._submitPermissionChange('add', 'Add', this.state.addPermissionText);
	}

	submitRemovePermission() {
		this._submitPermissionChange('remove', 'Remove', this.state.permissionToRemove);
	}

	_submitPermissionChange(type, Type, permission) {
		this.setState({[`${type}PermissionLoading`]: true, [`${type}PermissionError`]: null});

		this.props[`Mutation${Type}Permission`]({
			variables: {
				username: this.props.user.username,
				permission: permission
			}
		})
		.then((result) => {
			if (result.data[`${type}Permission`].ok) {
				this.setState({
					[`${type}PermissionLoading`]: false,
					[`show${Type}PermissionDialog`]: false,
					saving: true
				});
				this._refetchUser();
			}
			else {
				if (this._mounted) {
					this.setState({
						[`${type}PermissionLoading`]: false,
						[`${type}PermissionError`]: result.data[`${type}Permission`].failureMessage
					});
				}
			}
		})
		.catch((err) => {
			this.setState({
				[`${type}PermissionLoading`]: false,
				[`${type}PermissionError`]: err.toString()
			});
		});
	}

	render() {
		let { firstname, lastname, email, university } = this.props.user;
		let content;
		let showLoadingIndicator = false;

		if (this.props.QueryUser.loading) {
			showLoadingIndicator = true;
		}

		if (this.props.QueryUser.getUserByEmail) {
			let {
				username, mobileNumber, studentID, isAdmin,
				registerDate, paidAmount, permissions,
				raceDetails: {
					PTProficiency, hasSmartphone,
					friends, dietaryRequirements
				}
			} = this.props.QueryUser.getUserByEmail;

			if (this.state.paidAmount === null) {
				setTimeout(() => {
					this.setState({paidAmount});
				}, 0);
			}

			let paidIcon = <Icon iconName='error' intent={Intent.DANGER}/>;
			if (parseFloat(this.state.paidAmount) >= this.props.paymentAmount) {
				paidIcon = <Icon iconName='tick' intent={Intent.SUCCESS}/>;
			}

			if (this.state.saving) {
				showLoadingIndicator = true;
			}

			content = (

								Username
								{username}

								Email
								{email}

								Mobile
								{mobileNumber}

								Paid {paidIcon}

									$<EditableText value={this.state.paidAmount}
										onChange={this.editPaid} selectAllOnFocus
										onConfirm={this.confirmPaid}/>

								Student ID
								{studentID}

								Register date
								{DateFormat(new Date(registerDate), 'mmm dd yyyy hh:MM TT')}

								PT Proficiency
								{PTProficiency}

								Has smartphone
								{hasSmartphone ? 'Yes' : 'No' }

								Friends
								{friends ? friends : 'None'}

								Dietary Requirements
								{dietaryRequirements ? dietaryRequirements : 'None'}

								Admin
								{isAdmin ? 'true':'false'}

									Account Permissions

									<Button style={{marginTop: '0.5rem'}} onClick={this.toggleAddPermission}
										iconName='add' text='Add permission' className='pt-button pt-icon-add pt-small'/>

										{ permissions.map((permission, index) => {
												return (

														<Button iconName='remove' className='pt-small pt-minimal'
															intent={Intent.DANGER} onClick={this.toggleRemovePermission(permission)}
															loading={this.state[permission+'RemoveLoading']}/>
														{permission}

												);
										}) }

			);
		}

		return (

				<Button className='pt-minimal' intent={Intent.DANGER} text='Close' onClick={this.closeProfile} style={{float:'right'}}/>
				{showLoadingIndicator ?

						<Spinner className='pt-small'/>

				: null }

{firstname + ' ' + lastname}

{university}

				{content}

				{/* Add permission dialog */}
				<Dialog title='Add new permission to user'
					isOpen={this.state.showAddPermissionDialog} onClose={this.toggleAddPermission}>

						{this.state.addPermissionError ?

								{this.state.addPermissionError}

							:null}
						<FormInput id='permission' value={this.state.addPermissionText}
							onChange={this.addPermissionChange}
							label='Permission:' disabled={this.state.addPermissionLoading}
							intent={this.state.addPermissionError?Intent.DANGER:Intent.NONE}/>

							<Button className='pt-minimal' onClick={this.toggleAddPermission} disabled={this.state.addPermissionLoading}>Cancel</Button>
							<Button className='pt-intent-primary' onClick={this.submitAddPermission} loading={this.state.addPermissionLoading}>Add</Button>

				</Dialog>

				{/* Remove permission dialog */}
				<Dialog title='Remove user permission'
					isOpen={this.state.showRemovePermissionDialog} onClose={this.toggleRemovePermission(null)}>

						{this.state.removePermissionError ?

								{this.state.removePermissionError}

							:null}

								Are you sure yu want to remove the permission {this.state.permissionToRemove} from the user?

							<Button className='pt-minimal' onClick={this.toggleRemovePermission(null)} disabled={this.state.removePermissionLoading}>Cancel</Button>
							<Button className='pt-intent-danger' onClick={this.submitRemovePermission} loading={this.state.removePermissionLoading}>Remove</Button>

				</Dialog>

		);
	}
}

export default UserProfile;
<|endoftext|>


<commit_before>const fs = require('fs')
const defs = require('./const')

/**
 * Class containing all level attributes.
 */
class Level {
  constructor () {
    this.version = 'Elma'
    this.link = 0
    this.integrity = [0.0, 0.0, 0.0, 0.0]
    this.lgr = 'default'
    this.name = 'New level'
    this.ground = 'ground'
    this.sky = 'sky'
    this.polygons = [{ grass: false, vertices: [{ x: 10.0, y: 0.0 }, { x: 10.0, y: 7.0 }, { x: 0.0, y: 7.0 }, { x: 0.0, y: 0.0 }] }]
    this.objects = [{ position: { x: 2.0, y: 7.0 - defs.OBJECT_RADIUS }, type: 'start' },
                    { position: { x: 8.0, y: 7.0 - defs.OBJECT_RADIUS }, type: 'exit' }]
    this.pictures = []
    this.top10 = {
      single: [],
      multi: []
    }
  }

  /**
   * Loads a level from file.
   * @param {string} filePath Path to file
   * @returns {Promise} Promise
   */
  static load (filePath) {
    return new Promise((resolve, reject) => {
      fs.readFile(filePath, (error, buffer) => {
        if (error) reject(error)
        let level = new Level()
        resolve(level)
      })
    })
  }

  /**
   * Internal convinience method.
   * @returns {Promise} Promise
   */
  _update () {
    return new Promise((resolve, reject) => {
      if (true) resolve()
      reject()
    })
  }

  /**
   * Toplogy check
   * @returns {Promise} Promise
   */
  _checkTopology () {
    return new Promise((resolve, reject) => {
      if (true) resolve()
      reject()
    })
  }

  /**
   * Returns raw buffer data
   * @returns {Promise} Promise
   */
  toBuffer () {
    return new Promise((resolve, reject) => {
      if (true) resolve()
      reject()
    })
  }

  /**
   * Generate new link number.
   */
  generateLink () {
    let max32 = Math.pow(2, 32) - 1
    this.link = Math.floor(Math.random() * max32)
  }

  /**
   * Saves a level to file.
   * @param {string} filePath Path to file
   * @returns {Promise} Promise
   */
  save (filePath) {
    return new Promise()
  }
}

module.exports = Level
<commit_msg>Uppercase DEFS<commit_after>const fs = require('fs')
const DEFS = require('./const')

/**
 * Class containing all level attributes.
 */
class Level {
  constructor () {
    this.version = 'Elma'
    this.link = 0
    this.integrity = [0.0, 0.0, 0.0, 0.0]
    this.lgr = 'default'
    this.name = 'New level'
    this.ground = 'ground'
    this.sky = 'sky'
    this.polygons = [{ grass: false, vertices: [{ x: 10.0, y: 0.0 }, { x: 10.0, y: 7.0 }, { x: 0.0, y: 7.0 }, { x: 0.0, y: 0.0 }] }]
    this.objects = [{ position: { x: 2.0, y: 7.0 - DEFS.OBJECT_RADIUS }, type: 'start' },
                    { position: { x: 8.0, y: 7.0 - DEFS.OBJECT_RADIUS }, type: 'exit' }]
    this.pictures = []
    this.top10 = {
      single: [],
      multi: []
    }
  }

  /**
   * Loads a level from file.
   * @param {string} filePath Path to file
   * @returns {Promise} Promise
   */
  static load (filePath) {
    return new Promise((resolve, reject) => {
      fs.readFile(filePath, (error, buffer) => {
        if (error) reject(error)
        let level = new Level()
        resolve(level)
      })
    })
  }

  /**
   * Internal convinience method.
   * @returns {Promise} Promise
   */
  _update () {
    return new Promise((resolve, reject) => {
      if (true) resolve()
      reject()
    })
  }

  /**
   * Toplogy check
   * @returns {Promise} Promise
   */
  _checkTopology () {
    return new Promise((resolve, reject) => {
      if (true) resolve()
      reject()
    })
  }

  /**
   * Returns raw buffer data
   * @returns {Promise} Promise
   */
  toBuffer () {
    return new Promise((resolve, reject) => {
      if (true) resolve()
      reject()
    })
  }

  /**
   * Generate new link number.
   */
  generateLink () {
    let max32 = Math.pow(2, 32) - 1
    this.link = Math.floor(Math.random() * max32)
  }

  /**
   * Saves a level to file.
   * @param {string} filePath Path to file
   * @returns {Promise} Promise
   */
  save (filePath) {
    return new Promise()
  }
}

module.exports = Level
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import uuid from 'uuid';
import _ from 'lodash';
// eslint-disable-next-line import/no-extraneous-dependencies
import moment from 'moment';
import { Callout } from '@folio/stripes/components';
import { FormattedMessage } from 'react-intl';
import ChargeForm from './ChargeForm';
import ItemLookup from './ItemLookup';
import PayModal from '../Actions/PayModal';
import { getFullName } from '../../../util';

class Charge extends React.Component {
  static manifest = Object.freeze({
    items: {
      type: 'okapi',
      records: 'items',
      path: 'inventory/items?query=barcode=%{activeRecord.barcode}*',
    },
    feefines: {
      type: 'okapi',
      records: 'feefines',
      GET: {
        path: 'feefines?query=(ownerId=%{activeRecord.ownerId} or ownerId=%{activeRecord.shared})&limit=100',
      },
    },
    feefineactions: {
      type: 'okapi',
      records: 'feefineactions',
      path: 'feefineactions',
    },
    owners: {
      type: 'okapi',
      records: 'owners',
      path: 'owners?limit=100',
    },
    accounts: {
      type: 'okapi',
      records: 'accounts',
      path: 'accounts',
      PUT: {
        path: 'accounts/%{activeRecord.id}'
      },
    },
    account: {
      type: 'okapi',
      resource: 'accounts',
      accumulate: 'true',
      path: 'accounts',
    },
    payments: {
      type: 'okapi',
      records: 'payments',
      path: 'payments',
    },
    commentRequired: {
      type: 'okapi',
      records: 'comments',
      path: 'comments',
    },
    allfeefines: {
      type: 'okapi',
      records: 'feefines',
      path: 'feefines?limit=100',
    },
    activeRecord: {},
  });

  static propTypes = {
    resources: PropTypes.shape({
      feefines: PropTypes.shape({
        records: PropTypes.arrayOf(PropTypes.object),
      }),
      owners: PropTypes.shape({
        records: PropTypes.arrayOf(PropTypes.object),
      }),
      activeRecord: PropTypes.object,
    }).isRequired,
    mutator: PropTypes.shape({
      accounts: PropTypes.shape({
        POST: PropTypes.func.isRequired,
        PUT: PropTypes.func.isRequired,
      }),
      feefineactions: PropTypes.shape({
        POST: PropTypes.func.isRequired,
      }),
      activeRecord: PropTypes.shape({
        update: PropTypes.func,
      }),
    }).isRequired,
    stripes: PropTypes.object.isRequired,
    onCloseChargeFeeFine: PropTypes.func.isRequired,
    handleAddRecords: PropTypes.func,
    okapi: PropTypes.object,
    selectedLoan: PropTypes.object,
    user: PropTypes.object,
  };

  constructor(props) {
    super(props);
    this.state = {
      ownerId: '0',
      lookup: false,
      pay: false,
    };
    this.onClickCharge = this.onClickCharge.bind(this);
    this.onClickSelectItem = this.onClickSelectItem.bind(this);
    this.onChangeOwner = this.onChangeOwner.bind(this);
    this.onFindShared = this.onFindShared.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
    this.item = {};
    this.onCloseModal = this.onCloseModal.bind(this);
    this.onChangeItem = this.onChangeItem.bind(this);
    this.onClosePayModal = this.onClosePayModal.bind(this);
    this.onClickPay = this.onClickPay.bind(this);
    this.type = {};
    this.callout = null;
  }

  shouldComponentUpdate(nextProps) {
    const items = _.get(this.props.resources, ['items', 'records'], []);
    const nextItems = _.get(nextProps.resources, ['items', 'records'], []);
    const barcode = _.get(this.props.resources, ['activeRecord', 'barcode']);
    if (nextItems.length === 1 && barcode !== null) {
      if (nextItems[0].barcode === barcode) this.item = nextItems[0];
    }

    if (items !== nextItems) {
      this.setState({
        lookup: true,
      });
    }

    return true;
  }

  componentWillUnmount() {
    this.item = {};
    this.props.mutator.activeRecord.update({ barcode: null });
  }

  onClickCharge(type) {
    const owners = _.get(this.props.resources, ['owners', 'records'], []);
    const feefines = _.get(this.props.resources, ['feefines', 'records'], []);
    const { selectedLoan } = this.props;
    const item = (selectedLoan.id) ? selectedLoan.item : this.item;

    type.paymentStatus = {
      name: 'Outstanding',
    };
    type.status = {
      name: 'Open',
    };
    type.remaining = type.amount;
    type.feeFineType = (feefines.find(f => f.id === type.feeFineId.substring(0, 36)) || {}).feeFineType || '';
    type.feeFineOwner = (owners.find(o => o.id === type.ownerId) || {}).owner || '';
    type.title = item.title;
    type.barcode = item.barcode;
    type.callNumber = item.callNumber;
    type.location = (selectedLoan.id) ? (item.location || {}).name : (item.effectiveLocation || {}).name;
    type.materialType = (item.materialType || {}).name;
    type.materialTypeId = (selectedLoan.id) ? '0' : (item.materialType || {}).id || '0';

    if (selectedLoan.dueDate) type.dueDate = selectedLoan.dueDate;
    if (selectedLoan.returnDate) type.returnedDate = selectedLoan.returnDate;
    type.id = uuid();
    type.loanId = this.props.selectedLoan.id || '0';
    type.userId = this.props.user.id;
    type.itemId = this.item.id || '0';
    const c = type.comments;
    delete type.comments;
    this.type = type;
    return this.props.mutator.accounts.POST(type)
      .then(() => this.newAction({}, type.id, type.feeFineType, type.amount, c, type.remaining, 0, type.feeFineOwner));
  }

  newAction = (action, id, typeAction, amount, comment, balance, transaction, createdAt) => {
    const path = `accounts/${this.type.id}`;
    return this.props.mutator.account.GET({ path }).then(record => {
      const dateAction = _.get(record, ['metadata', 'updatedDate'], moment().format());

      const newAction = {
        typeAction,
        source: `${this.props.okapi.currentUser.lastName}, ${this.props.okapi.currentUser.firstName}`,
        createdAt,
        accountId: id,
        dateAction,
        userId: this.props.user.id,
        amountAction: parseFloat(amount || 0).toFixed(2),
        balance: parseFloat(balance || 0).toFixed(2),
        transactionInformation: transaction || '-',
        comments: comment,
      };
      this.props.mutator.feefineactions.POST(Object.assign(action, newAction));
    });
  }

  onClickPay(type) {
    this.type = type;
    this.type.remaining = type.amount;
    this.setState({
      pay: true,
    });
    return new Promise((resolve, reject) => {
      this.payResolve = resolve;
      this.payReject = reject;
    });
  }

  onSubmit(data) {
    this.log('xhr', data);
  }

  onClosePayModal() {
    this.setState({
      pay: false,
    });
  }

  onClickSelectItem(barcode) {
    if (barcode !== '') {
      this.props.mutator.activeRecord.update({ barcode });
      if ((this.props.resources.activeRecord || {}).barcode === barcode) {
        this.setState({
          lookup: true,
        });
      }
    }
  }

  onChangeOwner(e) {
    const ownerId = e.target.value;
    if (_.get(this.props.resources, ['activeRecord', 'shared']) === undefined) {
      const owners = _.get(this.props.resources, ['owners', 'records'], []);
      const shared = (owners.find(o => o.owner === 'Shared') || {}).id || '0';
      this.props.mutator.activeRecord.update({ shared });
    }
    this.props.mutator.activeRecord.update({ ownerId });
    this.setState({
      ownerId,
    });
  }

  onChangeItem(item) {
    this.item = item;
  }

  onFindShared(id) {
    this.props.mutator.activeRecord.update({ shared: id });
  }

  onCloseModal() {
    this.setState({
      lookup: false,
    });
  }

  showCalloutMessage(a) {
    const message =

        <FormattedMessage id="ui-users.charge.messageThe" />
        {a.feeFineType}
        <FormattedMessage id="ui-users.charge.messageOf" />
        {`${parseFloat(a.amount).toFixed(2)}`}
        <FormattedMessage id="ui-users.charge.messageSuccessfully" />
        {a.paymentStatus.name}
        <FormattedMessage id="ui-users.charge.messageFor" />
        {`${getFullName(this.props.user)}`}
      ;
    this.callout.sendCallout({ message });
  }

  render() {
    const resources = this.props.resources;
    const allfeefines = _.get(resources, ['allfeefines', 'records'], []);
    const owners = _.get(resources, ['owners', 'records'], []);
    const list = [];
    const shared = owners.find(o => o.owner === 'Shared'); // Crear variable Shared en translations
    allfeefines.forEach(f => {
      if (!list.find(o => (o || {}).id === f.ownerId)) {
        list.push(owners.find(o => (o || {}).id === f.ownerId));
      }
    });
    const feefines = (this.state.ownerId !== '0') ? (resources.feefines || {}).records || [] : [];
    const payments = _.get(resources, ['payments', 'records'], []);
    const accounts = _.get(resources, ['accounts', 'records'], []);
    const settings = _.get(this.props.resources, ['commentRequired', 'records', 0], {});

    let selected = parseFloat(0);
    accounts.forEach(a => {
      selected += parseFloat(a.remaining);
    });
    parseFloat(selected).toFixed(2);
    const item = {
      id: this.item.id || '',
      instance: this.item.title || '',
      barcode: this.item.barcode || '',
      itemStatus: (this.item.status || {}).name || '',
      callNumber: this.item.callNumber || '',
      location: (this.item.effectiveLocation || {}).name || '',
      type: (this.item.materialType || {}).name || '',
    };

    const isPending = {
      owners: _.get(resources, ['owners', 'isPending'], false),
      feefines: _.get(resources, ['feefines', 'isPending'], false),
    };

    const items = _.get(resources, ['items', 'records'], []);
    return (

        <ChargeForm
          onClickCancel={this.props.onCloseChargeFeeFine}
          onClickPay={this.onClickPay}
          onSubmit={(data) => {
            if (data.pay) {
              delete data.pay;
              this.type.remaining = data.amount;
              this.onClickPay(data);
            } else {
              delete data.pay;
              this.onClickCharge(data)
                .then(() => this.props.handleAddRecords())
                .then(() => this.props.onCloseChargeFeeFine());
            }
          }}
          user={this.props.user}
          ownerList={(shared) ? owners : list}
          owners={owners}
          isPending={isPending}
          ownerId={this.state.ownerId}
          feefines={feefines}
          item={item}
          onFindShared={this.onFindShared}
          onChangeOwner={this.onChangeOwner}
          onClickSelectItem={this.onClickSelectItem}
          stripes={this.props.stripes}
          {...this.props}
        />
        <ItemLookup
          resources={this.props.resources}
          items={items}
          open={(this.state.lookup && items.length > 1)}
          onChangeItem={this.onChangeItem}
          onClose={this.onCloseModal}
        />
        <PayModal
          open={this.state.pay}
          commentRequired={settings.paid}
          onClose={this.onClosePayModal}
          accounts={[this.type]}
          balance={this.type.amount}
          payments={payments}
          stripes={this.props.stripes}
          onSubmit={(values) => {
            this.onClickCharge(this.type).then(() => {
              this.type.remaining = parseFloat(this.type.amount - values.amount).toFixed(2);
              if (this.type.remaining === '0.00') {
                this.type.paymentStatus.name = 'Paid Fully';
                this.type.status.name = 'Closed';
              } else {
                this.type.paymentStatus.name = 'Paid Partially';
              }
              this.props.mutator.activeRecord.update({ id: this.type.id });
              return this.props.mutator.accounts.PUT(this.type);
            })
              .then(() => this.newAction({ paymentMethod: values.method }, this.type.id,
                this.type.paymentStatus.name, values.amount,
                values.comment, this.type.remaining,
                values.transaction, this.type.feeFineOwner))
              .then(() => {
                this.showCalloutMessage(this.type);
                this.payResolve();
              })
              .then(() => this.props.handleAddRecords())
              .then(() => setTimeout(this.props.onCloseChargeFeeFine, 2000));
          }}
        />
        <Callout ref={(ref) => { this.callout = ref; }} />

    );
  }
}

export default Charge;
<commit_msg>Fix service point and modify payment methods<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import uuid from 'uuid';
import _ from 'lodash';
// eslint-disable-next-line import/no-extraneous-dependencies
import moment from 'moment';
import { Callout } from '@folio/stripes/components';
import { FormattedMessage } from 'react-intl';
import ChargeForm from './ChargeForm';
import ItemLookup from './ItemLookup';
import PayModal from '../Actions/PayModal';
import { getFullName } from '../../../util';

class Charge extends React.Component {
  static manifest = Object.freeze({
    curUserServicePoint: {
      type: 'okapi',
      path: 'service-points-users?query=(userId==!{currentUser.id})',
      records: 'servicePointsUsers',
    },
    items: {
      type: 'okapi',
      records: 'items',
      path: 'inventory/items?query=barcode=%{activeRecord.barcode}*',
    },
    feefines: {
      type: 'okapi',
      records: 'feefines',
      GET: {
        path: 'feefines?query=(ownerId=%{activeRecord.ownerId} or ownerId=%{activeRecord.shared})&limit=100',
      },
    },
    feefineactions: {
      type: 'okapi',
      records: 'feefineactions',
      path: 'feefineactions',
    },
    accounts: {
      type: 'okapi',
      records: 'accounts',
      path: 'accounts',
      PUT: {
        path: 'accounts/%{activeRecord.id}'
      },
    },
    account: {
      type: 'okapi',
      resource: 'accounts',
      accumulate: 'true',
      path: 'accounts',
    },
    owners: {
      type: 'okapi',
      records: 'owners',
      path: 'owners?limit=100',
    },
    payments: {
      type: 'okapi',
      records: 'payments',
      path: 'payments',
    },
    commentRequired: {
      type: 'okapi',
      records: 'comments',
      path: 'comments',
    },
    allfeefines: {
      type: 'okapi',
      records: 'feefines',
      path: 'feefines?limit=100',
    },
    activeRecord: {},
  });

  static propTypes = {
    resources: PropTypes.shape({
      feefines: PropTypes.shape({
        records: PropTypes.arrayOf(PropTypes.object),
      }),
      owners: PropTypes.shape({
        records: PropTypes.arrayOf(PropTypes.object),
      }),
      activeRecord: PropTypes.object,
    }).isRequired,
    mutator: PropTypes.shape({
      accounts: PropTypes.shape({
        POST: PropTypes.func.isRequired,
        PUT: PropTypes.func.isRequired,
      }),
      feefineactions: PropTypes.shape({
        POST: PropTypes.func.isRequired,
      }),
      activeRecord: PropTypes.shape({
        update: PropTypes.func,
      }),
    }).isRequired,
    stripes: PropTypes.object.isRequired,
    onCloseChargeFeeFine: PropTypes.func.isRequired,
    handleAddRecords: PropTypes.func,
    okapi: PropTypes.object,
    selectedLoan: PropTypes.object,
    user: PropTypes.object,
  };

  constructor(props) {
    super(props);
    this.state = {
      ownerId: '0',
      lookup: false,
      pay: false,
    };
    this.onClickCharge = this.onClickCharge.bind(this);
    this.onClickSelectItem = this.onClickSelectItem.bind(this);
    this.onChangeOwner = this.onChangeOwner.bind(this);
    this.onFindShared = this.onFindShared.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
    this.item = {};
    this.onCloseModal = this.onCloseModal.bind(this);
    this.onChangeItem = this.onChangeItem.bind(this);
    this.onClosePayModal = this.onClosePayModal.bind(this);
    this.onClickPay = this.onClickPay.bind(this);
    this.type = {};
    this.callout = null;
  }

  shouldComponentUpdate(nextProps) {
    const items = _.get(this.props.resources, ['items', 'records'], []);
    const nextItems = _.get(nextProps.resources, ['items', 'records'], []);
    const barcode = _.get(this.props.resources, ['activeRecord', 'barcode']);
    if (nextItems.length === 1 && barcode !== null) {
      if (nextItems[0].barcode === barcode) this.item = nextItems[0];
    }

    if (items !== nextItems) {
      this.setState({
        lookup: true,
      });
    }

    return true;
  }

  componentWillUnmount() {
    this.item = {};
    this.props.mutator.activeRecord.update({ barcode: null });
  }

  onClickCharge(type) {
    const owners = _.get(this.props.resources, ['owners', 'records'], []);
    const feefines = _.get(this.props.resources, ['feefines', 'records'], []);
    const { selectedLoan } = this.props;
    const item = (selectedLoan.id) ? selectedLoan.item : this.item;

    type.paymentStatus = {
      name: 'Outstanding',
    };
    type.status = {
      name: 'Open',
    };
    type.remaining = type.amount;
    type.feeFineType = (feefines.find(f => f.id === type.feeFineId.substring(0, 36)) || {}).feeFineType || '';
    type.feeFineOwner = (owners.find(o => o.id === type.ownerId) || {}).owner || '';
    type.title = item.title;
    type.barcode = item.barcode;
    type.callNumber = item.callNumber;
    type.location = (selectedLoan.id) ? (item.location || {}).name : (item.effectiveLocation || {}).name;
    type.materialType = (item.materialType || {}).name;
    type.materialTypeId = (selectedLoan.id) ? '0' : (item.materialType || {}).id || '0';

    if (selectedLoan.dueDate) type.dueDate = selectedLoan.dueDate;
    if (selectedLoan.returnDate) type.returnedDate = selectedLoan.returnDate;
    type.id = uuid();
    type.loanId = this.props.selectedLoan.id || '0';
    type.userId = this.props.user.id;
    type.itemId = this.item.id || '0';
    const c = type.comments;
    delete type.comments;
    this.type = type;
    return this.props.mutator.accounts.POST(type)
      .then(() => this.newAction({}, type.id, type.feeFineType, type.amount, c, type.remaining, 0, type.feeFineOwner));
  }

  newAction = (action, id, typeAction, amount, comment, balance, transaction, createdAt) => {
    const path = `accounts/${this.type.id}`;
    return this.props.mutator.account.GET({ path }).then(record => {
      const dateAction = _.get(record, ['metadata', 'updatedDate'], moment().format());

      const newAction = {
        typeAction,
        source: `${this.props.okapi.currentUser.lastName}, ${this.props.okapi.currentUser.firstName}`,
        createdAt,
        accountId: id,
        dateAction,
        userId: this.props.user.id,
        amountAction: parseFloat(amount || 0).toFixed(2),
        balance: parseFloat(balance || 0).toFixed(2),
        transactionInformation: transaction || '-',
        comments: comment,
      };
      this.props.mutator.feefineactions.POST(Object.assign(action, newAction));
    });
  }

  onClickPay(type) {
    this.type = type;
    this.type.remaining = type.amount;
    this.setState({
      pay: true,
    });
    return new Promise((resolve, reject) => {
      this.payResolve = resolve;
      this.payReject = reject;
    });
  }

  onSubmit(data) {
    this.log('xhr', data);
  }

  onClosePayModal() {
    this.setState({
      pay: false,
    });
  }

  onClickSelectItem(barcode) {
    if (barcode !== '') {
      this.props.mutator.activeRecord.update({ barcode });
      if ((this.props.resources.activeRecord || {}).barcode === barcode) {
        this.setState({
          lookup: true,
        });
      }
    }
  }

  onChangeOwner(e) {
    const ownerId = e.target.value;
    if (_.get(this.props.resources, ['activeRecord', 'shared']) === undefined) {
      const owners = _.get(this.props.resources, ['owners', 'records'], []);
      const shared = (owners.find(o => o.owner === 'Shared') || {}).id || '0';
      this.props.mutator.activeRecord.update({ shared });
    }
    this.props.mutator.activeRecord.update({ ownerId });
    this.setState({
      ownerId,
    });
  }

  onChangeItem(item) {
    this.item = item;
  }

  onFindShared(id) {
    this.props.mutator.activeRecord.update({ shared: id });
  }

  onCloseModal() {
    this.setState({
      lookup: false,
    });
  }

  showCalloutMessage(a) {
    const message =

        <FormattedMessage id="ui-users.charge.messageThe" />
        {a.feeFineType}
        <FormattedMessage id="ui-users.charge.messageOf" />
        {`${parseFloat(a.amount).toFixed(2)}`}
        <FormattedMessage id="ui-users.charge.messageSuccessfully" />
        {a.paymentStatus.name}
        <FormattedMessage id="ui-users.charge.messageFor" />
        {`${getFullName(this.props.user)}`}
      ;
    this.callout.sendCallout({ message });
  }

  render() {
    const resources = this.props.resources;
    const allfeefines = _.get(resources, ['allfeefines', 'records'], []);
    const owners = _.get(resources, ['owners', 'records'], []);
    const list = [];
    const shared = owners.find(o => o.owner === 'Shared'); // Crear variable Shared en translations
    allfeefines.forEach(f => {
      if (!list.find(o => (o || {}).id === f.ownerId)) {
        const owner = owners.find(o => (o || {}).id === f.ownerId);
        if (owner !== undefined) { list.push(owner); }
      }
    });
    const feefines = (this.state.ownerId !== '0') ? (resources.feefines || {}).records || [] : [];
    const payments = _.get(resources, ['payments', 'records'], []).filter(p => p.ownerId === this.state.ownerId);
    const accounts = _.get(resources, ['accounts', 'records'], []);
    const settings = _.get(this.props.resources, ['commentRequired', 'records', 0], {});

    const defaultServicePointId = _.get(resources, ['curUserServicePoint', 'records', 0, 'defaultServicePointId'], '-');
    const servicePointsIds = _.get(resources, ['curUserServicePoint', 'records', 0, 'servicePointsIds'], []);

    let selected = parseFloat(0);
    accounts.forEach(a => {
      selected += parseFloat(a.remaining);
    });
    parseFloat(selected).toFixed(2);
    const item = {
      id: this.item.id || '',
      instance: this.item.title || '',
      barcode: this.item.barcode || '',
      itemStatus: (this.item.status || {}).name || '',
      callNumber: this.item.callNumber || '',
      location: (this.item.effectiveLocation || {}).name || '',
      type: (this.item.materialType || {}).name || '',
    };

    const isPending = {
      owners: _.get(resources, ['owners', 'isPending'], false),
      feefines: _.get(resources, ['feefines', 'isPending'], false),
      servicePoints: _.get(resources, ['curUserServicePoint', 'isPending'], true)
    };

    const items = _.get(resources, ['items', 'records'], []);
    return (

        <ChargeForm
          onClickCancel={this.props.onCloseChargeFeeFine}
          onClickPay={this.onClickPay}
          defaultServicePointId={defaultServicePointId}
          servicePointsIds={servicePointsIds}
          onSubmit={(data) => {
            if (data.pay) {
              delete data.pay;
              this.type.remaining = data.amount;
              this.onClickPay(data);
            } else {
              delete data.pay;
              this.onClickCharge(data)
                .then(() => this.props.handleAddRecords())
                .then(() => this.props.onCloseChargeFeeFine());
            }
          }}
          user={this.props.user}
          ownerList={(shared) ? owners : list}
          owners={owners}
          isPending={isPending}
          ownerId={this.state.ownerId}
          feefines={feefines}
          item={item}
          onFindShared={this.onFindShared}
          onChangeOwner={this.onChangeOwner}
          onClickSelectItem={this.onClickSelectItem}
          stripes={this.props.stripes}
          {...this.props}
        />
        <ItemLookup
          resources={this.props.resources}
          items={items}
          open={(this.state.lookup && items.length > 1)}
          onChangeItem={this.onChangeItem}
          onClose={this.onCloseModal}
        />
        <PayModal
          open={this.state.pay}
          commentRequired={settings.paid}
          onClose={this.onClosePayModal}
          accounts={[this.type]}
          balance={this.type.amount}
          payments={payments}
          stripes={this.props.stripes}
          onSubmit={(values) => {
            this.onClickCharge(this.type).then(() => {
              this.type.remaining = parseFloat(this.type.amount - values.amount).toFixed(2);
              if (this.type.remaining === '0.00') {
                this.type.paymentStatus.name = 'Paid Fully';
                this.type.status.name = 'Closed';
              } else {
                this.type.paymentStatus.name = 'Paid Partially';
              }
              this.props.mutator.activeRecord.update({ id: this.type.id });
              return this.props.mutator.accounts.PUT(this.type);
            })
              .then(() => this.newAction({ paymentMethod: values.method }, this.type.id,
                this.type.paymentStatus.name, values.amount,
                values.comment, this.type.remaining,
                values.transaction, this.type.feeFineOwner))
              .then(() => {
                this.showCalloutMessage(this.type);
                this.payResolve();
              })
              .then(() => this.props.handleAddRecords())
              .then(() => setTimeout(this.props.onCloseChargeFeeFine, 2000));
          }}
        />
        <Callout ref={(ref) => { this.callout = ref; }} />

    );
  }
}

export default Charge;
<|endoftext|>


<commit_before>
import fetch from 'whatwg-fetch';

function noop(err) {
  return err;
}

const CONFIG = {
  lang: 'en-US',
  url: '',
  ext: 'lang.json',
  asyncLoadError: noop,
};

const I18N = {
  bundle: {},
  errors: {},
  async: {},
};

const TEMPLATE_I18N_REGEX = /{\s*?(\w+?)\s*?}/g;

function i18nCreateDelimiter(message) {
  let str = '!1@2#3';
  if (new RegExp(str).test(message)) {
    return str + str;
  }
  return str;
}

function setConfig(conf) {
  Object.keys(conf || {}).forEach((prop) => {
    CONFIG[prop] = conf[prop];
  });
}

function setError(bName, err) {
  I18N.errors[bName] = err;
}

function hasError(bName) {
  return !!I18N.errors[bName];
}

function getError(bName) {
  return I18N.errors[bName];
}

function templatize(bundle) {
  const templates = {};
  Object.keys(bundle).forEach((bKey) => {
    const bMessage = bundle[bKey];
    if (typeof bMessage === 'string') {
      const delimiter = i18nCreateDelimiter(bMessage);
      templates[bKey] = bMessage.replace(TEMPLATE_I18N_REGEX, (match) => {
        return `${delimiter}${match}${delimiter}`;
      })
      .split(delimiter);
    }
  });
  return templates;
}

function _parseLocaleKey(localeKey) {
  return (localeKey || '').split('.').splice(0, 2);
}

function getBundle(bName) {
  return I18N.bundle[bName];
}

function getMessage(localeKey, bKeyParam) {
  const [bName, bKey] = _parseLocaleKey(localeKey);
  return (getBundle(bName) || {})[bKey || bKeyParam];
}

function getMessages(langRefs) {
  const msgs = {};
  Object.keys(langRefs).forEach((ref) => {
    const value = langRefs[ref];
    if (typeof value === 'string') {
      // assumes that value is a locale key
      msgs[ref] = getMessage(value);
    } else {
      // assumes that value has nested locale keys
      msgs[ref] = getMessages(value);
    }
  });
  return msgs;
}

function _loadBundleSync(lang, bName, bMessages) {
  I18N.bundle[bName] = templatize(bMessages);
}

function loadBundlesSync(lang, bundles) {
  Object.keys(bundles).forEach((bName) => {
    _loadBundleSync(lang, bName, bundles[bName]);
  });
}

function dedup(bNames) {
  const obj = {};
  if (typeof bNames === 'string') {
    return [ bNames ];
  }
  (bNames || []).forEach((item) => {
    obj[item] = true;
  });
  return Object.keys(obj);
}

function _loadBundleAsync(localeKey) {
  // accepts bName or localeKey
  const [bName] = _parseLocaleKey(localeKey);
  const bundle = getBundle(bName);

  if (hasError(bName)) {
    return Promise.reject(new Error(getError(bName)));
  }

  // resolve bundle if exists in memory
  if (bundle) {
    return Promise.resolve(bundle);
  }

  // reject if URL is not set.
  if (!CONFIG.url) {
    const message = `Set the i18n URL path to asynchronously load ${ bName } bundle.`;
    setError(bName, message);
    return Promise.reject(new Error(message));
  }

  // resolve bundle promise if already fetching
  if (I18N.async[bName]) {
    return Promise.resolve(I18N.async[bName]);
  }

  // fetch bundle!
  const url = resolveAbsoluteURL(`${ CONFIG.url }/${ CONFIG.lang }/${ bName }.${ CONFIG.ext }`);
  I18N.async[bName] = fetch(url).then((resp) => {
    return resp.ok ? resp.json() : Promise.reject();
  }).then((bMessages) => {
    _loadBundleSync(CONFIG.lang, bName, bMessages || {});
    delete I18N.async[bName];
  }, function () {
    const message = `${bName} bundle failed to load.`;
    setError(bName, message);
    return (CONFIG.asyncLoadError || noop)(new Error(message), {
      bundle: bName,
      url,
    });
  });
  return I18N.async[bName];
}

function loadBundlesAsync(localeKeys) {
  const bNames = localeKeys.map((localeKey) => {
    const [bName] = _parseLocaleKey(localeKey);
    return bName;
  });
  return Promise.all(dedup(bNames).map((bName) => {
    return _loadBundleAsync(bName);
  }));
}

function _renderMessage(message, options) {
  const opts = options || {};
  return (Array.isArray(message) ? message : []).map((item, index) => {
    if (!item) {
      return;
    }
    const matches = TEMPLATE_I18N_REGEX.exec(item);
    return (

        { matches ? opts[matches[1]] : item }

    );
  });
}

function renderI18n(localeKey, options) {
  const message = getMessage(localeKey);
  return renderMessage(message, options);
}

function resolveAbsoluteURL(url) {
  const a = document.createElement('a');
  a.href = url.replace(/\/\//g, '/');
  return a.href;
}

export default {
  setConfig,
  getMessage,
  getMessages,
  _renderMessage,
  _loadBundleSync,
  loadBundlesSync,
  _loadBundleAsync,
  loadBundlesAsync,
  _parseLocaleKey,
  renderI18n,
}
<commit_msg>fix the method name typo<commit_after>
import fetch from 'whatwg-fetch';

function noop(err) {
  return err;
}

const CONFIG = {
  lang: 'en-US',
  url: '',
  ext: 'lang.json',
  asyncLoadError: noop,
};

const I18N = {
  bundle: {},
  errors: {},
  async: {},
};

const TEMPLATE_I18N_REGEX = /{\s*?(\w+?)\s*?}/g;

function i18nCreateDelimiter(message) {
  let str = '!1@2#3';
  if (new RegExp(str).test(message)) {
    return str + str;
  }
  return str;
}

function setConfig(conf) {
  Object.keys(conf || {}).forEach((prop) => {
    CONFIG[prop] = conf[prop];
  });
}

function setError(bName, err) {
  I18N.errors[bName] = err;
}

function hasError(bName) {
  return !!I18N.errors[bName];
}

function getError(bName) {
  return I18N.errors[bName];
}

function templatize(bundle) {
  const templates = {};
  Object.keys(bundle).forEach((bKey) => {
    const bMessage = bundle[bKey];
    if (typeof bMessage === 'string') {
      const delimiter = i18nCreateDelimiter(bMessage);
      templates[bKey] = bMessage.replace(TEMPLATE_I18N_REGEX, (match) => {
        return `${delimiter}${match}${delimiter}`;
      })
      .split(delimiter);
    }
  });
  return templates;
}

function _parseLocaleKey(localeKey) {
  return (localeKey || '').split('.').splice(0, 2);
}

function getBundle(bName) {
  return I18N.bundle[bName];
}

function getMessage(localeKey, bKeyParam) {
  const [bName, bKey] = _parseLocaleKey(localeKey);
  return (getBundle(bName) || {})[bKey || bKeyParam];
}

function getMessages(langRefs) {
  const msgs = {};
  Object.keys(langRefs).forEach((ref) => {
    const value = langRefs[ref];
    if (typeof value === 'string') {
      // assumes that value is a locale key
      msgs[ref] = getMessage(value);
    } else {
      // assumes that value has nested locale keys
      msgs[ref] = getMessages(value);
    }
  });
  return msgs;
}

function _loadBundleSync(lang, bName, bMessages) {
  I18N.bundle[bName] = templatize(bMessages);
}

function loadBundlesSync(lang, bundles) {
  Object.keys(bundles).forEach((bName) => {
    _loadBundleSync(lang, bName, bundles[bName]);
  });
}

function dedup(bNames) {
  const obj = {};
  if (typeof bNames === 'string') {
    return [ bNames ];
  }
  (bNames || []).forEach((item) => {
    obj[item] = true;
  });
  return Object.keys(obj);
}

function _loadBundleAsync(localeKey) {
  // accepts bName or localeKey
  const [bName] = _parseLocaleKey(localeKey);
  const bundle = getBundle(bName);

  if (hasError(bName)) {
    return Promise.reject(new Error(getError(bName)));
  }

  // resolve bundle if exists in memory
  if (bundle) {
    return Promise.resolve(bundle);
  }

  // reject if URL is not set.
  if (!CONFIG.url) {
    const message = `Set the i18n URL path to asynchronously load ${ bName } bundle.`;
    setError(bName, message);
    return Promise.reject(new Error(message));
  }

  // resolve bundle promise if already fetching
  if (I18N.async[bName]) {
    return Promise.resolve(I18N.async[bName]);
  }

  // fetch bundle!
  const url = resolveAbsoluteURL(`${ CONFIG.url }/${ CONFIG.lang }/${ bName }.${ CONFIG.ext }`);
  I18N.async[bName] = fetch(url).then((resp) => {
    return resp.ok ? resp.json() : Promise.reject();
  }).then((bMessages) => {
    _loadBundleSync(CONFIG.lang, bName, bMessages || {});
    delete I18N.async[bName];
  }, function () {
    const message = `${bName} bundle failed to load.`;
    setError(bName, message);
    return (CONFIG.asyncLoadError || noop)(new Error(message), {
      bundle: bName,
      url,
    });
  });
  return I18N.async[bName];
}

function loadBundlesAsync(localeKeys) {
  const bNames = localeKeys.map((localeKey) => {
    const [bName] = _parseLocaleKey(localeKey);
    return bName;
  });
  return Promise.all(dedup(bNames).map((bName) => {
    return _loadBundleAsync(bName);
  }));
}

function _renderMessage(message, options) {
  const opts = options || {};
  return (Array.isArray(message) ? message : []).map((item, index) => {
    if (!item) {
      return;
    }
    const matches = TEMPLATE_I18N_REGEX.exec(item);
    return (

        { matches ? opts[matches[1]] : item }

    );
  });
}

function renderI18n(localeKey, options) {
  const message = getMessage(localeKey);
  return _renderMessage(message, options);
}

function resolveAbsoluteURL(url) {
  const a = document.createElement('a');
  a.href = url.replace(/\/\//g, '/');
  return a.href;
}

export default {
  setConfig,
  getMessage,
  getMessages,
  _renderMessage,
  _loadBundleSync,
  loadBundlesSync,
  _loadBundleAsync,
  loadBundlesAsync,
  _parseLocaleKey,
  renderI18n,
}
<|endoftext|>