<commit_before>(function($) {
var firstPosition = true;
var accurancyStyle = {
    fillColor: '#000',
    fillOpacity: 0.1,
    strokeWidth: 1,
    strokeColor: '#000'
};
$.widget("mapbender.mbGpsPosition", {
    options: {
        follow: false,
        average: 1,
        zoomToAccuracy: false,
        centerOnFirstPosition: true,
        zoomOnFirstPosition: true
    },

    map: null,
    interval : null,
    stack: [],

    _create: function() {
        var self = this;
        var me = $(this.element);

        if(!Mapbender.checkTarget("mbGpsPosition", this.options.target)){
                return;
        }
        Mapbender.elementRegistry.onElementReady(this.options.target, $.proxy(self._setup, self));

        if(!this.options.average) {
            this.options.average = 1;
        }

        me.click(function() {
            me.parent().addClass("toolBarItemActive");
            self._timerGeolocation.call(self);
        });
    },

    _setup: function() {
        this.map = $('#' + this.options.target).data('mapbenderMbMap');
        if (this.options.autoStart === true){
            this._getGeolocation();
            this._activateTimer();
        }
    },

    _timerGeolocation: function() {
        if (this.interval != null){
            this._deactivateTimer();
        } else {
            this._getGeolocation();
            this._activateTimer();
        }
    },

    _getGeolocation: function() {
        var self = this;
        var olmap = this.map.map.olMap;
        if (navigator.geolocation)
        {
            navigator.geolocation.getCurrentPosition(function success(position) {
                var proj = new OpenLayers.Projection("EPSG:4326");
                var newProj = olmap.getProjectionObject();
                var p = new OpenLayers.LonLat(position.coords.longitude,position.coords.latitude);
                p.transform(proj, newProj);

                // Averaging: Building a queue...
                self.stack.push(p);
                if(self.stack.length > self.options.average) {
                    self.stack.splice(0, 1);
                }

                // ...and reducing it.
                p = _.reduce(self.stack, function(memo, p) {
                    memo.lon += p.lon / self.stack.length;
                    memo.lat += p.lat / self.stack.length;
                    return memo;
                }, new OpenLayers.LonLat(0, 0));

                self._createMarker(p, position.coords.accuracy);
                self._centerMap(p);
                self._zoomMap(p, position.coords.accuracy);

                if(firstPosition) firstPosition = false;

            }, function error(msg) {}, { enableHighAccuracy: true, maximumAge: 0 });
        } else {
            Mapbender.error(Mapbender.trans("mb.core.gpsposition.error.notsupported"));
        }
    },

    _createMarker: function (position, accuracy) {
        var olmap = this.map.map.olMap;
        var markers;
        var candidates = olmap.getLayersByName('Markers');
        if (candidates.length > 0){
            markers = candidates[0];
            olmap.removeLayer(markers);
            markers.destroy();
        }
        markers = new OpenLayers.Layer.Markers( "Markers" );
        olmap.addLayer(markers);
        var size = new OpenLayers.Size(20,20);
        var icon = new OpenLayers.Icon(Mapbender.configuration.application.urls.asset + 'bundles/mapbendercore/image/marker_fett.gif', size);
        markers.addMarker(new OpenLayers.Marker(position,icon));

        // Accurancy
        var circle = new OpenLayers.Feature.Vector(
            OpenLayers.Geometry.Polygon.createRegularPolygon(
                position,
                accuracy/2,
                40,
                0
            ),
            {},
            accurancyStyle
        );

        return;
        markers.addFeatures([
            new OpenLayers.Feature.Vector(

            )
        ]);
        var size = new OpenLayers.Size(20,20);
        var icon = new OpenLayers.Icon(Mapbender.configuration.application.urls.asset + 'bundles/mapbendercore/image/marker_fett.gif', size);
        markers.addMarker(new OpenLayers.Marker(position,icon))
    },

    _centerMap: function (point){
        var olmap = this.map.map.olMap;
        var extent = olmap.getExtent();
        if (extent.containsLonLat(point) === false || true === this.options.follow) {
            olmap.panTo(point);
        } else if(firstPosition && this.options.centerOnFirstPosition) {
            olmap.panTo(point);
        }
    },

    _zoomMap: function(point, accuracy){
        if(!accuracy) return; // no accurancy
        if(!this.options.zoomToAccuracy && !(this.options.zoomOnFirstPosition && firstPosition)) return;

        var olmap = this.map.map.olMap;

        var metersProj = new OpenLayers.Projection("EPSG:900913");
        var currentProj = olmap.getProjectionObject();
        var pointInMeters = point.transform(currentProj, metersProj);
        var min = new OpenLayers.LonLat(pointInMeters.lon-(accuracy/2),pointInMeters.lat-(accuracy/2)).transform(metersProj, currentProj);
        var max = new OpenLayers.LonLat(pointInMeters.lon+(accuracy/2),pointInMeters.lat+(accuracy/2)).transform(metersProj, currentProj);
        olmap.zoomToExtent(new OpenLayers.Bounds(min.lon, min.lat, max.lon, max.lat));
    },

    _activateTimer: function (){
        var self = this;
        var interval = this.options.refreshinterval;
        this.interval = setInterval(function() { self._getGeolocation.call(self); },interval);
    },

    _deactivateTimer: function (){
        $(this.element).parent().removeClass("toolBarItemActive");
        this.interval = clearInterval(this.interval);

        var olmap = this.map.map.olMap;
        var markers;
        var candidates = olmap.getLayersByName('Markers');
        if (candidates.length > 0){
            markers = candidates[0];
            olmap.removeLayer(markers);
            markers.destroy();
        }
        firstPosition = true;
    },
    /**
     *
     */
    ready: function(callback) {
        if(this.readyState === true) {
            callback();
        } else {
            this.readyCallbacks.push(callback);
        }
    },
    /**
     *
     */
    _ready: function() {
        for(callback in this.readyCallbacks) {
            callback();
            delete(this.readyCallbacks[callback]);
        }
        this.readyState = true;
    }
});

})(jQuery);
<commit_msg>try to draw a circle<commit_after>(function($) {
var firstPosition = true;
var accurancyStyle = {
    fillColor: '#000',
    fillOpacity: 1,
    strokeWidth: 1,
    strokeColor: '#000'
};
$.widget("mapbender.mbGpsPosition", {
    options: {
        follow: false,
        average: 1,
        zoomToAccuracy: false,
        centerOnFirstPosition: true,
        zoomOnFirstPosition: true
    },

    map: null,
    interval : null,
    stack: [],

    _create: function() {
        var self = this;
        var me = $(this.element);

        if(!Mapbender.checkTarget("mbGpsPosition", this.options.target)){
                return;
        }
        Mapbender.elementRegistry.onElementReady(this.options.target, $.proxy(self._setup, self));

        if(!this.options.average) {
            this.options.average = 1;
        }

        me.click(function() {
            me.parent().addClass("toolBarItemActive");
            self._timerGeolocation.call(self);
        });
    },

    _setup: function() {
        this.map = $('#' + this.options.target).data('mapbenderMbMap');
        if (this.options.autoStart === true){
            this._getGeolocation();
            this._activateTimer();
        }
    },

    _timerGeolocation: function() {
        if (this.interval != null){
            this._deactivateTimer();
        } else {
            this._getGeolocation();
            this._activateTimer();
        }
    },

    _getGeolocation: function() {
        var self = this;
        var olmap = this.map.map.olMap;
        if (navigator.geolocation)
        {
            navigator.geolocation.getCurrentPosition(function success(position) {
                var proj = new OpenLayers.Projection("EPSG:4326");
                var newProj = olmap.getProjectionObject();
                var p = new OpenLayers.LonLat(position.coords.longitude,position.coords.latitude);
                p.transform(proj, newProj);

                // Averaging: Building a queue...
                self.stack.push(p);
                if(self.stack.length > self.options.average) {
                    self.stack.splice(0, 1);
                }

                // ...and reducing it.
                p = _.reduce(self.stack, function(memo, p) {
                    memo.lon += p.lon / self.stack.length;
                    memo.lat += p.lat / self.stack.length;
                    return memo;
                }, new OpenLayers.LonLat(0, 0));

                self._createMarker(p, position.coords.accuracy);
                self._centerMap(p);
                self._zoomMap(p, position.coords.accuracy);

                if(firstPosition) firstPosition = false;

            }, function error(msg) {}, { enableHighAccuracy: true, maximumAge: 0 });
        } else {
            Mapbender.error(Mapbender.trans("mb.core.gpsposition.error.notsupported"));
        }
    },

    _createMarker: function (position, accuracy) {
        var olmap = this.map.map.olMap;
        var markers;
        var candidates = olmap.getLayersByName('Markers');
        if (candidates.length > 0){
            markers = candidates[0];
            olmap.removeLayer(markers);
            markers.destroy();
        }
        markers = new OpenLayers.Layer.Markers( "Markers" );
        olmap.addLayer(markers);
        var size = new OpenLayers.Size(20,20);
        var icon = new OpenLayers.Icon(Mapbender.configuration.application.urls.asset + 'bundles/mapbendercore/image/marker_fett.gif', size);
        markers.addMarker(new OpenLayers.Marker(position,icon));

        // Accurancy
        if(!accuracy) return;
        var candidates = olmap.getLayersByName('Accuracy');
        if (candidates.length > 0){
            olmap.removeLayer(candidates[0]);
            candidates[0].destroy();
        }
        var vector = new OpenLayers.Layer.Vector( "Accuracy" );
        olmap.addLayer(vector);
        console.warn(window.g = olmap);
        var circle = new OpenLayers.Feature.Vector(
            OpenLayers.Geometry.Polygon.createRegularPolygon(
                olmap.getCenter(),//position,
                100,//accuracy/2,
                40,
                0
            ),
            {},
            accurancyStyle
        );
        console.log(circle);
console.log("Radius in m:", accuracy/2);
        vector.addFeatures([circle]);
        vector.drawFeature(circle);
console.log("draw", circle);
        return;
    },

    _centerMap: function (point){
        var olmap = this.map.map.olMap;
        var extent = olmap.getExtent();
        if (extent.containsLonLat(point) === false || true === this.options.follow) {
            olmap.panTo(point);
        } else if(firstPosition && this.options.centerOnFirstPosition) {
            olmap.panTo(point);
        }
    },

    _zoomMap: function(point, accuracy){
        if(!accuracy) return; // no accurancy
        if(!this.options.zoomToAccuracy && !(this.options.zoomOnFirstPosition && firstPosition)) return;

        var olmap = this.map.map.olMap;

        var metersProj = new OpenLayers.Projection("EPSG:900913");
        var currentProj = olmap.getProjectionObject();
        var pointInMeters = point.transform(currentProj, metersProj);
        var min = new OpenLayers.LonLat(pointInMeters.lon-(accuracy/2),pointInMeters.lat-(accuracy/2)).transform(metersProj, currentProj);
        var max = new OpenLayers.LonLat(pointInMeters.lon+(accuracy/2),pointInMeters.lat+(accuracy/2)).transform(metersProj, currentProj);
        olmap.zoomToExtent(new OpenLayers.Bounds(min.lon, min.lat, max.lon, max.lat));
    },

    _activateTimer: function (){
        var self = this;
        var interval = this.options.refreshinterval;
        this.interval = setInterval(function() { self._getGeolocation.call(self); },interval);
    },

    _deactivateTimer: function (){
        $(this.element).parent().removeClass("toolBarItemActive");
        this.interval = clearInterval(this.interval);

        var olmap = this.map.map.olMap;
        var markers;
        var candidates = olmap.getLayersByName('Markers');
        if (candidates.length > 0){
            markers = candidates[0];
            olmap.removeLayer(markers);
            markers.destroy();
        }
        firstPosition = true;
    },
    /**
     *
     */
    ready: function(callback) {
        if(this.readyState === true) {
            callback();
        } else {
            this.readyCallbacks.push(callback);
        }
    },
    /**
     *
     */
    _ready: function() {
        for(callback in this.readyCallbacks) {
            callback();
            delete(this.readyCallbacks[callback]);
        }
        this.readyState = true;
    }
});

})(jQuery);
<|endoftext|>


<commit_before>/**
 * XadillaX created at 2016-04-01 15:13:51 With ♥
 *
 * Copyright (c) 2016 Souche.com, all rights
 * reserved.
 */
"use strict";

var Errors = require("ero");

var definition = {
    Normal: {
        code: 10000,
        status: 500,
        logLevel: "error",
        business: "Server had came across a normal error."
    },

    QueryValidation: {
        code: 9001,
        status: 400,
        logLevel: "warn",
        business: "Query string validation failed."
    },

    BodyValidation: {
        code: 9002,
        status: 400,
        logLevel: "warn",
        business: "Body validation failed."
    },

    PathValidation: {
        code: 9003,
        status: 400,
        logLevel: "warn",
        business: "Router path validation failed."
    },

    NotFound: {
        code: 10001,
        status: 404,
        logLevel: "warn",
        business: "Resource you requested is not existed."
    },

    Forbidden: {
        code: 10002,
        status: 403,
        logLevel: "warn",
        business: "You have no permission to access for this resource."
    },

    ThirdParty: {
        code: 20000,
        status: 502,
        logLevel: "error",
        business: "Remote API server error."
    }
};

module.exports = Errors.init({
    template: require("./template"),
    definitions: definition
});
<commit_msg>refactor predefinition error<commit_after>/**
 * XadillaX created at 2016-04-01 15:13:51 With ♥
 *
 * Copyright (c) 2016 Souche.com, all rights
 * reserved.
 */
"use strict";

module.exports = {
    Normal: {
        code: 10000,
        status: 500,
        logLevel: "error",
        business: "Server had came across a normal error."
    },

    QueryValidation: {
        code: 9001,
        status: 400,
        logLevel: "warn",
        business: "Query string validation failed."
    },

    BodyValidation: {
        code: 9002,
        status: 400,
        logLevel: "warn",
        business: "Body validation failed."
    },

    PathValidation: {
        code: 9003,
        status: 400,
        logLevel: "warn",
        business: "Router path validation failed."
    },

    NotFound: {
        code: 10001,
        status: 404,
        logLevel: "warn",
        business: "Resource you requested is not existed."
    },

    Forbidden: {
        code: 10002,
        status: 403,
        logLevel: "warn",
        business: "You have no permission to access for this resource."
    },

    ThirdParty: {
        code: 20000,
        status: 502,
        logLevel: "error",
        business: "Remote API server error."
    }
};
<|endoftext|>


<commit_before>
/*****************************************************************************/
/* TravelRequisition2Print: Event Handlers */
/*****************************************************************************/
import _ from 'underscore';

Template.registerHelper('formatDate', function(date) {
    return moment(date).format('DD-MM-YYYY');
});

/*****************************************************************************/
/* TravelRequisition2Print: Helpers */
/*****************************************************************************/
Template.TravelRequisition2Print.helpers({
    travelTypeChecked(val){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();
        if(currentTravelRequest && val){
            return currentTravelRequest.type === val ? checked="checked" : '';
        }
    },
    isReturnTrip(){
        return Template.instance().currentTravelRequest.get().type === "Return";
    },
    isCarModeOfTransport(index){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();

        if(currentTravelRequest && index){
            return currentTravelRequest.trips[parseInt(index) - 1].transportationMode === "CAR"? '':'none';
        }
    },
    isAirModeOfTransport(index){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();

        if(currentTravelRequest && index){
            return currentTravelRequest.trips[parseInt(index) - 1].transportationMode === "AIRLINE"? '':'none';
        }
    },
    'getEmployeeFullName': function(employeeId) {
        let employee = Meteor.users.findOne({_id: employeeId});
        if(employee)
        return employee.profile.fullName;
        else
        return ""
    },
    'getBudgetHolderNames': function(budgetCodeId) {
        const budget = Budgets.findOne({_id: budgetCodeId})

        if(budget) {
            let employeeId = budget.employeeId
            let employee = Meteor.users.findOne({_id: employeeId});
            if(employee)
            return employee.profile.fullName;
            else
            return "..."
        }
    },
    'getEmployeeEmail': function(employeeId) {
        let employee = Meteor.users.findOne({_id: employeeId});
        if(employee)
        return employee.emails[0].address;
        else
        return "..."
    },
    'getEmployeePhoneNumber': function(employeeId) {
        let employee = Meteor.users.findOne({_id: employeeId});
        if(employee)
        return employee.employeeProfile.phone;
        else
        return "..."
    },
    // 'getEmployeeNameById': function(employeeId){
    //         return (Meteor.users.findOne({_id: employeeId})).profile.fullName;
    // },

    isBreakfastIncluded(index){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();
        if(currentTravelRequest && index){
            return currentTravelRequest.trips[parseInt(index) - 1].isBreakfastIncluded? checked="checked" : '';
        }
    },
    provideAirportPickup(index){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();
        if(currentTravelRequest && index){
            return currentTravelRequest.trips[parseInt(index) - 1].provideAirportPickup? checked="checked" : '';
        }
    },
    provideGroundTransport(index){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();
        if(currentTravelRequest && index){
            return currentTravelRequest.trips[parseInt(index) - 1].provideGroundTransport? checked="checked" : '';
        }
    },
    isLunchIncluded(index){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();
        if(currentTravelRequest && index){
            return currentTravelRequest.trips[parseInt(index) - 1].isLunchIncluded? checked="checked" : '';
        }
    },
    isDinnerIncluded(index){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();
        if(currentTravelRequest && index){
            return currentTravelRequest.trips[parseInt(index) - 1].isDinnerIncluded? checked="checked" : '';
        }
    },
    isIncidentalsIncluded(index){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();
        if(currentTravelRequest && index){
            return currentTravelRequest.trips[parseInt(index) - 1].isIncidentalsIncluded? checked="checked" : '';
        }
    },
    isLastLeg(index){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();
        if(currentTravelRequest && index && currentTravelRequest.type ==="Multiple"){
            return parseInt(index) >= currentTravelRequest.trips.length;
        }
    },
    'getTravelcityName': function(travelcityId) {
        const travelcity = Travelcities.findOne({_id: travelcityId})

        if(travelcity) {
            return travelcity.name
        }
    },
    'getHotelName': function(hotelId) {
        const hotel = Hotels.findOne({_id: hotelId})

        if(hotel) {
            return hotel.name
        }
    },
    'getAirlineName': function(airlineId) {
        const airline = Airlines.findOne({_id: airlineId})

        if(airline) {
            return airline.name
        }
    },
    cashAdvanceNotRequiredChecked(){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();
        if(currentTravelRequest){
            return currentTravelRequest.cashAdvanceNotRequired? checked="checked" : '';
        }
    },
    'getBudgetName': function(budgetCodeId) {
        const budget = Budgets.findOne({_id: budgetCodeId})

        if(budget) {
            return budget.name
        }
    },
    'currentTravelRequest': function() {
        return Template.instance().currentTravelRequest.get()
    },
    getCreatedByFullName: (requisition) => {
        const userId = requisition.createdBy

        const user = Meteor.users.findOne(userId)
        return user ? user.profile.fullName : '...'
    },
    'isInEditMode': function() {
        return Template.instance().isInEditMode.get()
    },
    'isInApproveMode': function() {
        return Template.instance().isInApproveMode.get()
    },
    'isInApproverEditMode': function() {
        return Template.instance().isInApproverEditMode.get()
    },
    'isInTreatMode': function() {
        return Template.instance().isInTreatMode.get()
    },
    'isInRetireMode': function() {
        return Template.instance().isInTreatMode.get()
    },
    'getUnitName': function(unitId) {
        if(unitId) {
            console.log(`unit id: `, unitId)
            return EntityObjects.findOne({_id: unitId}).name
        }
    },

    'getHumanReadableApprovalState': function(boolean) {
        return boolean ? "Approved" : "Rejected"
    },
    'or': (a, b) => {
        return a || b
    },
    'isEqual': (a, b) => {
        return a === b;
    },

    'totalTripCostNGN': function() {
        return Template.instance().totalTripCostNGN.get()
    },
});

/*****************************************************************************/
/* TravelRequisition2Print: Lifecycle Hooks */
/*****************************************************************************/
Template.TravelRequisition2Print.onCreated(function () {
    console.log(Router.current());

    let self = this;
    let businessUnitId = Router.current().params._id;
    console.log("businessUnitId from print.js is:")
    console.log(businessUnitId)
    self.subscribe("allEmployees", Router.current().params._id);
    self.subscribe("travelcities",  Router.current().params._id);
    self.subscribe("hotels",  Router.current().params._id);
    self.subscribe("airlines",  Router.current().params._id);
    self.subscribe("budgets",  Router.current().params._id);

    let invokeReason = {}
    invokeReason.requisitionId = Router.current().params.query.requisitionId
    invokeReason.reason = 'edit'
    invokeReason.approverId = null

    self.currentTravelRequest = new ReactiveVar()
    self.isInEditMode = new ReactiveVar()
    self.isInViewMode = new ReactiveVar()
    self.isInApproveMode = new ReactiveVar()
    self.isInApproverEditMode = new ReactiveVar()
    self.isInTreatMode = new ReactiveVar()
    self.isInRetireMode = new ReactiveVar()

    self.businessUnitCustomConfig = new ReactiveVar()

    // self.totalTripCost = new ReactiveVar(0)
    self.amountNonPaybelToEmp = new ReactiveVar(0)
    self.amoutPayableToEmp = new ReactiveVar(0)
    self.totalTripCost = new ReactiveVar(0)

    if(invokeReason.reason === 'edit') {
        self.isInEditMode.set(true)
    }
    if(invokeReason.reason === 'approve') {
        self.isInApproveMode.set(true)
    }
    if(invokeReason.reason === 'treat') {
        self.isInTreatMode.set(true)
    }
    if(invokeReason.reason === 'retire') {
        self.isInRetireMode.set(true)
    }

    self.businessUnitLogoUrl = new ReactiveVar()

    self.autorun(function() {

        Meteor.call('BusinessUnitCustomConfig/getConfig', businessUnitId, function(err, customConfig) {
            if(!err) {
                self.businessUnitCustomConfig.set(customConfig)
            }
        })

        let businessUnitSubscription = self.subscribe("BusinessUnit", businessUnitId)
        let travelRequest2Sub = self.subscribe('TravelRequest2', invokeReason.requisitionId)

        if(travelRequest2Sub.ready()) {

            let travelRequestDetails = TravelRequisition2s.findOne({_id: invokeReason.requisitionId})
            self.currentTravelRequest.set(travelRequestDetails)

        }

        if(businessUnitSubscription.ready()) {
            let businessUnit = BusinessUnits.findOne({_id: businessUnitId})
            self.businessUnitLogoUrl.set(businessUnit.logoUrl)
        }
    })

});

Template.TravelRequisition2Print.onRendered(function () {
    $('select.dropdown').dropdown();
    let self = this

    let currentTravelRequest = self.currentTravelRequest.get()
    if(currentTravelRequest) {
        if(currentTravelRequest.status !== 'Draft' && currentTravelRequest.status !== 'Pending') {
            if(self.isInEditMode.get()) {
                Modal.hide();
                swal('Error', "Sorry, you can't edit this travel request. ", 'error')
            }
        } else if(currentTravelRequest.status === 'Pending') {
            self.isInViewMode.set(true)
        } else if(currentTravelRequest.status === 'Approve') {
            if(self.isInEditMode.get()) {
                swal('Error', "Sorry, you can't edit this travel request. It has been approved", 'error')
            }
        }
    }
});

Template.TravelRequisition2Print.onDestroyed(function () {
});
<commit_msg>changing businessunit logourl<commit_after>
/*****************************************************************************/
/* TravelRequisition2Print: Event Handlers */
/*****************************************************************************/
import _ from 'underscore';

Template.registerHelper('formatDate', function(date) {
    return moment(date).format('DD-MM-YYYY');
});

/*****************************************************************************/
/* TravelRequisition2Print: Helpers */
/*****************************************************************************/
Template.TravelRequisition2Print.helpers({
    travelTypeChecked(val){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();
        if(currentTravelRequest && val){
            return currentTravelRequest.type === val ? checked="checked" : '';
        }
    },
    isReturnTrip(){
        return Template.instance().currentTravelRequest.get().type === "Return";
    },
    isCarModeOfTransport(index){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();

        if(currentTravelRequest && index){
            return currentTravelRequest.trips[parseInt(index) - 1].transportationMode === "CAR"? '':'none';
        }
    },
    isAirModeOfTransport(index){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();

        if(currentTravelRequest && index){
            return currentTravelRequest.trips[parseInt(index) - 1].transportationMode === "AIRLINE"? '':'none';
        }
    },
    'getEmployeeFullName': function(employeeId) {
        let employee = Meteor.users.findOne({_id: employeeId});
        if(employee)
        return employee.profile.fullName;
        else
        return ""
    },
    'getBudgetHolderNames': function(budgetCodeId) {
        const budget = Budgets.findOne({_id: budgetCodeId})

        if(budget) {
            let employeeId = budget.employeeId
            let employee = Meteor.users.findOne({_id: employeeId});
            if(employee)
            return employee.profile.fullName;
            else
            return "..."
        }
    },
    'getEmployeeEmail': function(employeeId) {
        let employee = Meteor.users.findOne({_id: employeeId});
        if(employee)
        return employee.emails[0].address;
        else
        return "..."
    },
    'getEmployeePhoneNumber': function(employeeId) {
        let employee = Meteor.users.findOne({_id: employeeId});
        if(employee)
        return employee.employeeProfile.phone;
        else
        return "..."
    },
    // 'getEmployeeNameById': function(employeeId){
    //         return (Meteor.users.findOne({_id: employeeId})).profile.fullName;
    // },

    isBreakfastIncluded(index){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();
        if(currentTravelRequest && index){
            return currentTravelRequest.trips[parseInt(index) - 1].isBreakfastIncluded? checked="checked" : '';
        }
    },
    provideAirportPickup(index){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();
        if(currentTravelRequest && index){
            return currentTravelRequest.trips[parseInt(index) - 1].provideAirportPickup? checked="checked" : '';
        }
    },
    provideGroundTransport(index){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();
        if(currentTravelRequest && index){
            return currentTravelRequest.trips[parseInt(index) - 1].provideGroundTransport? checked="checked" : '';
        }
    },
    isLunchIncluded(index){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();
        if(currentTravelRequest && index){
            return currentTravelRequest.trips[parseInt(index) - 1].isLunchIncluded? checked="checked" : '';
        }
    },
    isDinnerIncluded(index){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();
        if(currentTravelRequest && index){
            return currentTravelRequest.trips[parseInt(index) - 1].isDinnerIncluded? checked="checked" : '';
        }
    },
    isIncidentalsIncluded(index){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();
        if(currentTravelRequest && index){
            return currentTravelRequest.trips[parseInt(index) - 1].isIncidentalsIncluded? checked="checked" : '';
        }
    },
    isLastLeg(index){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();
        if(currentTravelRequest && index && currentTravelRequest.type ==="Multiple"){
            return parseInt(index) >= currentTravelRequest.trips.length;
        }
    },
    'getTravelcityName': function(travelcityId) {
        const travelcity = Travelcities.findOne({_id: travelcityId})

        if(travelcity) {
            return travelcity.name
        }
    },
    'getHotelName': function(hotelId) {
        const hotel = Hotels.findOne({_id: hotelId})

        if(hotel) {
            return hotel.name
        }
    },
    'getAirlineName': function(airlineId) {
        const airline = Airlines.findOne({_id: airlineId})

        if(airline) {
            return airline.name
        }
    },
    cashAdvanceNotRequiredChecked(){
        const currentTravelRequest = Template.instance().currentTravelRequest.get();
        if(currentTravelRequest){
            return currentTravelRequest.cashAdvanceNotRequired? checked="checked" : '';
        }
    },
    'getBudgetName': function(budgetCodeId) {
        const budget = Budgets.findOne({_id: budgetCodeId})

        if(budget) {
            return budget.name
        }
    },
    'currentTravelRequest': function() {
        return Template.instance().currentTravelRequest.get()
    },
    getCreatedByFullName: (requisition) => {
        const userId = requisition.createdBy

        const user = Meteor.users.findOne(userId)
        return user ? user.profile.fullName : '...'
    },
    'isInEditMode': function() {
        return Template.instance().isInEditMode.get()
    },
    'isInApproveMode': function() {
        return Template.instance().isInApproveMode.get()
    },
    'isInApproverEditMode': function() {
        return Template.instance().isInApproverEditMode.get()
    },
    'isInTreatMode': function() {
        return Template.instance().isInTreatMode.get()
    },
    'isInRetireMode': function() {
        return Template.instance().isInTreatMode.get()
    },
    'getUnitName': function(unitId) {
        if(unitId) {
            console.log(`unit id: `, unitId)
            return EntityObjects.findOne({_id: unitId}).name
        }
    },

    'getHumanReadableApprovalState': function(boolean) {
        return boolean ? "Approved" : "Rejected"
    },
    'or': (a, b) => {
        return a || b
    },
    'isEqual': (a, b) => {
        return a === b;
    },

    'totalTripCostNGN': function() {
        return Template.instance().totalTripCostNGN.get()
    },
});

/*****************************************************************************/
/* TravelRequisition2Print: Lifecycle Hooks */
/*****************************************************************************/
Template.TravelRequisition2Print.onCreated(function () {
    console.log(Router.current());

    let self = this;
    let businessUnitId = Router.current().params._id;
    console.log("businessUnitId from print.js is:")
    console.log(businessUnitId)
    self.subscribe("allEmployees", Router.current().params._id);
    self.subscribe("travelcities",  Router.current().params._id);
    self.subscribe("hotels",  Router.current().params._id);
    self.subscribe("airlines",  Router.current().params._id);
    self.subscribe("budgets",  Router.current().params._id);

    let invokeReason = {}
    invokeReason.requisitionId = Router.current().params.query.requisitionId
    invokeReason.reason = 'edit'
    invokeReason.approverId = null

    self.currentTravelRequest = new ReactiveVar()
    self.isInEditMode = new ReactiveVar()
    self.isInViewMode = new ReactiveVar()
    self.isInApproveMode = new ReactiveVar()
    self.isInApproverEditMode = new ReactiveVar()
    self.isInTreatMode = new ReactiveVar()
    self.isInRetireMode = new ReactiveVar()

    self.businessUnitCustomConfig = new ReactiveVar()

    // self.totalTripCost = new ReactiveVar(0)
    self.amountNonPaybelToEmp = new ReactiveVar(0)
    self.amoutPayableToEmp = new ReactiveVar(0)
    self.totalTripCost = new ReactiveVar(0)

    if(invokeReason.reason === 'edit') {
        self.isInEditMode.set(true)
    }
    if(invokeReason.reason === 'approve') {
        self.isInApproveMode.set(true)
    }
    if(invokeReason.reason === 'treat') {
        self.isInTreatMode.set(true)
    }
    if(invokeReason.reason === 'retire') {
        self.isInRetireMode.set(true)
    }

    self.businessUnitLogoUrl = new ReactiveVar()

    self.autorun(function() {

        Meteor.call('BusinessUnitCustomConfig/getConfig', businessUnitId, function(err, customConfig) {
            if(!err) {
                self.businessUnitCustomConfig.set(customConfig)
            }
        })

        let businessUnitSubscription = self.subscribe("BusinessUnit", businessUnitId)
        let travelRequest2Sub = self.subscribe('TravelRequest2', invokeReason.requisitionId)

        if(travelRequest2Sub.ready()) {

            let travelRequestDetails = TravelRequisition2s.findOne({_id: invokeReason.requisitionId})
            self.currentTravelRequest.set(travelRequestDetails)

        }

        if(businessUnitSubscription.ready()) {
            let businessUnit = BusinessUnits.findOne({_id: businessUnitId})
            console.log("businessUnit is")
            console.log(businessUnit)
            self.businessUnitLogoUrl.set(businessUnit.logoUrl)
        }
    })

});

Template.TravelRequisition2Print.onRendered(function () {
    $('select.dropdown').dropdown();
    let self = this

    let currentTravelRequest = self.currentTravelRequest.get()
    if(currentTravelRequest) {
        if(currentTravelRequest.status !== 'Draft' && currentTravelRequest.status !== 'Pending') {
            if(self.isInEditMode.get()) {
                Modal.hide();
                swal('Error', "Sorry, you can't edit this travel request. ", 'error')
            }
        } else if(currentTravelRequest.status === 'Pending') {
            self.isInViewMode.set(true)
        } else if(currentTravelRequest.status === 'Approve') {
            if(self.isInEditMode.get()) {
                swal('Error', "Sorry, you can't edit this travel request. It has been approved", 'error')
            }
        }
    }
});

Template.TravelRequisition2Print.onDestroyed(function () {
});
<|endoftext|>


<commit_before>"use strict";

app.controller("TituladoSearchController", ['$scope', '$http', 'ix3Configuration','dialog', function ($scope, $http, ix3Configuration,dialog) {
        $scope.businessMessages = [];

        $scope.fail = {};
        $scope.apiUrl = ix3Configuration.server.api;
        $scope.mostrarCodigosMunicipio = function () {
            dialog.create('mostrarCodigosMunicipio');
        };
        $scope.failImportJson = function (data) {
            if (data && data.jqXHR && data.jqXHR.responseText)
                $scope.businessMessages = JSON.parse(data.jqXHR.responseText);
        };
        $scope.updateList = function () {
            alert("El listado de Titulados se importó correctamente");
            $scope.search();
        };

        $scope.anyo=null;
        $scope.anyos=[];
        var currentYear=(new Date()).getFullYear();
        for(var anyo=currentYear;anyo>=1980;anyo--) {
            $scope.anyos.push(anyo);
        }

        if ($scope.user && $scope.user.centro) {
            $scope.centro=$scope.user.centro;
            getEstadisticasByCentro($scope,$scope.user.centro,$scope.anyo,$scope.anyo);
        }

        function getEstadisticasByCentro($scope,centro,anyoInicio,anyoFin) {
            $http({
                method: "GET",
                url: ix3Configuration.server.api + "/Estadisticas/centro/" + centro.idCentro + "?expand=titulosFPPorFamilia.tituladosPorCiclo&anyoInicio=" + (anyoInicio==null?'':anyoInicio) +"&anyoFin=" + (anyoFin==null?'':anyoFin)
            }).then(function (estadisticas) {
                $scope.centro.estadisticas = estadisticas.data;
            });
        }

        $scope.buttonSearch=function() {
            getEstadisticasByCentro($scope,$scope.user.centro,$scope.anyo,$scope.anyo);
        }

    }]);
<commit_msg>fix(#128):No avisa si falla al importar el JSON<commit_after>"use strict";

app.controller("TituladoSearchController", ['$scope', '$http', 'ix3Configuration','dialog', function ($scope, $http, ix3Configuration,dialog) {
        $scope.businessMessages = [];

        $scope.fail = {};
        $scope.apiUrl = ix3Configuration.server.api;
        $scope.mostrarCodigosMunicipio = function () {
            dialog.create('mostrarCodigosMunicipio');
        };
        $scope.failImportJson = function (data) {
            if (data && data.jqXHR) {
                if (data.jqXHR.status === 500) {
                    alert("Uf, esto es embarazoso pero \n ha ocurrido un error al procesar la petición:\n"+data.jqXHR.responseText);
                } else {
                    if (data.jqXHR.responseText) {
                        $scope.businessMessages = JSON.parse(data.jqXHR.responseText);
                    }
                }
            }
        };
        $scope.updateList = function () {
            alert("El listado de Titulados se importó correctamente");
            $scope.search();
        };

        $scope.anyo=null;
        $scope.anyos=[];
        var currentYear=(new Date()).getFullYear();
        for(var anyo=currentYear;anyo>=1980;anyo--) {
            $scope.anyos.push(anyo);
        }

        if ($scope.user && $scope.user.centro) {
            $scope.centro=$scope.user.centro;
            getEstadisticasByCentro($scope,$scope.user.centro,$scope.anyo,$scope.anyo);
        }

        function getEstadisticasByCentro($scope,centro,anyoInicio,anyoFin) {
            $http({
                method: "GET",
                url: ix3Configuration.server.api + "/Estadisticas/centro/" + centro.idCentro + "?expand=titulosFPPorFamilia.tituladosPorCiclo&anyoInicio=" + (anyoInicio==null?'':anyoInicio) +"&anyoFin=" + (anyoFin==null?'':anyoFin)
            }).then(function (estadisticas) {
                $scope.centro.estadisticas = estadisticas.data;
            });
        }

        $scope.buttonSearch=function() {
            getEstadisticasByCentro($scope,$scope.user.centro,$scope.anyo,$scope.anyo);
        }

    }]);
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of fiware-iotagent-lib
 *
 * fiware-iotagent-lib 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.
 *
 * fiware-iotagent-lib 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 fiware-iotagent-lib.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::daniel.moranjimenez@telefonica.com
 */

'use strict';

var async = require('async'),
    apply = async.apply,
    ngsi = require('./services/ngsi/ngsiService'),
    statsRegistry = require('./services/stats/statsRegistry'),
    deviceService = require('./services/devices/deviceService'),
    groupConfig = require('./services/groups/groupService'),
    security = require('./services/common/securityService'),
    iotManager = require('./services/common/iotManagerService'),
    contextServer = require('./services/northBound/northboundServer'),
    errors = require('./errors'),
    logger = require('logops'),
    context = {
        op: 'IoTAgentNGSI.Global'
    },
    config;

function activateStatLogs(newConfig, callback) {
    if (newConfig.stats && newConfig.stats.interval) {
        async.series([
            apply(statsRegistry.globalLoad, {
                deviceCreationRequests: 0,
                deviceRemovalRequests: 0,
                measureRequests: 0
            }),
            apply(statsRegistry.addTimerAction, statsRegistry.logStats)
        ], callback);
    } else {
        callback();
    }
}

/**
 * Activates the IoT Agent to start listening for NGSI Calls (to act as a Context Provider). It also creates the
 * device registry for the IoT Agent (based on the deviceRegistry.type configuration option).
 *
 * @param {Object} newConfig            Configuration of the Context Server
 */
function doActivate(newConfig, callback) {
    var registry,
        groupRegistry;

    config = newConfig;

    if (config.logLevel) {
        logger.setLevel(config.logLevel);
    }

    logger.info(context, 'Activating IOT Agent NGSI Library.');

    if (newConfig.deviceRegistry &&
        newConfig.deviceRegistry.type &&
        newConfig.deviceRegistry.type === 'mongodb') {
        logger.info(context, 'MongoDB Device registry selected for NGSI Library');

        registry = require('./services/devices/deviceRegistryMongoDB');
        groupRegistry = require('./services/groups/groupRegistryMongoDB');
    } else {
        logger.info(context, 'Falling back to Transient Memory registry for NGSI Library');

        registry = require('./services/devices/deviceRegistryMemory');
        groupRegistry = require('./services/groups/groupRegistryMemory');
    }

    exports.clearAll = registry.clear;

    async.series([
        apply(registry.init, newConfig),
        apply(statsRegistry.init, newConfig),
        apply(ngsi.init, registry, groupRegistry, newConfig),
        apply(iotManager.init, groupRegistry),
        apply(deviceService.init, registry, groupRegistry, newConfig),
        apply(groupConfig.init, groupRegistry, newConfig),
        apply(security.init, newConfig),
        apply(contextServer.start, newConfig),
        apply(activateStatLogs, newConfig)
    ], callback);
}

function checkConfig(newConfig, callback) {
    var mandatory = ['providerUrl', 'types'],
        missing = [];

    for (var i in mandatory) {
        if (!newConfig[mandatory[i]]) {
            missing.push(mandatory[i]);
        }
    }

    if (missing.length === 0) {
        callback();
    } else {
        callback(new errors.MissingConfigParams(missing));
    }
}

function activate(newConfig, callback) {
    async.series([
        apply(checkConfig, newConfig),
        apply(doActivate, newConfig),
        apply(iotManager.register, newConfig)
    ], callback);
}

/**
 * Stops the HTTP server.
 */
function deactivate(callback) {
    contextServer.stop(callback);
}

exports.activate = activate;
exports.deactivate = deactivate;
exports.register = deviceService.register;
exports.updateRegister = deviceService.updateRegister;
exports.unregister = deviceService.unregister;
exports.query = ngsi.query;
exports.update = ngsi.update;
exports.setCommandResult = ngsi.setCommandResult;
exports.listDevices = deviceService.listDevices;
exports.getDevice = deviceService.getDevice;
exports.getDeviceByName = deviceService.getDeviceByName;
exports.getDevicesByAttribute = deviceService.getDevicesByAttribute;
exports.getConfiguration = groupConfig.get;
exports.findConfiguration = groupConfig.find;
exports.setDataUpdateHandler = contextServer.setUpdateHandler;
exports.setCommandHandler = contextServer.setCommandHandler;
exports.setDataQueryHandler = contextServer.setQueryHandler;
exports.setConfigurationHandler = contextServer.setConfigurationHandler;
exports.setProvisioningHandler = contextServer.setProvisioningHandler;
exports.statsRegistry = statsRegistry;
exports.clearRegistry = deviceService.clearRegistry;
<commit_msg>ADD Group clean to the clearAll function<commit_after>/*
 * Copyright 2014 Telefonica Investigación y Desarrollo, S.A.U
 *
 * This file is part of fiware-iotagent-lib
 *
 * fiware-iotagent-lib 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.
 *
 * fiware-iotagent-lib 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 fiware-iotagent-lib.
 * If not, seehttp://www.gnu.org/licenses/.
 *
 * For those usages not covered by the GNU Affero General Public License
 * please contact with::daniel.moranjimenez@telefonica.com
 */

'use strict';

var async = require('async'),
    apply = async.apply,
    ngsi = require('./services/ngsi/ngsiService'),
    statsRegistry = require('./services/stats/statsRegistry'),
    deviceService = require('./services/devices/deviceService'),
    groupConfig = require('./services/groups/groupService'),
    security = require('./services/common/securityService'),
    iotManager = require('./services/common/iotManagerService'),
    contextServer = require('./services/northBound/northboundServer'),
    errors = require('./errors'),
    logger = require('logops'),
    context = {
        op: 'IoTAgentNGSI.Global'
    },
    config;

function activateStatLogs(newConfig, callback) {
    if (newConfig.stats && newConfig.stats.interval) {
        async.series([
            apply(statsRegistry.globalLoad, {
                deviceCreationRequests: 0,
                deviceRemovalRequests: 0,
                measureRequests: 0
            }),
            apply(statsRegistry.addTimerAction, statsRegistry.logStats)
        ], callback);
    } else {
        callback();
    }
}

/**
 * Activates the IoT Agent to start listening for NGSI Calls (to act as a Context Provider). It also creates the
 * device registry for the IoT Agent (based on the deviceRegistry.type configuration option).
 *
 * @param {Object} newConfig            Configuration of the Context Server
 */
function doActivate(newConfig, callback) {
    var registry,
        groupRegistry;

    config = newConfig;

    if (config.logLevel) {
        logger.setLevel(config.logLevel);
    }

    logger.info(context, 'Activating IOT Agent NGSI Library.');

    if (newConfig.deviceRegistry &&
        newConfig.deviceRegistry.type &&
        newConfig.deviceRegistry.type === 'mongodb') {
        logger.info(context, 'MongoDB Device registry selected for NGSI Library');

        registry = require('./services/devices/deviceRegistryMongoDB');
        groupRegistry = require('./services/groups/groupRegistryMongoDB');
    } else {
        logger.info(context, 'Falling back to Transient Memory registry for NGSI Library');

        registry = require('./services/devices/deviceRegistryMemory');
        groupRegistry = require('./services/groups/groupRegistryMemory');
    }

    exports.clearAll = function(callback) {
        async.series([
            registry.clear,
            groupRegistry.clear
        ], callback);
    };

    async.series([
        apply(registry.init, newConfig),
        apply(statsRegistry.init, newConfig),
        apply(ngsi.init, registry, groupRegistry, newConfig),
        apply(iotManager.init, groupRegistry),
        apply(deviceService.init, registry, groupRegistry, newConfig),
        apply(groupConfig.init, groupRegistry, newConfig),
        apply(security.init, newConfig),
        apply(contextServer.start, newConfig),
        apply(activateStatLogs, newConfig)
    ], callback);
}

function checkConfig(newConfig, callback) {
    var mandatory = ['providerUrl', 'types'],
        missing = [];

    for (var i in mandatory) {
        if (!newConfig[mandatory[i]]) {
            missing.push(mandatory[i]);
        }
    }

    if (missing.length === 0) {
        callback();
    } else {
        callback(new errors.MissingConfigParams(missing));
    }
}

function activate(newConfig, callback) {
    async.series([
        apply(checkConfig, newConfig),
        apply(doActivate, newConfig),
        apply(iotManager.register, newConfig)
    ], callback);
}

/**
 * Stops the HTTP server.
 */
function deactivate(callback) {
    contextServer.stop(callback);
}

exports.activate = activate;
exports.deactivate = deactivate;
exports.register = deviceService.register;
exports.updateRegister = deviceService.updateRegister;
exports.unregister = deviceService.unregister;
exports.query = ngsi.query;
exports.update = ngsi.update;
exports.setCommandResult = ngsi.setCommandResult;
exports.listDevices = deviceService.listDevices;
exports.getDevice = deviceService.getDevice;
exports.getDeviceByName = deviceService.getDeviceByName;
exports.getDevicesByAttribute = deviceService.getDevicesByAttribute;
exports.getConfiguration = groupConfig.get;
exports.findConfiguration = groupConfig.find;
exports.setDataUpdateHandler = contextServer.setUpdateHandler;
exports.setCommandHandler = contextServer.setCommandHandler;
exports.setDataQueryHandler = contextServer.setQueryHandler;
exports.setConfigurationHandler = contextServer.setConfigurationHandler;
exports.setProvisioningHandler = contextServer.setProvisioningHandler;
exports.statsRegistry = statsRegistry;
exports.clearRegistry = deviceService.clearRegistry;
<|endoftext|>


<commit_before>/**
 * JavaScript utilities for CImage and img.php.
 */
window.CImage = (function(){
    "use strict";

    /**
     * Update the permalink.
     */
    function updatePermaLink() {
        var link,
            input1 = document.getElementById("input1"),
            input2 = document.getElementById("input2"),
            input3 = document.getElementById("input3"),
            input4 = document.getElementById("input4"),
            details = document.getElementById("viewDetails"),
            stack = document.getElementById("stack"),
            permalink = document.getElementById("permalink");

        link  = "?";
        link += "input1=" + encodeURIComponent(input1.value) + "&";
        link += "input2=" + encodeURIComponent(input2.value) + "&";
        link += "input3=" + encodeURIComponent(input3.value) + "&";
        link += "input4=" + encodeURIComponent(input4.value) + "&";
        link += "json=" + encodeURIComponent(details.checked) + "&";
        link += "stack=" + encodeURIComponent(stack.checked);
        permalink.href = link;
    }

    /**
     * Init the compare page with details.
     */
    function compareLoadImage(event) {
        var img, json, button, area, deck, id, permalink;

        id = this.dataset.id;
        img = document.getElementById("img" + id);
        json = document.getElementById("json" + id);
        button = document.getElementById("button" + id);
        area = document.getElementById("area" + id);
        deck = document.getElementById("deck" + id);

        updatePermaLink();

        if (this.value == "") {
            // Clear image if input is cleared
            button.setAttribute("disabled", "disabled");
            area.classList.add("hidden");
            button.classList.remove("selected");
            return;
        }

        // Display image in its area
        img.src = this.value;
        area.classList.remove("hidden");

        $.getJSON(this.value + "&json", function(data) {
            json.innerHTML = "filename: " + data.filename + "\ncolors: " + data.colors + "\nsize: " + data.size + "\nwidth: " + data.width + "\nheigh: " + data.height + "\naspect-ratio: " + data.aspectRatio;
        })
            .fail(function() {
                json.innerHTML = "Details not available."
                console.log( "JSON error" );
            });

        // Display image in overlay
        button.removeAttribute("disabled");
        button.classList.add("selected");

    };

    /**
     * Init the compare page with details.
     */
    function compareInit(options)
    {
        var elements, id, onTop, myEvent,
            input1 = document.getElementById("input1"),
            input2 = document.getElementById("input2"),
            input3 = document.getElementById("input3"),
            input4 = document.getElementById("input4"),
            details = document.getElementById("viewDetails"),
            stack = document.getElementById("stack"),
            buttons = document.getElementById("buttonWrap");

        input1.addEventListener("change", compareLoadImage);
        input2.addEventListener("change", compareLoadImage);
        input3.addEventListener("change", compareLoadImage);
        input4.addEventListener("change", compareLoadImage);

        // Toggle json
        details.addEventListener("change", function() {
            var elements = document.querySelectorAll(".json");
            for (var element of elements) {
                element.classList.toggle("hidden");
            }
            updatePermaLink();
            console.log("View JSON");
        });

        // Show json as default
        if (options.json === true) {
            details.setAttribute("checked", "checked");
            myEvent = new CustomEvent("change");
            details.dispatchEvent(myEvent);
        }

        // Toggle stack
        stack.addEventListener("change", function() {
            var element,
                elements = document.querySelectorAll(".area");

            buttons.classList.toggle("hidden");

            for (element of elements) {
                element.classList.toggle("stack");

                if (!element.classList.contains('hidden')) {
                    onTop = element;
                }
            }
            onTop.classList.toggle("top");
            updatePermaLink();

            console.log("Stacking");
        });

        // Stack as default
        if (options.stack === true) {
            stack.setAttribute("checked", "checked");
            myEvent = new CustomEvent("change");
            stack.dispatchEvent(myEvent);
        }

        // Button clicks
        elements = document.querySelectorAll(".button");
        for (var element of elements) {
            element.addEventListener("click", function() {
                var id = this.dataset.id,
                    area = document.getElementById("area" + id);

                area.classList.toggle("top");
                onTop.classList.toggle("top");
                onTop = area;
                console.log("button" + id);
            });
        }

        input1.value = options.input1 || null;
        input2.value = options.input2 || null;
        input3.value = options.input3 || null;
        input4.value = options.input4 || null;

        compareLoadImage.call(input1);
        compareLoadImage.call(input2);
        compareLoadImage.call(input3);
        compareLoadImage.call(input4);

        console.log(options);
    }

    return {
        "compare": compareInit
    };

}());
<commit_msg>remove ECMA 6 construct of for of<commit_after>/**
 * JavaScript utilities for CImage and img.php.
 */
window.CImage = (function() {
    "use strict";

    /**
     * Waiting for ECMA 6...
     */
     var forEach = function(array, callback, scope) {
      for (var i = 0; i < array.length; i++) {
        callback.call(scope, i, array[i]);
      }
    };

    /**
     * Update the permalink.
     */
    function updatePermaLink() {
        var link,
            input1 = document.getElementById("input1"),
            input2 = document.getElementById("input2"),
            input3 = document.getElementById("input3"),
            input4 = document.getElementById("input4"),
            details = document.getElementById("viewDetails"),
            stack = document.getElementById("stack"),
            permalink = document.getElementById("permalink");

        link  = "?";
        link += "input1=" + encodeURIComponent(input1.value) + "&";
        link += "input2=" + encodeURIComponent(input2.value) + "&";
        link += "input3=" + encodeURIComponent(input3.value) + "&";
        link += "input4=" + encodeURIComponent(input4.value) + "&";
        link += "json=" + encodeURIComponent(details.checked) + "&";
        link += "stack=" + encodeURIComponent(stack.checked);
        permalink.href = link;
    }

    /**
     * Init the compare page with details.
     */
    function compareLoadImage(event) {
        var img, json, button, area, deck, id, permalink;

        id = this.dataset.id;
        img = document.getElementById("img" + id);
        json = document.getElementById("json" + id);
        button = document.getElementById("button" + id);
        area = document.getElementById("area" + id);
        deck = document.getElementById("deck" + id);

        updatePermaLink();

        if (this.value == "") {
            // Clear image if input is cleared
            button.setAttribute("disabled", "disabled");
            area.classList.add("hidden");
            button.classList.remove("selected");
            return;
        }

        // Display image in its area
        img.src = this.value;
        area.classList.remove("hidden");

        $.getJSON(this.value + "&json", function(data) {
            json.innerHTML = "filename: " + data.filename + "\ncolors: " + data.colors + "\nsize: " + data.size + "\nwidth: " + data.width + "\nheigh: " + data.height + "\naspect-ratio: " + data.aspectRatio;
        })
            .fail(function() {
                json.innerHTML = "Details not available."
                console.log( "JSON error" );
            });

        // Display image in overlay
        button.removeAttribute("disabled");
        button.classList.add("selected");

    };

    /**
     * Init the compare page with details.
     */
    function compareInit(options)
    {
        var elements, id, onTop, myEvent,
            input1 = document.getElementById("input1"),
            input2 = document.getElementById("input2"),
            input3 = document.getElementById("input3"),
            input4 = document.getElementById("input4"),
            details = document.getElementById("viewDetails"),
            stack = document.getElementById("stack"),
            buttons = document.getElementById("buttonWrap");

        input1.addEventListener("change", compareLoadImage);
        input2.addEventListener("change", compareLoadImage);
        input3.addEventListener("change", compareLoadImage);
        input4.addEventListener("change", compareLoadImage);

        // Toggle json
        details.addEventListener("change", function() {
            var elements = document.querySelectorAll(".json");

            forEach(elements, function (index, element) {
                element.classList.toggle("hidden");
            });

            /* ECMA 6
            for (var element of elements) {
                element.classList.toggle("hidden");
            }
            */

            updatePermaLink();
            console.log("View JSON");
        });

        // Show json as default
        if (options.json === true) {
            details.setAttribute("checked", "checked");
            myEvent = new CustomEvent("change");
            details.dispatchEvent(myEvent);
        }

        // Toggle stack
        stack.addEventListener("change", function() {
            var element,
                elements = document.querySelectorAll(".area");

            buttons.classList.toggle("hidden");

            forEach(elements, function (index, element) {
                element.classList.toggle("stack");

                if (!element.classList.contains('hidden')) {
                    onTop = element;
                }
            });

            /* ECMA 6
            for (element of elements) {
                element.classList.toggle("stack");

                if (!element.classList.contains('hidden')) {
                    onTop = element;
                }
            }
            */

            onTop.classList.toggle("top");
            updatePermaLink();

            console.log("Stacking");
        });

        // Stack as default
        if (options.stack === true) {
            stack.setAttribute("checked", "checked");
            myEvent = new CustomEvent("change");
            stack.dispatchEvent(myEvent);
        }

        // Button clicks
        elements = document.querySelectorAll(".button");

        forEach(elements, function (index, element) {
            element.addEventListener("click", function() {
                var id = this.dataset.id,
                    area = document.getElementById("area" + id);

                area.classList.toggle("top");
                onTop.classList.toggle("top");
                onTop = area;
                console.log("button" + id);
            });
        });

        /* ECMA 6
        for (var element of elements) {
            element.addEventListener("click", function() {
                var id = this.dataset.id,
                    area = document.getElementById("area" + id);

                area.classList.toggle("top");
                onTop.classList.toggle("top");
                onTop = area;
                console.log("button" + id);
            });
        }
        */

        input1.value = options.input1 || null;
        input2.value = options.input2 || null;
        input3.value = options.input3 || null;
        input4.value = options.input4 || null;

        compareLoadImage.call(input1);
        compareLoadImage.call(input2);
        compareLoadImage.call(input3);
        compareLoadImage.call(input4);

        console.log(options);
    }

    return {
        "compare": compareInit
    };

}());
<|endoftext|>


<commit_before>var test = require('tap').test
var fs = require('fs')
var pkg = process.env.npm_config_tmp || '/tmp/'
pkg += 'npm-test-publish-config'

require('mkdirp').sync(pkg)

fs.writeFileSync(pkg + '/package.json', JSON.stringify({
  name: 'npm-test-publish-config',
  version: '1.2.3',
  publishConfig: { registry: 'http://localhost:13370' }
}), 'utf8')

var spawn = require('child_process').spawn
var npm = require.resolve('../../bin/npm-cli.js')
var node = process.execPath

console.error('pkg=%j', pkg)

test(function (t) {
  var child
  require('http').createServer(function (req, res) {
    t.pass('got request on the fakey fake registry')
    t.end()
    this.close()
    res.statusCode = 500
    res.end('{"error":"sshhh. naptime nao. \\^O^/ <(YAWWWWN!)"}')
    child.kill()
  }).listen(13370, function () {
    t.pass('server is listening')

    // don't much care about listening to the child's results
    // just wanna make sure it hits the server we just set up.
    //
    // there are plenty of other tests to verify that publish
    // itself functions normally.
    child = spawn(node, [npm, 'publish'], {
      cwd: pkg
    })
  })
})
<commit_msg>fix travis test<commit_after>var test = require('tap').test
var fs = require('fs')
var pkg = process.env.npm_config_tmp || '/tmp'
pkg += '/npm-test-publish-config'

require('mkdirp').sync(pkg)

fs.writeFileSync(pkg + '/package.json', JSON.stringify({
  name: 'npm-test-publish-config',
  version: '1.2.3',
  publishConfig: { registry: 'http://localhost:13370' }
}), 'utf8')

var spawn = require('child_process').spawn
var npm = require.resolve('../../bin/npm-cli.js')
var node = process.execPath

console.error('pkg=%j', pkg)

test(function (t) {
  var child
  require('http').createServer(function (req, res) {
    t.pass('got request on the fakey fake registry')
    t.end()
    this.close()
    res.statusCode = 500
    res.end('{"error":"sshhh. naptime nao. \\^O^/ <(YAWWWWN!)"}')
    child.kill()
  }).listen(13370, function () {
    t.pass('server is listening')

    // don't much care about listening to the child's results
    // just wanna make sure it hits the server we just set up.
    //
    // there are plenty of other tests to verify that publish
    // itself functions normally.
    child = spawn(node, [npm, 'publish'], {
      cwd: pkg
    })
  })
})
<|endoftext|>


<commit_before>(function($) {
    'use strict'

    var Panel = function() {
        //set the monitoring form.
        this.setForm();
        //run an initial evaluation with current form's settings.
        this.evaluateWithServer();
        //Observe the form.
        this.observe();
    };

    Panel.prototype.buildData = function() {
        var $form = this.form;
        var data = {};
        $form.find(':input').each(function() {
            var name = $(this).attr('name');
            var value = $(this).val();
            if (typeof name !== 'undefined' && typeof value !== 'undefined' ) {
                data[name] = value;
            }
        });

        return data;
    };

    Panel.prototype.hidePanels = function(panels) {
        if (!panels instanceof Array) {
            return false;
        }

        panels.forEach(function(cur){
            var current = cur;
            var $panel = $('.panel');
            $panel.each(function() {
                var title = $(this).find('.panel-title').text();
                if (current === title) {
                    if (!$(this).hasClass('hidden')) {
                        $(this).addClass('hidden');
                    }
                }
            });
        });
    };

    Panel.prototype.resetVisibility = function() {
        $('.panel').removeClass('hidden');
    };

    Panel.prototype.setForm = function() {
        this.form = $('.panel').closest('form');
    };

    Panel.prototype.observe = function() {
        var $form = this.form;
        var that = this;
        $form.find(':input').change(function() {
            that.evaluateWithServer();
        });
    };

    Panel.prototype.evaluateWithServer = function() {
        var $form = this.form;
        var action = $form.attr('action');
        var matches = action.split('/', 2);
        var module = matches[1];
        var that = this;
        if (!module) {
            return false;
        }
        var url = '/api/' + module + '/panels/';
        var token = api_options.token;
        $.ajax({
            url: url,
            type: 'POST',
            data: that.buildData(),
            dataType: 'json',
            headers: {
                'Authorization': 'Bearer ' + token
            },
            success: function(data)
            {
                if(typeof data.error === 'undefined') {
                    that.resetVisibility();
                    that.hidePanels(data.data);
                } else {
                    console.log('Panel - Ajax failing. Unable to hide panels.');
                }
            },
        });
    };

    new Panel();

})(jQuery);
<commit_msg>Eligibe actions (task #2322)<commit_after>(function($) {
    'use strict'

    var Panel = function() {
        if (!this.isEligibleAction()) {
            return false;
        }
        //set the monitoring form.
        this.setForm();
        //run an initial evaluation with current form's settings.
        this.evaluateWithServer();
        //Observe the form.
        this.observe();
    };

    /**
     * Check if the running action is eligible.
     *
     * This function provides the eligible actions for hiding and
     * showing the panels.
     * @return {Boolean} True if the current is action is eligible.
     */
    Panel.prototype.isEligibleAction = function() {
        var actions = ['add', 'edit'];
        var pathname = window.location.pathname;
        var matches = pathname.split('/', 3);
        var action = matches[matches.length - 1];
        var pos = actions.indexOf(action);

        return (pos > -1) ? true : false;
    };

    Panel.prototype.buildData = function() {
        var $form = this.form;
        var data = {};
        $form.find(':input').each(function() {
            var name = $(this).attr('name');
            var value = $(this).val();
            if (typeof name !== 'undefined' && typeof value !== 'undefined' ) {
                data[name] = value;
            }
        });

        return data;
    };

    Panel.prototype.hidePanels = function(panels) {
        if (!panels instanceof Array) {
            return false;
        }

        panels.forEach(function(cur){
            var current = cur;
            var $panel = $('.panel');
            $panel.each(function() {
                var title = $(this).find('.panel-title').text();
                if (current === title) {
                    if (!$(this).hasClass('hidden')) {
                        $(this).addClass('hidden');
                    }
                }
            });
        });
    };

    Panel.prototype.resetVisibility = function() {
        $('.panel').removeClass('hidden');
    };

    Panel.prototype.setForm = function() {
        this.form = $('.panel').closest('form');
    };

    Panel.prototype.observe = function() {
        var $form = this.form;
        var that = this;
        $form.find(':input').change(function() {
            that.evaluateWithServer();
        });
    };

    Panel.prototype.evaluateWithServer = function() {
        var $form = this.form;
        var action = $form.attr('action');
        var matches = action.split('/', 2);
        var module = matches[1];
        var that = this;
        if (!module) {
            return false;
        }
        var url = '/api/' + module + '/panels/';
        var token = api_options.token;
        $.ajax({
            url: url,
            type: 'POST',
            data: that.buildData(),
            dataType: 'json',
            headers: {
                'Authorization': 'Bearer ' + token
            },
            success: function(data)
            {
                if(typeof data.error === 'undefined') {
                    that.resetVisibility();
                    that.hidePanels(data.data);
                } else {
                    console.log('Panel - Ajax failing. Unable to hide panels.');
                }
            },
        });
    };

    new Panel();

})(jQuery);
<|endoftext|>


<commit_before>var nodeunit	 			= require('nodeunit')
	, mod_cssnormalizer		= require('../lib/cssnormalizer.js')

module.exports = nodeunit.testCase({
	testSimple : function (test) {
		var css = "p{background-image:url(/test/me.css)}\n\ntd { \n background-image: url('../../../foo.png');\ncolor:red}\na {\n background-image: url(\"bar.png\");\n\n@import url(grunz.css)";
		var exp = 'p{background-image:url("/modules/app/test/me.css")}\n\ntd { \n background-image: url("/foo.png");\ncolor:red}\na {\n background-image: url("/modules/app/bar.png");\n\n@import url("/modules/app/grunz.css")';

		var ncss = mod_cssnormalizer.normalize(css, '/modules/app');
		test.equal(ncss, exp)
		test.done();
	}

});<commit_msg>OBEY!<commit_after>var nodeunit	 			= require('nodeunit')
	, mod_cssnormalizer		= require('../lib/cssnormalizer.js')

module.exports = nodeunit.testCase({
	testSimple : function (test) {
		var css = "p{background-image:url(/test/me.css)}\n\ntd { \n background-image: url('../../../foo.png');\ncolor:red}\na {\n background-image: url(\"bar.png\");\n\n@import url(grunz.css)";
		var exp = 'p{background-image:url("/modules/app/test/me.css")}\n\ntd { \n background-image: url("/foo.png");\ncolor:red}\na {\n background-image: url("/modules/app/bar.png");\n\n@import url("/modules/app/grunz.css")';

		var ncss = mod_cssnormalizer.normalize(css, '/modules/app');
		test.equal(ncss, exp);
		test.done();
	}

});<|endoftext|>


<commit_before>// This file is responsible for performing modules initialization like configuration load,
// providers initialization, application server startup etc.

var colors  = require('colors'),
    when    = require('when');

function startPanda (app) {
    when()
        .then(function () {
            return require('./server/config').init();
        })
        .then(function () {
            return require('./server/providers').init();
        })
        .then(function () {
            var panda = require('./server');
            panda(app);
        })
        .catch(function (err) {
            console.log(("Panda server initialization error " + err).red);
        })
}

module.exports = startPanda;<commit_msg>Display stack trace when error<commit_after>// This file is responsible for performing modules initialization like configuration load,
// providers initialization, application server startup etc.

var colors  = require('colors'),
    when    = require('when');

function startPanda (app) {
    when()
        .then(function () {
            return require('./server/config').init();
        })
        .then(function () {
            return require('./server/providers').init();
        })
        .then(function () {
            var panda = require('./server');
            panda(app);
        })
        .catch(function (err) {
            console.log(("Panda server initialization error " + err).red);
            console.log((err.stack).red);
        })
}

module.exports = startPanda;<|endoftext|>


<commit_before>var express					= require('express'),
		path						= require('path'),
		passwordless 		= require('passwordless'),
		RouteController = require('./controllers/routes'),
		AuthController 	= require('./controllers/auth');

module.exports = function(app) {
	var router = express.Router();
	// API routes ===========================================================

	router.get('/', function (req, res) {
		res.json({ message: 'Welcome to the API!' });
	});

	// API route handlers for /media
	router.route('/media')
		// .post(passwordless.restricted, RouteController.postMedia)
		.post(RouteController.postMedia)
		.get(RouteController.getMedia);

	// API route handlers for /media/:file
	router.route('/media/:file')
		.get(RouteController.getFile)
		// .put(passwordless.restricted, RouteController.putFile)
		// .delete(passwordless.restricted, RouteController.deleteFile);
		.put(RouteController.putFile)
		.delete(RouteController.deleteFile);

	// API route handlers for /photos
	router.route('/photos')
		.get(RouteController.getPhotos);

	// API route handlers for /videos
	router.route('/videos')
		.get(RouteController.getVideos);

	// API route handlers for /users
	router.route('/users')
		// .post(passwordless.restricted, RouteController.postUsers)
		.post(RouteController.postUsers)
		.get(RouteController.getUsers);

	// API route handlers for /users/:user
	router.route('/users/:user')
		.get(RouteController.getUser)
		// .put(passwordless.restricted, RouteController.putUser)
		// .delete(passwordless.restricted, RouteController.deleteUser);
		.put(RouteController.putUser)
		.delete(RouteController.deleteUser);

	// API route handlers for /sendtoken
	router.route('/sendtoken')
		.post(AuthController.requestToken, RouteController.postSendToken);

	// API route handlers for /login
	router.route('/login')
		.post(passwordless.acceptToken, RouteController.postLogin);

	// API route handlers for /logout
	router.route('/logout')
		// .post(passwordless.logout);
		.post();

	/* Register API Routes */
	app.use('/api/v1', router);

	// frontend routes ===========================================================

	/* Front End Routes Handled by Angular */
	app.get('*', function (req, res) {
		res.sendFile(path.join(__dirname, '../public/views', 'index.html'));
	});
};<commit_msg>Updating routes based on new data structure<commit_after>var express					= require('express'),
		path						= require('path'),
		passwordless 		= require('passwordless'),
		RouteController = require('./controllers/routes'),
		AuthController 	= require('./controllers/auth');

module.exports = function(app) {
	var router = express.Router();
	// ==========================================================================
	// API Routes ===============================================================
	// ==========================================================================

	router.get('/', function (req, res) {
		res.json({ message: 'Welcome to the API!' });
	});

	// Media Routes =============================================================

	// API route handlers for /media
	router.route('/media')
		.get(RouteController.getMedia);

	// Photo Routes =============================================================
	// API route handlers for /photos
	router.route('/photos')
		.get(RouteController.getPhotos)
		.post(RouteController.postPhotos);

	// API route handlers for /photos/:id
	router.route('/photos/:id')
		.get(RouteController.getPhoto)
		.put(RouteController.putPhoto)
		.delete(RouteController.deletePhoto);

	// Video Routes =============================================================

	// API route handlers for /videos
	router.route('/videos')
		.get(RouteController.getVideos)
		.post(RouteController.postVideos);

	// API route handlers for /photos/:id
	router.route('/videos/:id')
		.get(RouteController.getVideo)
		.put(RouteController.putVideo)
		.delete(RouteController.deleteVideo);

	// User Routes ==============================================================

	// API route handlers for /users
	router.route('/users')
		// .post(passwordless.restricted, RouteController.postUsers)
		.post(RouteController.postUsers)
		.get(RouteController.getUsers);

	// API route handlers for /users/:user
	router.route('/users/:user')
		.get(RouteController.getUser)
		// .put(passwordless.restricted, RouteController.putUser)
		// .delete(passwordless.restricted, RouteController.deleteUser);
		.put(RouteController.putUser)
		.delete(RouteController.deleteUser);

	// API route handlers for /sendtoken
	router.route('/sendtoken')
		.post(AuthController.requestToken, RouteController.postSendToken);

	// API route handlers for /login
	router.route('/login')
		.post(passwordless.acceptToken, RouteController.postLogin);

	// API route handlers for /logout
	router.route('/logout')
		// .post(passwordless.logout);
		.post();

	// Register API Routes ======================================================

	app.use('/api/v1', router);

	// Frontend rRutes ==========================================================

	/* Front End Routes Handled by Angular */
	app.get('*', function (req, res) {
		res.sendFile(path.join(__dirname, '../public/views', 'index.html'));
	});
};<|endoftext|>


<commit_before>// HTTP/HTTPS
var https = require('https');
var http = require('http');
// Express
var express = require('express');
var inspect = require('util').inspect;
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var compress = require('compression');
var authentication = require('./middleware/authentication');
var crypto = require('crypto');
// File System
var fs = require('fs');

var ACCESS = require('./routes/access');
var API = require('./routes/api');

// Make Database connection
// & Start the server
module.exports = function(environment, port, connection, instance) {
    var app = express();

    if (!port) port = 3000; // Default port;

    app.set("models", connection.collections);
    app.set("connections", connection.connections);
    app.set("galleon", instance);
    app.set("environment", environment);
    app.set("secret", environment.secret);

    // SSL Detection, Automatically switches between HTTP and HTTPS on start
    if (environment.ssl.use) {
        var SSL_CONFIG;
        try {
            SSL_CONFIG = {
                key: fs.readFileSync(environment.ssl.api.key, 'utf8'),
                cert: fs.readFileSync(environment.ssl.api.cert, 'utf8')
            }
        }catch(e) {
            http.createServer(app).listen(port);
        }
        https.createServer(SSL_CONFIG, app).listen(port);
    }else {
        http.createServer(app).listen(port);
    }

    // Allow API access outside origin (This is an API after all)
    app.use(function(req, res, next) {
		// Allow for Webmail interface
        res.header("Access-Control-Allow-Origin", req.protocol + '://' + environment.domain + ":2095");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
		res.header("Access-Control-Allow-Credentials", "true")
        next();
    });

    // uncomment after placing your favicon in /public
    //app.use(favicon(__dirname + '/public/favicon.ico'));
    app.use(compress());
    app.use(logger('dev'));

    // If Environment secret is not set assign a random secret on every restart
    app.use(cookieParser(app.get('secret') || crypto.randomBytes(20).toString('hex')));

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
        extended: false
    }));

    // Database middleware
    app.use(function(req, res, next) {
        req.galleon = app.get("galleon");
        req.database = {
            models: app.get("models"),
            connections: app.get("connections")
        }
        req.environment = app.get("environment");
        next();
    });

    app.use(authentication({
        login: '/access/login',
        logout: '/access/logout'
    }));
    app.use('//access', ACCESS);
    app.use('//', API);

    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
        var err = new Error('Not Found');
        err.status = 404;
        next(err);
    });

    // error handlers

    // development error handler
    // will print stacktrace
    if (app.get('env') === 'development') {
        app.use(function(err, req, res, next) {
            console.trace(err);
            res.status(err.status || 500);
            res.json({
                message: err.message,
                error: inspect(err, {
                    showHidden: true,
                    depth: 5
                })
            })
        });
    }

    // production error handler
    // no stacktraces leaked to user
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.json({
            message: err.message,
            error: JSON.stringify(err)
        })
    });
}
<commit_msg>Fixed a bug<commit_after>// HTTP/HTTPS
var https = require('https');
var http = require('http');
// Express
var express = require('express');
var inspect = require('util').inspect;
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var compress = require('compression');
var authentication = require('./middleware/authentication');
var crypto = require('crypto');
// File System
var fs = require('fs');

var ACCESS = require('./routes/access');
var API = require('./routes/api');

// Make Database connection
// & Start the server
module.exports = function(environment, port, connection, instance) {
    var app = express();

    if (!port) port = 3000; // Default port;

    app.set("models", connection.collections);
    app.set("connections", connection.connections);
    app.set("galleon", instance);
    app.set("environment", environment);
    app.set("secret", environment.secret);

    // SSL Detection, Automatically switches between HTTP and HTTPS on start
    if (environment.ssl.use) {
        var SSL_CONFIG;
        try {
            SSL_CONFIG = {
                key: fs.readFileSync(environment.ssl.api.key, 'utf8'),
                cert: fs.readFileSync(environment.ssl.api.cert, 'utf8')
            }
            https.createServer(SSL_CONFIG, app).listen(port);
        }catch(e) {
            http.createServer(app).listen(port);
        }
    }else {
        http.createServer(app).listen(port);
    }

    // Allow API access outside origin (This is an API after all)
    app.use(function(req, res, next) {
		// Allow for Webmail interface
        res.header("Access-Control-Allow-Origin", req.protocol + '://' + environment.domain + ":2095");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
		res.header("Access-Control-Allow-Credentials", "true")
        next();
    });

    // uncomment after placing your favicon in /public
    //app.use(favicon(__dirname + '/public/favicon.ico'));
    app.use(compress());
    app.use(logger('dev'));

    // If Environment secret is not set assign a random secret on every restart
    app.use(cookieParser(app.get('secret') || crypto.randomBytes(20).toString('hex')));

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
        extended: false
    }));

    // Database middleware
    app.use(function(req, res, next) {
        req.galleon = app.get("galleon");
        req.database = {
            models: app.get("models"),
            connections: app.get("connections")
        }
        req.environment = app.get("environment");
        next();
    });

    app.use(authentication({
        login: '/access/login',
        logout: '/access/logout'
    }));
    app.use('//access', ACCESS);
    app.use('//', API);

    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
        var err = new Error('Not Found');
        err.status = 404;
        next(err);
    });

    // error handlers

    // development error handler
    // will print stacktrace
    if (app.get('env') === 'development') {
        app.use(function(err, req, res, next) {
            console.trace(err);
            res.status(err.status || 500);
            res.json({
                message: err.message,
                error: inspect(err, {
                    showHidden: true,
                    depth: 5
                })
            })
        });
    }

    // production error handler
    // no stacktraces leaked to user
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.json({
            message: err.message,
            error: JSON.stringify(err)
        })
    });
}
<|endoftext|>


<commit_before>import Vue from 'vue'

const yaml = require('js-yaml')

const basePath = 'http://127.0.0.1:27866/api/v1/'

/*
 * Exported functions, which can be used in pages/components
 */

// loads all dependencies
export async function getDependencies (successFunc, errorFunc) {
  await sleep(1000)
  var handler = ['policy'].join('/')
  callAPI(handler, function (data) {
    var dependencies = getObjectsByKind(data['objects'], 'dependency')
    for (var idx in dependencies) {
      fetchDependency(dependencies[idx])
    }
    successFunc(dependencies)
  }, function (err) {
    errorFunc(err)
  })
}

// loads all endpoints
export async function getEndpoints (successFunc, errorFunc) {
  await sleep(1000)
  var handler = ['endpoints'].join('/')
  callAPI(handler, function (data) {
    successFunc(data['endpoints'])
  }, function (err) {
    errorFunc(err)
  })
}

/*
 * Utility/helper functions
 */

// sleeps for a given number of milliseconds
function sleep (ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

// makes an API call to Aptomi
function callAPI (handler, successFunc, errorFunc) {
  var path = basePath + handler
  var xhr = new XMLHttpRequest()
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        successFunc(yaml.safeLoad(xhr.responseText))
      } else {
        if (xhr.statusText) {
          errorFunc(xhr.status + ' ' + xhr.statusText)
        } else {
          errorFunc('unable to load data from ' + path)
        }
      }
    }
  }
  xhr.open('GET', path, true)
  xhr.send()
}

// receives a map[namespace][kind][name] -> generation and returns the list of objects with a given kind
function getObjectsByKind (data, kindFilter) {
  var result = []
  for (var ns in data) {
    for (var kind in data[ns]) {
      if (kind === kindFilter) {
        for (var name in data[ns][kind]) {
          var entry = {
            'namespace': ns,
            'kind': kind,
            'name': name,
            'generation': data[ns][kind][name]
          }
          fetchObjectProperties(entry)
          result.push(entry)
        }
      }
    }
  }
  return result
}

// receives a bare entry with populated fields (namespace, kind, name, generation), loads the corresponding object
// from the database and populates the corresponding fields in obj
function fetchObjectProperties (obj) {
  var handler = ['policy', 'gen', obj['generation'], 'object', obj['namespace'], obj['kind'], obj['name']].join('/')
  callAPI(handler, function (data) {
    for (var key in data) {
      Vue.set(obj, key, data[key])
    }
  }, function (err) {
    // can't fetch object properties
    Vue.set(obj, 'error', 'unable to fetch object properties: ' + err)
  })
}

// fetches data for a single dependency
function fetchDependency (d) {
  var handler = ['dependency_status'].join('/')
  callAPI(handler, function (data) {
    Vue.set(d, 'status', 'Deployed')
  }, function (err) {
    // can't fetch dependency properties
    Vue.set(d, 'status_error', 'unable to fetch dependency status: ' + err)
  })
}
<commit_msg>delayMs constant for debugging<commit_after>import Vue from 'vue'

const yaml = require('js-yaml')
const delayMs = 1000
const basePath = 'http://127.0.0.1:27866/api/v1/'

/*
 * Exported functions, which can be used in pages/components
 */

// loads all dependencies
export async function getDependencies (successFunc, errorFunc) {
  await makeDelay()
  var handler = ['policy'].join('/')
  callAPI(handler, function (data) {
    var dependencies = getObjectsByKind(data['objects'], 'dependency')
    for (var idx in dependencies) {
      fetchDependency(dependencies[idx])
    }
    successFunc(dependencies)
  }, function (err) {
    errorFunc(err)
  })
}

// loads all endpoints
export async function getEndpoints (successFunc, errorFunc) {
  await makeDelay()
  var handler = ['endpoints'].join('/')
  callAPI(handler, function (data) {
    successFunc(data['endpoints'])
  }, function (err) {
    errorFunc(err)
  })
}

/*
 * Utility/helper functions
 */

// sleeps for a given number of milliseconds
function makeDelay () {
  return new Promise(resolve => setTimeout(resolve, delayMs))
}

// makes an API call to Aptomi
function callAPI (handler, successFunc, errorFunc) {
  var path = basePath + handler
  var xhr = new XMLHttpRequest()
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        successFunc(yaml.safeLoad(xhr.responseText))
      } else {
        if (xhr.statusText) {
          errorFunc(xhr.status + ' ' + xhr.statusText)
        } else {
          errorFunc('unable to load data from ' + path)
        }
      }
    }
  }
  xhr.open('GET', path, true)
  xhr.send()
}

// receives a map[namespace][kind][name] -> generation and returns the list of objects with a given kind
function getObjectsByKind (data, kindFilter) {
  var result = []
  for (var ns in data) {
    for (var kind in data[ns]) {
      if (kind === kindFilter) {
        for (var name in data[ns][kind]) {
          var entry = {
            'namespace': ns,
            'kind': kind,
            'name': name,
            'generation': data[ns][kind][name]
          }
          fetchObjectProperties(entry)
          result.push(entry)
        }
      }
    }
  }
  return result
}

// receives a bare entry with populated fields (namespace, kind, name, generation), loads the corresponding object
// from the database and populates the corresponding fields in obj
function fetchObjectProperties (obj) {
  var handler = ['policy', 'gen', obj['generation'], 'object', obj['namespace'], obj['kind'], obj['name']].join('/')
  callAPI(handler, function (data) {
    for (var key in data) {
      Vue.set(obj, key, data[key])
    }
  }, function (err) {
    // can't fetch object properties
    Vue.set(obj, 'error', 'unable to fetch object properties: ' + err)
  })
}

// fetches data for a single dependency
function fetchDependency (d) {
  var handler = ['dependency_status'].join('/')
  callAPI(handler, function (data) {
    Vue.set(d, 'status', 'Deployed')
  }, function (err) {
    // can't fetch dependency properties
    Vue.set(d, 'status_error', 'unable to fetch dependency status: ' + err)
  })
}
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');
const test = require('ava');

test.before(() => {
  return helpers.run(path.join(__dirname, '../../generators/app'))
    .withPrompts({
      name: 'cool',
      author: 'super cool',
      description: 'cool descr',
      eslint: true,
      CI: ['Travis-CI', 'Appveyor'],
      docker: true,
      heroku: true,
      auth: true
    });
});

test('with auth', () => {
  assert.file([
    'src',
    '.editorconfig',
    '.eslintrc.js',
    'package.json',
    '.gitignore',
    '.travis.yml',
    'appveyor.yml',
    'README.md',
    'docker-compose.yml',
    'Dockerfile',
    'Procfile',
    'gulpfile.babel.js',
    '.codeclimate.yml',
    'src/auth/local/index.js',
    'src/auth/local/passport.js',
    'src/auth/auth.service.js',
    'src/auth/index.js',
    'src/test/controllers/auth.js',
    'src/test/controllers/user.js',
    'src/test/models/user.js',
    'src/api/controllers/auth.js',
    'src/api/controllers/user.js'
  ]);
});
<commit_msg>tests<commit_after>'use strict';

const path = require('path');
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');
const test = require('ava');

test.before(() => {
  return helpers.run(path.join(__dirname, '../../generators/app'))
    .withPrompts({
      name: 'cool',
      author: 'super cool',
      description: 'cool descr',
      eslint: true,
      CI: ['Travis-CI', 'Appveyor'],
      docker: true,
      heroku: true,
      auth: true
    });
});

test('with auth', () => {
  assert.file([
    'src',
    '.editorconfig',
    '.eslintrc.js',
    'package.json',
    '.gitignore',
    '.travis.yml',
    'appveyor.yml',
    'README.md',
    'docker-compose.yml',
    'Dockerfile',
    'Procfile',
    'gulpfile.babel.js',
    '.codeclimate.yml',
    'mocha.conf.js',
    'src/auth/local/index.js',
    'src/auth/local/passport.js',
    'src/auth/auth.service.js',
    'src/auth/index.js',
    'src/test/controllers/auth.js',
    'src/test/controllers/user.js',
    'src/test/models/user.js',
    'src/api/controllers/auth.js',
    'src/api/controllers/user.js'
  ]);
});
<|endoftext|>