<commit_before>(function() {

    'use strict';

    /**
     * @ngdoc service
     * @name requisition.RequisitionService
     *
     * @description
     * Responsible for retriving all information from server.
     */
    angular
        .module('requisition')
        .service('RequisitionService', requisitionService);

    requisitionService.$inject = ['$q', '$resource', 'messageService', 'OpenlmisURL',
                                  'RequisitionURL', 'RequisitionFactory', 'Confirm',
                                  'Notification', 'DateUtils', 'localStorageFactory',
                                  'OfflineService'];

    function requisitionService($q, $resource, messageService, OpenlmisURL, RequisitionURL,
                                RequisitionFactory, Confirm, Notification, DateUtils,
                                localStorageFactory, OfflineService) {

        var offlineTemplates = localStorageFactory('requisitionTemplates'),
            offlineRequisitions = localStorageFactory('requisitions'),
            onlineOnlyRequisitions = localStorageFactory('onlineOnly'),
            offlineApprovedProducts = localStorageFactory('approvedProducts'),
            offlineStockAdjustmentReasons = localStorageFactory('stockAdjustmentReasons');

        var resource = $resource(RequisitionURL('/api/requisitions/:id'), {}, {
            'initiate': {
                url: RequisitionURL('/api/requisitions/initiate'),
                method: 'POST'
            },
            'search': {
                url: RequisitionURL('/api/requisitions/search'),
                method: 'GET',
                isArray: true,
                transformResponse: transformRequisitionListResponse
            },
            'forApproval': {
                url: RequisitionURL('/api/requisitions/requisitionsForApproval'),
                method: 'GET',
                isArray: true,
                transformResponse: transformRequisitionListResponse
            },
            'getTemplate': {
                url: RequisitionURL('/api/requisitionTemplates/:id'),
                method: 'GET'
            },
            'forConvert': {
                url: RequisitionURL('/api/requisitions/requisitionsForConvert'),
                method: 'GET',
                isArray: true,
                transformResponse: transformResponseForConvert
            },
            'convertToOrder': {
                url: RequisitionURL('/api/requisitions/convertToOrder'),
                method: 'POST',
                transformRequest: transformRequest
            },
            'getApprovedProducts': {
                url: OpenlmisURL('/api/facilities/:id/approvedProducts'),
                method: 'GET',
                isArray: true
            },
            'getStockAdjustmentReasonsByProgram': {
                url: OpenlmisURL('/api/stockAdjustmentReasons/search'),
                method: 'GET',
                isArray: true
            }
        });

        var service = {
            get: get,
            initiate: initiate,
            search: search,
            forApproval: forApproval,
            forConvert: forConvert,
            convertToOrder: convertToOrder
        };

        return service;

        /**
         * @ngdoc function
         * @name get
         * @methodOf requisition.RequisitionService
         * @param {String} id Requisition UUID
         * @return {Promise} requisition promise
         *
         * @description
         * Retrieves requisition by id.
         *
         */
        function get(id) {
            var deferred = $q.defer();

            if (OfflineService.isOffline()) {
                var requisition = offlineRequisitions.getBy('id', id),
                    template = offlineTemplates.getBy('id', requisition.template),
                    approvedProducts = offlineApprovedProducts.search({
                        requisitionId: id
                    }),
                    reasons = offlineStockAdjustmentReasons.search({
                        program: {
                            id: requisition.program.id
                        }
                    });

                resolve(requisition, template, approvedProducts, reasons);
            } else {
                var requisition = offlineRequisitions.search({
                    id: id,
                    $modified: true
                });
                if (!requisition || !requisition.length) {
                    var i = 0;
                    getRequisition(id).then(function(requisition) {
                        requisition.$availableOffline = !onlineOnlyRequisitions.contains(id);
                        $q.all([
                            getTemplate(requisition),
                            getApprovedProducts(requisition),
                            getStockAdjustmentReasons(requisition)
                        ]).then(function(responses) {
                            if (requisition.$availableOffline) {
                                storeResponses(requisition, responses[0], responses[1],
                                responses[2]);
                            }
                            resolve(requisition, responses[0], responses[1], responses[2]);
                        }, function() {
                            if (requisition.$availableOffline) {
                                offlineRequisitions.put(requisition);
                            }
                            resolve(requisition);
                        });
                    }, error);
                } else {
                    var template = offlineTemplates.getBy('id', requisition[0].template),
                        approvedProducts = offlineApprovedProducts.search({
                            requisitionId: id
                        }),
                        reasons = offlineStockAdjustmentReasons.search({
                            program: requisition[0].program.id
                        });

                    resolve(requisition[0], template, approvedProducts, reasons);
                }
            }

            return deferred.promise;

            function resolve(requisition, template, approvedProducts, reasons) {
                deferred.resolve(RequisitionFactory(requisition, template, approvedProducts, reasons));
            }

            function error() {
                deferred.reject();
            }
        }

        /**
         * @ngdoc function
         * @name initiate
         * @methodOf requisition.RequisitionService
         * @param {String} facility Facility UUID
         * @param {String} program Program UUID
         * @param {String} suggestedPeriod Period UUID
         * @param {boolean} emergency Indicates if requisition is emergency or not
         * @return {Promise} requisition promise
         *
         * @description
         * Initates new requisition for program in facility with given period.
         *
         */
        function initiate(facility, program, suggestedPeriod, emergency) {
            return resource.initiate({
                facility: facility,
                program: program,
                suggestedPeriod: suggestedPeriod,
                emergency: emergency
            }, {}).$promise;
        }

        /**
         * @ngdoc function
         * @name search
         * @methodOf requisition.RequisitionService
         * @param {boolean} offline Indicates if searching in offline requisitions
         * @param {Object} searchParams Contains parameters for searching requisitions, i.e.
         * {
         *      program: 'programID',
         *      facility: 'facilityID',
         *      createdDateFrom: 'startDate',
         *      createdDateTo: 'endDate',
         *      requisitionStatus: ['status1', 'status2'],
         *      emergency: false
         * }
         *
         * @return {Array} Array of requisitions for given criteria (optional)
         *
         * @description
         * Search requisitons by criteria from parameters.
         *
         */
        function search(offline, searchParams) {
            var deferred = $q.defer();

            if(offline) {
                var requisitions = offlineRequisitions.search(searchParams, 'requisitionFilter');
                angular.forEach(requisitions, function(requisition) {
                    transformRequisition(requisition);
                    requisition.$searchedOffline = true;
                });
                deferred.resolve(requisitions);
            } else {
                resource.search(searchParams).$promise.then(function(requisitions) {
                    angular.forEach(requisitions, function(requisition) {
                        if(offlineRequisitions.getBy('id', requisition.id)) requisition.$availableOffline = true;
                    });
                    deferred.resolve(requisitions);
                }, function() {
                    deferred.reject();
                });
            }

            return deferred.promise;
        }

        /**
         * @ngdoc function
         * @name forApproval
         * @methodOf requisition.RequisitionService
         * @return {Array} Array of requisitions for approval
         *
         * @description
         * Retrieves all requisitions with authorized status for approve.
         *
         */
        function forApproval() {
            return resource.forApproval().$promise;
        }

        /**
         * @ngdoc function
         * @name forConvert
         * @methodOf requisition.RequisitionService
         * @param {Object} params Request params, contains i.e.: filertBy, filterValue, sortBy, descending
         * @return {Array} Array of requisitions for convert
         *
         * @description
         * Search requisitons for convert to order by given criteria.
         *
         */
        function forConvert(params) {
            return resource.forConvert(params).$promise;
        }

        /**
         * @ngdoc function
         * @name convertToOrder
         * @methodOf requisition.RequisitionService
         * @param {Array} requisitions Array of requisitions to convert
         *
         * @description
         * Converts given requisitions into orders.
         *
         */
        function convertToOrder(requisitions) {
            var deferred = $q.defer();

            Confirm('msg.question.confirmation').then(function() {
                resource.convertToOrder(requisitions).$promise.then(function() {
                    deferred.resolve();
                    Notification.success('msg.rnr.converted.to.order');
                }, function() {
                    deferred.reject();
                    Notification.error('msg.error.occurred');
                });
            }, function() {
                deferred.reject();
            });

            return deferred.promise;
        }

        function getRequisition(id) {
            return resource.get({
                id: id
            }).$promise;
        }

        function getOfflineRequisition(id) {
            return offlineRequisitions.getBy('id', id);
        }

        function getTemplate(requisition) {
            return resource.getTemplate({
                id: requisition.template
            }).$promise;
        }

        function getApprovedProducts(requisition) {
            return resource.getApprovedProducts({
                id: requisition.facility.id,
                fullSupply: false,
                programId: requisition.program.id
            }).$promise;
        }

        function getStockAdjustmentReasons(requisition) {
            return resource.getStockAdjustmentReasonsByProgram({
                program: requisition.program.id
            }).$promise;
        }

        function storeResponses(requisition, template, approvedProducts, reasons) {
            requisition.$modified = false;
            offlineRequisitions.put(requisition);
            offlineTemplates.put(template);

            var approvedProductsOffline = localStorageFactory('approvedProducts');
            approvedProducts.forEach(function(product) {
                product.requisitionId = requisition.id;
                approvedProductsOffline.put(product);
            });

            var reasonsOffline = localStorageFactory('stockAdjustmentReasons');
            reasons.forEach(function(reason) {
                reasonsOffline.put(reason);
            });
        }

        function transformRequest(requisitionsWithDepots) {
            var body = [];
            angular.forEach(requisitionsWithDepots, function(requisitionWithDepots) {
                body.push({
                    requisitionId: requisitionWithDepots.requisition.id,
                    supplyingDepotId: requisitionWithDepots.requisition.supplyingFacility
                });
            });
            return angular.toJson(body);
        }

        function transformRequisitionListResponse(data, headers, status) {
            return transformResponse(data, status, function(requisitions) {
                angular.forEach(requisitions, transformRequisition);
                return requisitions;
            });
        }

        function transformResponseForConvert(data, headers, status) {
            return transformResponse(data, status, function(items) {
                angular.forEach(items, function(item) {
                    transformRequisition(item.requisition);
                });
                return items;
            });
        }

        function transformResponse(data, status, transformer) {
            if (status === 200) {
                return transformer(angular.fromJson(data));
            }
            return data;
        }

        function transformRequisition(requisition) {
            requisition.createdDate = DateUtils.toDate(requisition.createdDate);
            requisition.processingPeriod.startDate = DateUtils.toDate(requisition.processingPeriod.startDate);
            requisition.processingPeriod.endDate = DateUtils.toDate(requisition.processingPeriod.endDate);
            requisition.processingPeriod.processingSchedule.modifiedDate = DateUtils.toDate(requisition.processingPeriod.processingSchedule.modifiedDate);
        }
    }
})();
<commit_msg>OLMIS-1470 FEOLMIS-760: Used declared local storage factory instead of creating new<commit_after>(function() {

    'use strict';

    /**
     * @ngdoc service
     * @name requisition.RequisitionService
     *
     * @description
     * Responsible for retriving all information from server.
     */
    angular
        .module('requisition')
        .service('RequisitionService', requisitionService);

    requisitionService.$inject = ['$q', '$resource', 'messageService', 'OpenlmisURL',
                                  'RequisitionURL', 'RequisitionFactory', 'Confirm',
                                  'Notification', 'DateUtils', 'localStorageFactory',
                                  'OfflineService'];

    function requisitionService($q, $resource, messageService, OpenlmisURL, RequisitionURL,
                                RequisitionFactory, Confirm, Notification, DateUtils,
                                localStorageFactory, OfflineService) {

        var offlineTemplates = localStorageFactory('requisitionTemplates'),
            offlineRequisitions = localStorageFactory('requisitions'),
            onlineOnlyRequisitions = localStorageFactory('onlineOnly'),
            offlineApprovedProducts = localStorageFactory('approvedProducts'),
            offlineStockAdjustmentReasons = localStorageFactory('stockAdjustmentReasons');

        var resource = $resource(RequisitionURL('/api/requisitions/:id'), {}, {
            'initiate': {
                url: RequisitionURL('/api/requisitions/initiate'),
                method: 'POST'
            },
            'search': {
                url: RequisitionURL('/api/requisitions/search'),
                method: 'GET',
                isArray: true,
                transformResponse: transformRequisitionListResponse
            },
            'forApproval': {
                url: RequisitionURL('/api/requisitions/requisitionsForApproval'),
                method: 'GET',
                isArray: true,
                transformResponse: transformRequisitionListResponse
            },
            'getTemplate': {
                url: RequisitionURL('/api/requisitionTemplates/:id'),
                method: 'GET'
            },
            'forConvert': {
                url: RequisitionURL('/api/requisitions/requisitionsForConvert'),
                method: 'GET',
                isArray: true,
                transformResponse: transformResponseForConvert
            },
            'convertToOrder': {
                url: RequisitionURL('/api/requisitions/convertToOrder'),
                method: 'POST',
                transformRequest: transformRequest
            },
            'getApprovedProducts': {
                url: OpenlmisURL('/api/facilities/:id/approvedProducts'),
                method: 'GET',
                isArray: true
            },
            'getStockAdjustmentReasonsByProgram': {
                url: OpenlmisURL('/api/stockAdjustmentReasons/search'),
                method: 'GET',
                isArray: true
            }
        });

        var service = {
            get: get,
            initiate: initiate,
            search: search,
            forApproval: forApproval,
            forConvert: forConvert,
            convertToOrder: convertToOrder
        };

        return service;

        /**
         * @ngdoc function
         * @name get
         * @methodOf requisition.RequisitionService
         * @param {String} id Requisition UUID
         * @return {Promise} requisition promise
         *
         * @description
         * Retrieves requisition by id.
         *
         */
        function get(id) {
            var deferred = $q.defer();

            if (OfflineService.isOffline()) {
                var requisition = offlineRequisitions.getBy('id', id),
                    template = offlineTemplates.getBy('id', requisition.template),
                    approvedProducts = offlineApprovedProducts.search({
                        requisitionId: id
                    }),
                    reasons = offlineStockAdjustmentReasons.search({
                        program: {
                            id: requisition.program.id
                        }
                    });

                resolve(requisition, template, approvedProducts, reasons);
            } else {
                var requisition = offlineRequisitions.search({
                    id: id,
                    $modified: true
                });
                if (!requisition || !requisition.length) {
                    var i = 0;
                    getRequisition(id).then(function(requisition) {
                        requisition.$availableOffline = !onlineOnlyRequisitions.contains(id);
                        $q.all([
                            getTemplate(requisition),
                            getApprovedProducts(requisition),
                            getStockAdjustmentReasons(requisition)
                        ]).then(function(responses) {
                            if (requisition.$availableOffline) {
                                storeResponses(requisition, responses[0], responses[1],
                                responses[2]);
                            }
                            resolve(requisition, responses[0], responses[1], responses[2]);
                        }, function() {
                            if (requisition.$availableOffline) {
                                offlineRequisitions.put(requisition);
                            }
                            resolve(requisition);
                        });
                    }, error);
                } else {
                    var template = offlineTemplates.getBy('id', requisition[0].template),
                        approvedProducts = offlineApprovedProducts.search({
                            requisitionId: id
                        }),
                        reasons = offlineStockAdjustmentReasons.search({
                            program: requisition[0].program.id
                        });

                    resolve(requisition[0], template, approvedProducts, reasons);
                }
            }

            return deferred.promise;

            function resolve(requisition, template, approvedProducts, reasons) {
                deferred.resolve(RequisitionFactory(requisition, template, approvedProducts, reasons));
            }

            function error() {
                deferred.reject();
            }
        }

        /**
         * @ngdoc function
         * @name initiate
         * @methodOf requisition.RequisitionService
         * @param {String} facility Facility UUID
         * @param {String} program Program UUID
         * @param {String} suggestedPeriod Period UUID
         * @param {boolean} emergency Indicates if requisition is emergency or not
         * @return {Promise} requisition promise
         *
         * @description
         * Initates new requisition for program in facility with given period.
         *
         */
        function initiate(facility, program, suggestedPeriod, emergency) {
            return resource.initiate({
                facility: facility,
                program: program,
                suggestedPeriod: suggestedPeriod,
                emergency: emergency
            }, {}).$promise;
        }

        /**
         * @ngdoc function
         * @name search
         * @methodOf requisition.RequisitionService
         * @param {boolean} offline Indicates if searching in offline requisitions
         * @param {Object} searchParams Contains parameters for searching requisitions, i.e.
         * {
         *      program: 'programID',
         *      facility: 'facilityID',
         *      createdDateFrom: 'startDate',
         *      createdDateTo: 'endDate',
         *      requisitionStatus: ['status1', 'status2'],
         *      emergency: false
         * }
         *
         * @return {Array} Array of requisitions for given criteria (optional)
         *
         * @description
         * Search requisitons by criteria from parameters.
         *
         */
        function search(offline, searchParams) {
            var deferred = $q.defer();

            if(offline) {
                var requisitions = offlineRequisitions.search(searchParams, 'requisitionFilter');
                angular.forEach(requisitions, function(requisition) {
                    transformRequisition(requisition);
                    requisition.$searchedOffline = true;
                });
                deferred.resolve(requisitions);
            } else {
                resource.search(searchParams).$promise.then(function(requisitions) {
                    angular.forEach(requisitions, function(requisition) {
                        if(offlineRequisitions.getBy('id', requisition.id)) requisition.$availableOffline = true;
                    });
                    deferred.resolve(requisitions);
                }, function() {
                    deferred.reject();
                });
            }

            return deferred.promise;
        }

        /**
         * @ngdoc function
         * @name forApproval
         * @methodOf requisition.RequisitionService
         * @return {Array} Array of requisitions for approval
         *
         * @description
         * Retrieves all requisitions with authorized status for approve.
         *
         */
        function forApproval() {
            return resource.forApproval().$promise;
        }

        /**
         * @ngdoc function
         * @name forConvert
         * @methodOf requisition.RequisitionService
         * @param {Object} params Request params, contains i.e.: filertBy, filterValue, sortBy, descending
         * @return {Array} Array of requisitions for convert
         *
         * @description
         * Search requisitons for convert to order by given criteria.
         *
         */
        function forConvert(params) {
            return resource.forConvert(params).$promise;
        }

        /**
         * @ngdoc function
         * @name convertToOrder
         * @methodOf requisition.RequisitionService
         * @param {Array} requisitions Array of requisitions to convert
         *
         * @description
         * Converts given requisitions into orders.
         *
         */
        function convertToOrder(requisitions) {
            var deferred = $q.defer();

            Confirm('msg.question.confirmation').then(function() {
                resource.convertToOrder(requisitions).$promise.then(function() {
                    deferred.resolve();
                    Notification.success('msg.rnr.converted.to.order');
                }, function() {
                    deferred.reject();
                    Notification.error('msg.error.occurred');
                });
            }, function() {
                deferred.reject();
            });

            return deferred.promise;
        }

        function getRequisition(id) {
            return resource.get({
                id: id
            }).$promise;
        }

        function getOfflineRequisition(id) {
            return offlineRequisitions.getBy('id', id);
        }

        function getTemplate(requisition) {
            return resource.getTemplate({
                id: requisition.template
            }).$promise;
        }

        function getApprovedProducts(requisition) {
            return resource.getApprovedProducts({
                id: requisition.facility.id,
                fullSupply: false,
                programId: requisition.program.id
            }).$promise;
        }

        function getStockAdjustmentReasons(requisition) {
            return resource.getStockAdjustmentReasonsByProgram({
                program: requisition.program.id
            }).$promise;
        }

        function storeResponses(requisition, template, approvedProducts, reasons) {
            requisition.$modified = false;
            offlineRequisitions.put(requisition);
            offlineTemplates.put(template);

            approvedProducts.forEach(function(product) {
                product.requisitionId = requisition.id;
                offlineApprovedProducts.put(product);
            });

            reasons.forEach(function(reason) {
                offlineStockAdjustmentReasons.put(reason);
            });
        }

        function transformRequest(requisitionsWithDepots) {
            var body = [];
            angular.forEach(requisitionsWithDepots, function(requisitionWithDepots) {
                body.push({
                    requisitionId: requisitionWithDepots.requisition.id,
                    supplyingDepotId: requisitionWithDepots.requisition.supplyingFacility
                });
            });
            return angular.toJson(body);
        }

        function transformRequisitionListResponse(data, headers, status) {
            return transformResponse(data, status, function(requisitions) {
                angular.forEach(requisitions, transformRequisition);
                return requisitions;
            });
        }

        function transformResponseForConvert(data, headers, status) {
            return transformResponse(data, status, function(items) {
                angular.forEach(items, function(item) {
                    transformRequisition(item.requisition);
                });
                return items;
            });
        }

        function transformResponse(data, status, transformer) {
            if (status === 200) {
                return transformer(angular.fromJson(data));
            }
            return data;
        }

        function transformRequisition(requisition) {
            requisition.createdDate = DateUtils.toDate(requisition.createdDate);
            requisition.processingPeriod.startDate = DateUtils.toDate(requisition.processingPeriod.startDate);
            requisition.processingPeriod.endDate = DateUtils.toDate(requisition.processingPeriod.endDate);
            requisition.processingPeriod.processingSchedule.modifiedDate = DateUtils.toDate(requisition.processingPeriod.processingSchedule.modifiedDate);
        }
    }
})();
<|endoftext|>


<commit_before>var d3 = require('d3');
var Labelizer = require('./labelizer.js');

var WIDTH = 1000;
var HEIGHT = 500;
var X_ORIG = 100;
var Y_ORIG = 20;
var PADDING = 20;
var CELL_W = 250;
var CELL_H = 75;
var MULTI_OFFSET = 3;

function Cell(x, y, width, height) {
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
}

function Xdsm(graph, svgid, tooltip) {
  this.graph = graph;
  this.tooltip = tooltip;
  var container = d3.select(".xdsm");
  this.svg = container.append("svg")
                 .attr("width", WIDTH)
                 .attr("height", HEIGHT)
                 .attr("class", svgid);

  this.grid = [];
  this.nodes = [];
  this.edges = [];
}

Xdsm.prototype.draw = function() {
  var self = this;

  if (self.graph.refname) {
    var ref = self.svg.append('g').classed('title', true);

    ref.append("text").text(self.graph.refname);
    var bbox = ref.nodes()[0].getBBox();
    ref.insert("rect", "text")
        .attr('x', bbox.x)
        .attr('y', bbox.y)
        .attr('width', bbox.width)
        .attr('height', bbox.height);

    ref.attr('transform',
             'translate(' + X_ORIG + ',' + (Y_ORIG + bbox.height) + ')');
  }

  self.nodes = self._createTextGroup("node");
  self.edges = self._createTextGroup("edge");

  // Workflow
  self._createWorkflow();

  // Layout texts
  self._layoutText(self.nodes);
  self._layoutText(self.edges);

  // Rectangles for nodes
  self.nodes.each(function(d, i) {
    var that = d3.select(this);
    that.call(self._customRect.bind(self), d, i, 0);
    if (d.isMulti) {
      that.call(self._customRect.bind(self), d, i, 1 * Number(MULTI_OFFSET));
      that.call(self._customRect.bind(self), d, i, 2 * Number(MULTI_OFFSET));
    }
  });

  // Trapezium for edges
  self.edges.each(function(d, i) {
    var that = d3.select(this);
    that.call(self._customTrapz.bind(self), d, i, 0);
    if (d.isMulti) {
      that.call(self._customTrapz.bind(self), d, i, 1 * Number(MULTI_OFFSET));
      that.call(self._customTrapz.bind(self), d, i, 2 * Number(MULTI_OFFSET));
    }
  });

  // Dataflow
  self._createDataflow(self.edges);

  // set svg size
  var w = CELL_W * (self.graph.nodes.length + 1);
  var h = CELL_H * (self.graph.nodes.length + 1);
  self.svg.attr("width", w).attr("height", h);

  var bordercolor = 'black';
  self.svg.append("rect")
            .classed("border", true)
            .attr("x", 4)
            .attr("y", 4)
            .attr("height", h - 4)
            .attr("width", w - 4)
            .style("stroke", bordercolor)
            .style("fill", "none")
            .style("stroke-width", 0);
};

Xdsm.prototype._createTextGroup = function(kind) {
  var self = this;

  var group = self.svg.append('g').attr("class", kind + "s");

  var textGroups =
    group.selectAll("." + kind)
      .data(this.graph[kind + "s"])
    .enter()
      .append("g").attr("class", function(d) {
        var klass = kind === "node" ? d.type : "dataInter";
        if (klass === "dataInter" && d.isIO()) {
          klass = "dataIO";
        }
        return d.id + " " + kind + " " + klass;
      }).each(function() {
        var labelize = Labelizer.labelize().ellipsis(5);
        d3.select(this).call(labelize);
      });

  d3.selectAll(".ellipsized").on("mouseover", function(d) {
    self.tooltip.transition().duration(200).style("opacity", 0.9);
    var tooltipize = Labelizer.tooltipize().text(d.name);
    self.tooltip.call(tooltipize)
      .style("width", "200px")
      .style("left", (d3.event.pageX) + "px")
      .style("top", (d3.event.pageY - 28) + "px");
  }).on("mouseout", function() {
    self.tooltip.transition().duration(500).style("opacity", 0);
  });

  return textGroups;
};

Xdsm.prototype._createWorkflow = function() {
  //  console.log(JSON.stringify(this.graph.chains));
  var workflow = this.svg.insert("g", ":first-child")
                    .attr("class", "workflow");

  workflow.selectAll("g")
    .data(this.graph.chains)
  .enter()
    .insert('g').attr("class", "workflow-chain")
    .selectAll('polyline')
      .data(function(d) { return d; })  // eslint-disable-line brace-style
    .enter()
      .append("polyline")
        .attr("class", function(d) {
          return "link_" + d[0] + "_" + d[1];
        })
        .attr("points", function(d) {
          var w = CELL_W * Math.abs(d[0] - d[1]);
          var h = CELL_H * Math.abs(d[0] - d[1]);
          var points = [];
          if (d[0] < d[1]) {
            if (d[0] !== 0) {
              points.push((-w) + ",0");
            }
            points.push("0,0");
            if (d[1] !== 0) {
              points.push("0," + h);
            }
          } else {
            if (d[0] !== 0) {
              points.push(w + ",0");
            }
            points.push("0,0");
            if (d[1] !== 0) {
              points.push("0," + (-h));
            }
          }
          return points.join(" ");
        })
      .attr("transform", function(d) {
        var max = Math.max(d[0], d[1]);
        var min = Math.min(d[0], d[1]);
        var w;
        var h;
        if (d[0] < d[1]) {
          w = CELL_W * max + X_ORIG;
          h = CELL_H * min + Y_ORIG;
        } else {
          w = CELL_W * min + X_ORIG;
          h = CELL_H * max + Y_ORIG;
        }
        return "translate(" + (X_ORIG + w) + "," + (Y_ORIG + h) + ")";
      });
};

Xdsm.prototype._createDataflow = function(edges) {
  var dataflow = this.svg.insert("g", ":first-child")
                   .attr("class", "dataflow");

  edges.each(function(d, i) {
    dataflow.insert("polyline", ":first-child")
      .attr("points", function() {
        var w = CELL_W * Math.abs(d.col - d.row);
        var h = CELL_H * Math.abs(d.col - d.row);
        var points = [];
        if (d.iotype === "in") {
          if (!d.io.fromU) {
            points.push((-w) + ",0");
          }
          points.push("0,0");
          if (!d.io.toU) {
            points.push("0," + h);
          }
        } else {
          if (!d.io.fromU) {
            points.push(w + ",0");
          }
          points.push("0,0");
          if (!d.io.toU) {
            points.push("0," + (-h));
          }
        }
        return points.join(" ");
      }).attr("transform", function() {
        var m = (d.col === undefined) ? i : d.col;
        var n = (d.row === undefined) ? i : d.row;
        var w = CELL_W * m + X_ORIG;
        var h = CELL_H * n + Y_ORIG;
        return "translate(" + (X_ORIG + w) + "," + (Y_ORIG + h) + ")";
      });
  });
};

Xdsm.prototype._layoutText = function(items) {
  var grid = this.grid;
  items.each(function(d, i) {
    var item = d3.select(this);
    if (grid[i] === undefined) {
      grid[i] = new Array(items.length);
    }
    item.select("text").each(function(d, j) {
      var that = d3.select(this);
      var data = item.data()[0];
      var m = (data.row === undefined) ? i : data.row;
      var n = (data.col === undefined) ? i : data.col;
      var bbox = that.nodes()[j].getBBox();
      grid[m][n] = new Cell(-bbox.width / 2, 0, bbox.width, bbox.height);
      that.attr("x", function() {
        return grid[m][n].x;
      }).attr("y", function() {
        return grid[m][n].y;
      }).attr("width", function() {
        return grid[m][n].width;
      }).attr("height", function() {
        return grid[m][n].height;
      });
    });
  });

  items.attr("transform", function(d, i) {
    var m = (d.col === undefined) ? i : d.col;
    var n = (d.row === undefined) ? i : d.row;
    var w = CELL_W * m + X_ORIG;
    var h = CELL_H * n + Y_ORIG;
    return "translate(" + (X_ORIG + w) + "," + (Y_ORIG + h) + ")";
  });
};

Xdsm.prototype._customRect = function(node, d, i, offset) {
  var grid = this.grid;
  node.insert("rect", ":first-child").attr("x", function() {
    return grid[i][i].x + offset - PADDING;
  }).attr("y", function() {
    return -grid[i][i].height * 2 / 3 - PADDING - offset;
  }).attr("width", function() {
    return grid[i][i].width + (PADDING * 2);
  }).attr("height", function() {
    return grid[i][i].height + (PADDING * 2);
  }).attr("rx", function() {
    var rounded = d.type === 'optimization' ||
                  d.type === 'mda' ||
                  d.type === 'doe';
    return rounded ? (grid[i][i].height + (PADDING * 2)) / 2 : 0;
  }).attr("ry", function() {
    var rounded = d.type === 'optimization' ||
                  d.type === 'mda' ||
                  d.type === 'doe';
    return rounded ? (grid[i][i].height + (PADDING * 2)) / 2 : 0;
  });
};

Xdsm.prototype._customTrapz = function(edge, d, i, offset) {
  var grid = this.grid;
  edge.insert("polygon", ":first-child").attr("points", function(d) {
    var pad = 5;
    var w = grid[d.row][d.col].width;
    var h = grid[d.row][d.col].height;
    var topleft = (-pad - w / 2 + offset) + ", " +
                  (-pad - h * 2 / 3 - offset);
    var topright = (w / 2 + pad + offset + 5) + ", " +
                   (-pad - h * 2 / 3 - offset);
    var botright = (w / 2 + pad + offset - 5 + 5) + ", " +
                   (pad + h / 3 - offset);
    var botleft = (-pad - w / 2 + offset - 5) + ", " +
                  (pad + h / 3 - offset);
    var tpz = [topleft, topright, botright, botleft].join(" ");
    return tpz;
  });
};

module.exports = Xdsm;
<commit_msg>refactor<commit_after>var d3 = require('d3');
var Labelizer = require('./labelizer.js');

var WIDTH = 1000;
var HEIGHT = 500;
var X_ORIG = 100;
var Y_ORIG = 20;
var PADDING = 20;
var CELL_W = 250;
var CELL_H = 75;
var MULTI_OFFSET = 3;

function Cell(x, y, width, height) {
  this.x = x;
  this.y = y;
  this.width = width;
  this.height = height;
}

function Xdsm(graph, svgid, tooltip) {
  this.graph = graph;
  this.tooltip = tooltip;
  var container = d3.select(".xdsm");
  this.svg = container.append("svg")
                 .attr("width", WIDTH)
                 .attr("height", HEIGHT)
                 .attr("class", svgid);

  this.grid = [];
  this.nodes = [];
  this.edges = [];
}

Xdsm.prototype.draw = function() {
  var self = this;

  if (self.graph.refname) {
    self._addTitle();
  }

  self.nodes = self._createTextGroup("node");
  self.edges = self._createTextGroup("edge");

  // Workflow
  self._createWorkflow();

  // Layout texts
  self._layoutText(self.nodes);
  self._layoutText(self.edges);

  // Rectangles for nodes
  self.nodes.each(function(d, i) {
    var that = d3.select(this);
    that.call(self._customRect.bind(self), d, i, 0);
    if (d.isMulti) {
      that.call(self._customRect.bind(self), d, i, 1 * Number(MULTI_OFFSET));
      that.call(self._customRect.bind(self), d, i, 2 * Number(MULTI_OFFSET));
    }
  });

  // Trapezium for edges
  self.edges.each(function(d, i) {
    var that = d3.select(this);
    that.call(self._customTrapz.bind(self), d, i, 0);
    if (d.isMulti) {
      that.call(self._customTrapz.bind(self), d, i, 1 * Number(MULTI_OFFSET));
      that.call(self._customTrapz.bind(self), d, i, 2 * Number(MULTI_OFFSET));
    }
  });

  // Dataflow
  self._createDataflow(self.edges);

  // set svg size
  var w = CELL_W * (self.graph.nodes.length + 1);
  var h = CELL_H * (self.graph.nodes.length + 1);
  self.svg.attr("width", w).attr("height", h);

  var bordercolor = 'black';
  self.svg.append("rect")
            .classed("border", true)
            .attr("x", 4)
            .attr("y", 4)
            .attr("height", h - 4)
            .attr("width", w - 4)
            .style("stroke", bordercolor)
            .style("fill", "none")
            .style("stroke-width", 0);
};

Xdsm.prototype._createTextGroup = function(kind) {
  var self = this;

  var group = self.svg.append('g').attr("class", kind + "s");

  var textGroups =
    group.selectAll("." + kind)
      .data(this.graph[kind + "s"])
    .enter()
      .append("g").attr("class", function(d) {
        var klass = kind === "node" ? d.type : "dataInter";
        if (klass === "dataInter" && d.isIO()) {
          klass = "dataIO";
        }
        return d.id + " " + kind + " " + klass;
      }).each(function() {
        var labelize = Labelizer.labelize().ellipsis(5);
        d3.select(this).call(labelize);
      });

  d3.selectAll(".ellipsized").on("mouseover", function(d) {
    self.tooltip.transition().duration(200).style("opacity", 0.9);
    var tooltipize = Labelizer.tooltipize().text(d.name);
    self.tooltip.call(tooltipize)
      .style("width", "200px")
      .style("left", (d3.event.pageX) + "px")
      .style("top", (d3.event.pageY - 28) + "px");
  }).on("mouseout", function() {
    self.tooltip.transition().duration(500).style("opacity", 0);
  });

  return textGroups;
};

Xdsm.prototype._createWorkflow = function() {
  //  console.log(JSON.stringify(this.graph.chains));
  var workflow = this.svg.insert("g", ":first-child")
                    .attr("class", "workflow");

  workflow.selectAll("g")
    .data(this.graph.chains)
  .enter()
    .insert('g').attr("class", "workflow-chain")
    .selectAll('polyline')
      .data(function(d) { return d; })  // eslint-disable-line brace-style
    .enter()
      .append("polyline")
        .attr("class", function(d) {
          return "link_" + d[0] + "_" + d[1];
        })
        .attr("points", function(d) {
          var w = CELL_W * Math.abs(d[0] - d[1]);
          var h = CELL_H * Math.abs(d[0] - d[1]);
          var points = [];
          if (d[0] < d[1]) {
            if (d[0] !== 0) {
              points.push((-w) + ",0");
            }
            points.push("0,0");
            if (d[1] !== 0) {
              points.push("0," + h);
            }
          } else {
            if (d[0] !== 0) {
              points.push(w + ",0");
            }
            points.push("0,0");
            if (d[1] !== 0) {
              points.push("0," + (-h));
            }
          }
          return points.join(" ");
        })
      .attr("transform", function(d) {
        var max = Math.max(d[0], d[1]);
        var min = Math.min(d[0], d[1]);
        var w;
        var h;
        if (d[0] < d[1]) {
          w = CELL_W * max + X_ORIG;
          h = CELL_H * min + Y_ORIG;
        } else {
          w = CELL_W * min + X_ORIG;
          h = CELL_H * max + Y_ORIG;
        }
        return "translate(" + (X_ORIG + w) + "," + (Y_ORIG + h) + ")";
      });
};

Xdsm.prototype._createDataflow = function(edges) {
  var dataflow = this.svg.insert("g", ":first-child")
                   .attr("class", "dataflow");

  edges.each(function(d, i) {
    dataflow.insert("polyline", ":first-child")
      .attr("points", function() {
        var w = CELL_W * Math.abs(d.col - d.row);
        var h = CELL_H * Math.abs(d.col - d.row);
        var points = [];
        if (d.iotype === "in") {
          if (!d.io.fromU) {
            points.push((-w) + ",0");
          }
          points.push("0,0");
          if (!d.io.toU) {
            points.push("0," + h);
          }
        } else {
          if (!d.io.fromU) {
            points.push(w + ",0");
          }
          points.push("0,0");
          if (!d.io.toU) {
            points.push("0," + (-h));
          }
        }
        return points.join(" ");
      }).attr("transform", function() {
        var m = (d.col === undefined) ? i : d.col;
        var n = (d.row === undefined) ? i : d.row;
        var w = CELL_W * m + X_ORIG;
        var h = CELL_H * n + Y_ORIG;
        return "translate(" + (X_ORIG + w) + "," + (Y_ORIG + h) + ")";
      });
  });
};

Xdsm.prototype._layoutText = function(items) {
  var grid = this.grid;
  items.each(function(d, i) {
    var item = d3.select(this);
    if (grid[i] === undefined) {
      grid[i] = new Array(items.length);
    }
    item.select("text").each(function(d, j) {
      var that = d3.select(this);
      var data = item.data()[0];
      var m = (data.row === undefined) ? i : data.row;
      var n = (data.col === undefined) ? i : data.col;
      var bbox = that.nodes()[j].getBBox();
      grid[m][n] = new Cell(-bbox.width / 2, 0, bbox.width, bbox.height);
      that.attr("x", function() {
        return grid[m][n].x;
      }).attr("y", function() {
        return grid[m][n].y;
      }).attr("width", function() {
        return grid[m][n].width;
      }).attr("height", function() {
        return grid[m][n].height;
      });
    });
  });

  items.attr("transform", function(d, i) {
    var m = (d.col === undefined) ? i : d.col;
    var n = (d.row === undefined) ? i : d.row;
    var w = CELL_W * m + X_ORIG;
    var h = CELL_H * n + Y_ORIG;
    return "translate(" + (X_ORIG + w) + "," + (Y_ORIG + h) + ")";
  });
};

Xdsm.prototype._customRect = function(node, d, i, offset) {
  var grid = this.grid;
  node.insert("rect", ":first-child").attr("x", function() {
    return grid[i][i].x + offset - PADDING;
  }).attr("y", function() {
    return -grid[i][i].height * 2 / 3 - PADDING - offset;
  }).attr("width", function() {
    return grid[i][i].width + (PADDING * 2);
  }).attr("height", function() {
    return grid[i][i].height + (PADDING * 2);
  }).attr("rx", function() {
    var rounded = d.type === 'optimization' ||
                  d.type === 'mda' ||
                  d.type === 'doe';
    return rounded ? (grid[i][i].height + (PADDING * 2)) / 2 : 0;
  }).attr("ry", function() {
    var rounded = d.type === 'optimization' ||
                  d.type === 'mda' ||
                  d.type === 'doe';
    return rounded ? (grid[i][i].height + (PADDING * 2)) / 2 : 0;
  });
};

Xdsm.prototype._customTrapz = function(edge, d, i, offset) {
  var grid = this.grid;
  edge.insert("polygon", ":first-child").attr("points", function(d) {
    var pad = 5;
    var w = grid[d.row][d.col].width;
    var h = grid[d.row][d.col].height;
    var topleft = (-pad - w / 2 + offset) + ", " +
                  (-pad - h * 2 / 3 - offset);
    var topright = (w / 2 + pad + offset + 5) + ", " +
                   (-pad - h * 2 / 3 - offset);
    var botright = (w / 2 + pad + offset - 5 + 5) + ", " +
                   (pad + h / 3 - offset);
    var botleft = (-pad - w / 2 + offset - 5) + ", " +
                  (pad + h / 3 - offset);
    var tpz = [topleft, topright, botright, botleft].join(" ");
    return tpz;
  });
};

Xdsm.prototype._addTitle = function() {
  var ref = self.svg.append('g').classed('title', true);

  ref.append("text").text(self.graph.refname);
  var bbox = ref.nodes()[0].getBBox();
  ref.insert("rect", "text")
      .attr('x', bbox.x)
      .attr('y', bbox.y)
      .attr('width', bbox.width)
      .attr('height', bbox.height);

  ref.attr('transform',
           'translate(' + X_ORIG + ',' + (Y_ORIG + bbox.height) + ')');
}
module.exports = Xdsm;
<|endoftext|>


<commit_before>(function() {

    'use strict';

    /**
     * @ngdoc service
     * @name requisition.requisitionService
     *
     * @description
     * Responsible for retriving all information from server.
     */
    angular
        .module('requisition')
        .service('requisitionService', service);

    service.$inject = [
        '$q', '$resource', 'messageService', 'openlmisUrlFactory', 'requisitionUrlFactory',
        'Requisition', 'confirmService', 'notificationService', 'dateUtils',
        'localStorageFactory', 'offlineService'
    ];

    function service($q, $resource, messageService, openlmisUrlFactory, requisitionUrlFactory,
                                Requisition, confirmService, notificationService, dateUtils,
                                localStorageFactory, offlineService) {

        var offlineRequisitions = localStorageFactory('requisitions'),
            onlineOnlyRequisitions = localStorageFactory('onlineOnly'),
            offlineStockAdjustmentReasons = localStorageFactory('stockAdjustmentReasons'),
            offlineStatusMessages = localStorageFactory('statusMessages');

        var resource = $resource(requisitionUrlFactory('/api/requisitions/:id'), {}, {
            'get': {
                method: 'GET',
                transformResponse: transformGetResponse
            },
            'initiate': {
                url: requisitionUrlFactory('/api/requisitions/initiate'),
                method: 'POST'
            },
            'search': {
                url: requisitionUrlFactory('/api/requisitions/search'),
                method: 'GET',
                isArray: true,
                transformResponse: transformRequisitionSearchResponse
            },
            'forApproval': {
                url: requisitionUrlFactory('/api/requisitions/requisitionsForApproval'),
                method: 'GET',
                isArray: true,
                transformResponse: transformRequisitionListResponse
            },
            'forConvert': {
                url: requisitionUrlFactory('/api/requisitions/requisitionsForConvert'),
                method: 'GET',
                transformResponse: transformResponseForConvert
            },
            'convertToOrder': {
                url: requisitionUrlFactory('/api/requisitions/convertToOrder'),
                method: 'POST',
                transformRequest: transformRequest
            },
            'getStockAdjustmentReasonsByProgram': {
                url: openlmisUrlFactory('/api/stockAdjustmentReasons/search'),
                method: 'GET',
                isArray: true
            },
            'getStatusMessages': {
                url: requisitionUrlFactory('/api/requisitions/:id/statusMessages'),
                method: 'GET',
                isArray: true
            }
        });

        var service = {
            get: get,
            initiate: initiate,
            search: search,
            forApproval: forApproval,
            forConvert: forConvert,
            convertToOrder: convertToOrder
        };

        return service;

        /**
         * @ngdoc function
         * @name get
         * @methodOf requisition.requisitionService
         * @param {String} id Requisition UUID
         * @return {Promise} requisition promise
         *
         * @description
         * Retrieves requisition by id.
         *
         */
        function get(id) {
            var deferred = $q.defer();

            if (offlineService.isOffline()) {
                var requisition = offlineRequisitions.getBy('id', id),
                    reasons = offlineStockAdjustmentReasons.search({
                        program: {
                            id: requisition.program.id
                        }
                    }),
                    statusMessages = offlineStatusMessages.search({
                        requisitionId: requisition.id
                    });

                resolve(requisition, reasons, statusMessages);
            } else {
                var requisition = offlineRequisitions.search({
                    id: id,
                    $modified: true
                });
                if (!requisition || !requisition.length) {
                    var i = 0;
                    getRequisition(id).then(function(requisition) {
                        requisition.$availableOffline = !onlineOnlyRequisitions.contains(id);
                        $q.all([
                            getStockAdjustmentReasons(requisition),
                            getStatusMessages(requisition)
                        ]).then(function(responses) {
                            if (requisition.$availableOffline) {
                                storeResponses(requisition, responses[0], responses[1]);
                            }
                            resolve(requisition, responses[0], responses[1]);
                        }, function() {
                            if (requisition.$availableOffline) {
                                offlineRequisitions.put(requisition);
                            }
                            resolve(requisition);
                        });
                    }, error);
                } else {
                    var reasons = offlineStockAdjustmentReasons.search({
                            program: requisition[0].program.id
                        }),
                        statusMessages = offlineStatusMessages.search({
                            requisitionId: requisition[0].id
                        });

                    resolve(requisition[0], reasons, statusMessages);
                }
            }

            return deferred.promise;

            function resolve(requisition, reasons, statusMessages) {
                deferred.resolve(new Requisition(requisition, reasons, statusMessages));
            }

            function error() {
                deferred.reject();
            }
        }

        /**
         * @ngdoc function
         * @name initiate
         * @methodOf requisition.requisitionService
         * @param {String} facility Facility UUID
         * @param {String} program Program UUID
         * @param {String} suggestedPeriod Period UUID
         * @param {boolean} emergency Indicates if requisition is emergency or not
         * @return {Promise} requisition promise
         *
         * @description
         * Initates new requisition for program in facility with given period.
         *
         */
        function initiate(facility, program, suggestedPeriod, emergency) {
            return resource.initiate({
                facility: facility,
                program: program,
                suggestedPeriod: suggestedPeriod,
                emergency: emergency
            }, {}).$promise;
        }

        /**
         * @ngdoc function
         * @name search
         * @methodOf requisition.requisitionService
         * @param {boolean} offline Indicates if searching in offline requisitions
         * @param {Object} searchParams Contains parameters for searching requisitions, i.e.
         * {
         *      program: 'programID',
         *      facility: 'facilityID',
         *      createdDateFrom: 'startDate',
         *      createdDateTo: 'endDate',
         *      requisitionStatus: ['status1', 'status2'],
         *      emergency: false
         * }
         *
         * @return {Array} Array of requisitions for given criteria (optional)
         *
         * @description
         * Search requisitons by criteria from parameters.
         *
         */
        function search(offline, searchParams) {
            var deferred = $q.defer();

            if(offline) {
                var requisitions = offlineRequisitions.search(searchParams, 'requisitionSearch');
                angular.forEach(requisitions, function(requisition) {
                    transformRequisition(requisition);
                    requisition.$searchedOffline = true;
                });
                deferred.resolve(requisitions);
            } else {
                resource.search(searchParams).$promise.then(function(requisitions) {
                    angular.forEach(requisitions, function(requisition) {
                        if(offlineRequisitions.getBy('id', requisition.id)) requisition.$availableOffline = true;
                    });
                    deferred.resolve(requisitions);
                }, function() {
                    deferred.reject();
                });
            }

            return deferred.promise;
        }

        /**
         * @ngdoc function
         * @name forApproval
         * @methodOf requisition.requisitionService
         * @return {Array} Array of requisitions for approval
         *
         * @description
         * Retrieves all requisitions with authorized status for approve.
         *
         */
        function forApproval() {
            return resource.forApproval().$promise;
        }

        /**
         * @ngdoc function
         * @name forConvert
         * @methodOf requisition.requisitionService
         * @param {Object} params Request params, contains i.e.: filertBy, filterValue, sortBy, descending
         * @return {Array} Array of requisitions for convert
         *
         * @description
         * Search requisitons for convert to order by given criteria.
         *
         */
        function forConvert(params) {
            return resource.forConvert(params).$promise;
        }

        /**
         * @ngdoc function
         * @name convertToOrder
         * @methodOf requisition.requisitionService
         * @param {Array} requisitions Array of requisitions to convert
         *
         * @description
         * Converts given requisitions into orders.
         *
         */
        function convertToOrder(requisitions) {
            var deferred = $q.defer();

            confirmService.confirm('msg.question.confirmation.convertToOrder').then(function() {
                resource.convertToOrder(requisitions).$promise.then(function() {
                    deferred.resolve();
                    notificationService.success('msg.rnr.converted.to.order');
                }, function() {
                    deferred.reject();
                    notificationService.error('msg.error.occurred');
                });
            }, function() {
                deferred.reject();
            });

            return deferred.promise;
        }

        function getRequisition(id) {
            return resource.get({
                id: id
            }).$promise;
        }

        function getOfflineRequisition(id) {
            return offlineRequisitions.getBy('id', id);
        }

        function getStockAdjustmentReasons(requisition) {
            return resource.getStockAdjustmentReasonsByProgram({
                program: requisition.program.id
            }).$promise;
        }

        function getStatusMessages(requisition) {
            return resource.getStatusMessages({
                id: requisition.id
            }).$promise;
        }

        function storeResponses(requisition, reasons, statusMessages) {
            requisition.$modified = false;
            offlineRequisitions.put(requisition);

            reasons.forEach(function(reason) {
                offlineStockAdjustmentReasons.put(reason);
            });

            statusMessages.forEach(function(statusMessage) {
                offlineStatusMessages.put(statusMessage);
            });
        }

        function transformRequest(requisitionsWithDepots) {
            var body = [];
            angular.forEach(requisitionsWithDepots, function(requisitionWithDepots) {
                body.push({
                    requisitionId: requisitionWithDepots.requisition.id,
                    supplyingDepotId: requisitionWithDepots.requisition.supplyingFacility
                });
            });
            return angular.toJson(body);
        }

        function transformGetResponse(data, headers, status) {
            return transformResponse(data, status, function(response) {
                if (response.processingPeriod.startDate) {
                    response.processingPeriod.startDate = dateUtils.toDate(response.processingPeriod.startDate);
                }
                if (response.processingPeriod.endDate) {
                    response.processingPeriod.endDate = dateUtils.toDate(response.processingPeriod.endDate);
                }
                return response;
            });
        }

        function transformRequisitionSearchResponse(data, headers, status) {
            return transformResponse(data, status, function(response) {
                angular.forEach(response.content, transformRequisition);
                return response.content;
            });
        }

        function transformRequisitionListResponse(data, headers, status) {
            return transformResponse(data, status, function(requisitions) {
                angular.forEach(requisitions, transformRequisition);
                return requisitions;
            });
        }

        function transformResponseForConvert(data, headers, status) {
            return transformResponse(data, status, function(response) {
                angular.forEach(response.content, function(item) {
                    transformRequisition(item.requisition);
                });
                return response;
            });
        }

        function transformResponse(data, status, transformer) {
            if (status === 200) {
                return transformer(angular.fromJson(data));
            }
            return data;
        }

        function transformRequisition(requisition) {
            requisition.createdDate = dateUtils.toDate(requisition.createdDate);
            requisition.processingPeriod.startDate = dateUtils.toDate(requisition.processingPeriod.startDate);
            requisition.processingPeriod.endDate = dateUtils.toDate(requisition.processingPeriod.endDate);
            requisition.processingPeriod.processingSchedule.modifiedDate = dateUtils.toDate(requisition.processingPeriod.processingSchedule.modifiedDate);
        }
    }
})();
<commit_msg>Fixed issue with disappearing reasons after page refresh<commit_after>(function() {

    'use strict';

    /**
     * @ngdoc service
     * @name requisition.requisitionService
     *
     * @description
     * Responsible for retriving all information from server.
     */
    angular
        .module('requisition')
        .service('requisitionService', service);

    service.$inject = [
        '$q', '$resource', 'messageService', 'openlmisUrlFactory', 'requisitionUrlFactory',
        'Requisition', 'confirmService', 'notificationService', 'dateUtils',
        'localStorageFactory', 'offlineService'
    ];

    function service($q, $resource, messageService, openlmisUrlFactory, requisitionUrlFactory,
                                Requisition, confirmService, notificationService, dateUtils,
                                localStorageFactory, offlineService) {

        var offlineRequisitions = localStorageFactory('requisitions'),
            onlineOnlyRequisitions = localStorageFactory('onlineOnly'),
            offlineStockAdjustmentReasons = localStorageFactory('stockAdjustmentReasons'),
            offlineStatusMessages = localStorageFactory('statusMessages');

        var resource = $resource(requisitionUrlFactory('/api/requisitions/:id'), {}, {
            'get': {
                method: 'GET',
                transformResponse: transformGetResponse
            },
            'initiate': {
                url: requisitionUrlFactory('/api/requisitions/initiate'),
                method: 'POST'
            },
            'search': {
                url: requisitionUrlFactory('/api/requisitions/search'),
                method: 'GET',
                isArray: true,
                transformResponse: transformRequisitionSearchResponse
            },
            'forApproval': {
                url: requisitionUrlFactory('/api/requisitions/requisitionsForApproval'),
                method: 'GET',
                isArray: true,
                transformResponse: transformRequisitionListResponse
            },
            'forConvert': {
                url: requisitionUrlFactory('/api/requisitions/requisitionsForConvert'),
                method: 'GET',
                transformResponse: transformResponseForConvert
            },
            'convertToOrder': {
                url: requisitionUrlFactory('/api/requisitions/convertToOrder'),
                method: 'POST',
                transformRequest: transformRequest
            },
            'getStockAdjustmentReasonsByProgram': {
                url: openlmisUrlFactory('/api/stockAdjustmentReasons/search'),
                method: 'GET',
                isArray: true
            },
            'getStatusMessages': {
                url: requisitionUrlFactory('/api/requisitions/:id/statusMessages'),
                method: 'GET',
                isArray: true
            }
        });

        var service = {
            get: get,
            initiate: initiate,
            search: search,
            forApproval: forApproval,
            forConvert: forConvert,
            convertToOrder: convertToOrder
        };

        return service;

        /**
         * @ngdoc function
         * @name get
         * @methodOf requisition.requisitionService
         * @param {String} id Requisition UUID
         * @return {Promise} requisition promise
         *
         * @description
         * Retrieves requisition by id.
         *
         */
        function get(id) {
            var deferred = $q.defer();

            if (offlineService.isOffline()) {
                var requisition = offlineRequisitions.getBy('id', id),
                    reasons = offlineStockAdjustmentReasons.search({
                        program: {
                            id: requisition.program.id
                        }
                    }),
                    statusMessages = offlineStatusMessages.search({
                        requisitionId: requisition.id
                    });

                resolve(requisition, reasons, statusMessages);
            } else {
                var requisition = offlineRequisitions.search({
                    id: id,
                    $modified: true
                });
                if (!requisition || !requisition.length) {
                    var i = 0;
                    getRequisition(id).then(function(requisition) {
                        requisition.$availableOffline = !onlineOnlyRequisitions.contains(id);
                        $q.all([
                            getStockAdjustmentReasons(requisition),
                            getStatusMessages(requisition)
                        ]).then(function(responses) {
                            if (requisition.$availableOffline) {
                                storeResponses(requisition, responses[0], responses[1]);
                            }
                            resolve(requisition, responses[0], responses[1]);
                        }, function() {
                            if (requisition.$availableOffline) {
                                offlineRequisitions.put(requisition);
                            }
                            resolve(requisition);
                        });
                    }, error);
                } else {
                    var reasons = offlineStockAdjustmentReasons.search({
                            program: {
                                id: requisition[0].program.id
                            }
                        }),
                        statusMessages = offlineStatusMessages.search({
                            requisitionId: requisition[0].id
                        });

                    resolve(requisition[0], reasons, statusMessages);
                }
            }

            return deferred.promise;

            function resolve(requisition, reasons, statusMessages) {
                deferred.resolve(new Requisition(requisition, reasons, statusMessages));
            }

            function error() {
                deferred.reject();
            }
        }

        /**
         * @ngdoc function
         * @name initiate
         * @methodOf requisition.requisitionService
         * @param {String} facility Facility UUID
         * @param {String} program Program UUID
         * @param {String} suggestedPeriod Period UUID
         * @param {boolean} emergency Indicates if requisition is emergency or not
         * @return {Promise} requisition promise
         *
         * @description
         * Initates new requisition for program in facility with given period.
         *
         */
        function initiate(facility, program, suggestedPeriod, emergency) {
            return resource.initiate({
                facility: facility,
                program: program,
                suggestedPeriod: suggestedPeriod,
                emergency: emergency
            }, {}).$promise;
        }

        /**
         * @ngdoc function
         * @name search
         * @methodOf requisition.requisitionService
         * @param {boolean} offline Indicates if searching in offline requisitions
         * @param {Object} searchParams Contains parameters for searching requisitions, i.e.
         * {
         *      program: 'programID',
         *      facility: 'facilityID',
         *      createdDateFrom: 'startDate',
         *      createdDateTo: 'endDate',
         *      requisitionStatus: ['status1', 'status2'],
         *      emergency: false
         * }
         *
         * @return {Array} Array of requisitions for given criteria (optional)
         *
         * @description
         * Search requisitons by criteria from parameters.
         *
         */
        function search(offline, searchParams) {
            var deferred = $q.defer();

            if(offline) {
                var requisitions = offlineRequisitions.search(searchParams, 'requisitionSearch');
                angular.forEach(requisitions, function(requisition) {
                    transformRequisition(requisition);
                    requisition.$searchedOffline = true;
                });
                deferred.resolve(requisitions);
            } else {
                resource.search(searchParams).$promise.then(function(requisitions) {
                    angular.forEach(requisitions, function(requisition) {
                        if(offlineRequisitions.getBy('id', requisition.id)) requisition.$availableOffline = true;
                    });
                    deferred.resolve(requisitions);
                }, function() {
                    deferred.reject();
                });
            }

            return deferred.promise;
        }

        /**
         * @ngdoc function
         * @name forApproval
         * @methodOf requisition.requisitionService
         * @return {Array} Array of requisitions for approval
         *
         * @description
         * Retrieves all requisitions with authorized status for approve.
         *
         */
        function forApproval() {
            return resource.forApproval().$promise;
        }

        /**
         * @ngdoc function
         * @name forConvert
         * @methodOf requisition.requisitionService
         * @param {Object} params Request params, contains i.e.: filertBy, filterValue, sortBy, descending
         * @return {Array} Array of requisitions for convert
         *
         * @description
         * Search requisitons for convert to order by given criteria.
         *
         */
        function forConvert(params) {
            return resource.forConvert(params).$promise;
        }

        /**
         * @ngdoc function
         * @name convertToOrder
         * @methodOf requisition.requisitionService
         * @param {Array} requisitions Array of requisitions to convert
         *
         * @description
         * Converts given requisitions into orders.
         *
         */
        function convertToOrder(requisitions) {
            var deferred = $q.defer();

            confirmService.confirm('msg.question.confirmation.convertToOrder').then(function() {
                resource.convertToOrder(requisitions).$promise.then(function() {
                    deferred.resolve();
                    notificationService.success('msg.rnr.converted.to.order');
                }, function() {
                    deferred.reject();
                    notificationService.error('msg.error.occurred');
                });
            }, function() {
                deferred.reject();
            });

            return deferred.promise;
        }

        function getRequisition(id) {
            return resource.get({
                id: id
            }).$promise;
        }

        function getOfflineRequisition(id) {
            return offlineRequisitions.getBy('id', id);
        }

        function getStockAdjustmentReasons(requisition) {
            return resource.getStockAdjustmentReasonsByProgram({
                program: requisition.program.id
            }).$promise;
        }

        function getStatusMessages(requisition) {
            return resource.getStatusMessages({
                id: requisition.id
            }).$promise;
        }

        function storeResponses(requisition, reasons, statusMessages) {
            requisition.$modified = false;
            offlineRequisitions.put(requisition);

            reasons.forEach(function(reason) {
                offlineStockAdjustmentReasons.put(reason);
            });

            statusMessages.forEach(function(statusMessage) {
                offlineStatusMessages.put(statusMessage);
            });
        }

        function transformRequest(requisitionsWithDepots) {
            var body = [];
            angular.forEach(requisitionsWithDepots, function(requisitionWithDepots) {
                body.push({
                    requisitionId: requisitionWithDepots.requisition.id,
                    supplyingDepotId: requisitionWithDepots.requisition.supplyingFacility
                });
            });
            return angular.toJson(body);
        }

        function transformGetResponse(data, headers, status) {
            return transformResponse(data, status, function(response) {
                if (response.processingPeriod.startDate) {
                    response.processingPeriod.startDate = dateUtils.toDate(response.processingPeriod.startDate);
                }
                if (response.processingPeriod.endDate) {
                    response.processingPeriod.endDate = dateUtils.toDate(response.processingPeriod.endDate);
                }
                return response;
            });
        }

        function transformRequisitionSearchResponse(data, headers, status) {
            return transformResponse(data, status, function(response) {
                angular.forEach(response.content, transformRequisition);
                return response.content;
            });
        }

        function transformRequisitionListResponse(data, headers, status) {
            return transformResponse(data, status, function(requisitions) {
                angular.forEach(requisitions, transformRequisition);
                return requisitions;
            });
        }

        function transformResponseForConvert(data, headers, status) {
            return transformResponse(data, status, function(response) {
                angular.forEach(response.content, function(item) {
                    transformRequisition(item.requisition);
                });
                return response;
            });
        }

        function transformResponse(data, status, transformer) {
            if (status === 200) {
                return transformer(angular.fromJson(data));
            }
            return data;
        }

        function transformRequisition(requisition) {
            requisition.createdDate = dateUtils.toDate(requisition.createdDate);
            requisition.processingPeriod.startDate = dateUtils.toDate(requisition.processingPeriod.startDate);
            requisition.processingPeriod.endDate = dateUtils.toDate(requisition.processingPeriod.endDate);
            requisition.processingPeriod.processingSchedule.modifiedDate = dateUtils.toDate(requisition.processingPeriod.processingSchedule.modifiedDate);
        }
    }
})();
<|endoftext|>


<commit_before>/**
 * updater.js
 *
 * Please use manual update only when it is really required, otherwise please use recommended non-intrusive auto update.
 *
 * Import steps:
 * 1. create `updater.js` for the code snippet
 * 2. require `updater.js` for menu implementation, and set `checkForUpdates` callback from `updater` for the click property of `Check Updates...` MenuItem.
 */
const { dialog } = require('electron')
const { autoUpdater } = require('electron-updater')

let updater = {}
autoUpdater.autoDownload = false

autoUpdater.on('error', (error) => {
  // dialog.showErrorBox('Error: ', error == null ? "unknown" : (error.stack || error).toString())
  var status = (error && error.status) ? error.status : '';
  dialog.showErrorBox('Error: could not check for updates. ', status);
})

autoUpdater.on('update-available', () => {
  dialog.showMessageBox({
    type: 'info',
    title: 'Found Updates',
    message: 'Found updates, do you want update now?',
    buttons: ['Sure', 'No']
  }, (buttonIndex) => {
    if (buttonIndex === 0) {
      autoUpdater.downloadUpdate()
    }
    else {
      updater.enabled = true
      // updater = null
    }
  })
})

autoUpdater.on('update-not-available', () => {
  dialog.showMessageBox({
    title: 'No Updates',
    message: 'Current version is up-to-date.'
  })
  updater.enabled = true
  // updater = null
})

autoUpdater.on('update-downloaded', () => {
  dialog.showMessageBox({
    title: 'Install Updates',
    message: 'Updates downloaded, application will be quit for update...'
  }, () => {
    setImmediate(() => autoUpdater.quitAndInstall())
  })
})

// export this to MenuItem click callback
// function checkForUpdates (menuItem, focusedWindow, event) {
function checkForUpdates() {
  // updater = menuItem
  updater.enabled = false
  autoUpdater.checkForUpdates()
}
module.exports.checkForUpdates = checkForUpdates
<commit_msg>revise wording in updater<commit_after>/**
 * updater.js
 *
 * Please use manual update only when it is really required, otherwise please use recommended non-intrusive auto update.
 *
 * Import steps:
 * 1. create `updater.js` for the code snippet
 * 2. require `updater.js` for menu implementation, and set `checkForUpdates` callback from `updater` for the click property of `Check Updates...` MenuItem.
 */
const { dialog } = require('electron')
const { autoUpdater } = require('electron-updater')

let updater = {}
autoUpdater.autoDownload = false

autoUpdater.on('error', (error) => {
  // dialog.showErrorBox('Error: ', error == null ? "unknown" : (error.stack || error).toString())
  var status = (error && error.status) ? error.status : '';
  dialog.showErrorBox('Error: could not check for updates. ', status);
})

autoUpdater.on('update-available', () => {
  dialog.showMessageBox({
    type: 'info',
    title: 'Found Updates',
    message: 'Found updates from Blink1Control2 github. Do you want update now?',
    buttons: ['Sure', 'No']
  }, (buttonIndex) => {
    if (buttonIndex === 0) {
      autoUpdater.downloadUpdate()
    }
    else {
      updater.enabled = true
      // updater = null
    }
  })
})

autoUpdater.on('update-not-available', () => {
  dialog.showMessageBox({
    title: 'No Updates',
    message: 'Current version is up-to-date.'
  })
  updater.enabled = true
  // updater = null
})

autoUpdater.on('update-downloaded', () => {
  dialog.showMessageBox({
    title: 'Install Updates',
    message: 'Updates downloaded. Quit application to update...'
  }, () => {
    setImmediate(() => autoUpdater.quitAndInstall())
  })
})

// export this to MenuItem click callback
// function checkForUpdates (menuItem, focusedWindow, event) {
function checkForUpdates() {
  // updater = menuItem
  updater.enabled = false
  autoUpdater.checkForUpdates()
}
module.exports.checkForUpdates = checkForUpdates
<|endoftext|>


<commit_before>const path = require('path');
const xml = require('xmldoc');
const fs = require('fs');
const efs = require('../utils/fs');
const glob = require('glob');

// Default android source directory to look for files
const BASE_DIR = './android';
const GLOB_PATTERN = '**/*.java';

/**
 * Gets source directory for current folder
 *
 * Given folder, it checks if /android exists, if no - returns null
 * Tries to find /app folder in /android and if it exists - returns it
 * Otherwise returns /android
 */
const getSourceDirectory = (folder) => {
  if (!fs.existsSync(path.join(folder, BASE_DIR))) {
    return null;
  }

  if (fs.existsSync(path.join(folder, BASE_DIR, 'app'))) {
    return path.join(BASE_DIR, 'app');
  }

  return BASE_DIR;
};

/**
 * Gets package name by opening AndroidManifest.xml and reading
 * package attribute
 */
const getPackageName = (src) => {
  const manifest = new xml.XmlDocument(
    efs.loadFile(path.join(src, 'src/main/AndroidManifest.xml'))
  );

  return manifest.attr.package;
};

/**
 * Given package name, replaces . to separators to follow Java convention
 * and locate .java files
 */
const getPackageFolder = (packageName) => packageName.replace('.', path.sep);

/**
 * Gets package name (class that implements ReactPackage) by searching for its
 * declaration in all Java files present in the src
 */
const getPackageInstance = (src) => {
  const files = glob.sync(GLOB_PATTERN, {
    cwd: src,
  });

  const packages = files
    .map(filePath => efs.loadFile(path.join(src, filePath)))
    .map(file => file.match(/class (.*) implements ReactPackage/))
    .filter(match => match);

  // No packages exported, ignore
  if (packages.length === 0) {
    return null;
  }

  return packages[0][1];
};

/**
 * Gets android project config by analyzing given folder and taking some
 * defaults specified by user into consideration
 */
exports.projectConfig = function projectConfigAndroid(folder, userConfig) {
  const sourceDir = userConfig.sourceDir || getSourceDirectory(folder);

  if (!sourceDir) {
    return null;
  }

  const src = path.join(folder, sourceDir);
  const packageName = userConfig.packageName || getPackageName(src);
  const packageFolder = userConfig.packageFolder || getPackageFolder(packageName);

  return {
    src: src,
    folder: folder,
    project: path.join(src, userConfig.project || 'build.gradle'),
    settings: path.join(folder, BASE_DIR, userConfig.settings || 'settings.gradle'),
    mainActivity: path.join(src, userConfig.mainActivity || `src/main/java/${packageFolder}/MainActivity.java`),
  };
};

/**
 * Same as projectConfigAndroid except it returns different config that applies to packages
 * only
 */
exports.dependencyConfig = function dependencyConfigAndroid(folder, userConfig) {
  const sourceDir = userConfig.sourceDir || getSourceDirectory(folder);

  if (!sourceDir) {
    return null;
  }

  const src = path.join(folder, sourceDir);
  const packageName = userConfig.packageName || getPackageName(src);
  const packageInstance = userConfig.packageInstance || getPackageInstance(src);

  // This module has no package to export
  if (!packageInstance) {
    return null;
  }

  return {
    src: src,
    folder: folder,
    packageImportPath: `import ${packageName}.${packageInstance}`,
    packageInstance: `new ${packageInstance}()`,
  };
};
<commit_msg>add assetsPath for android<commit_after>const path = require('path');
const xml = require('xmldoc');
const fs = require('fs');
const efs = require('../utils/fs');
const glob = require('glob');

// Default android source directory to look for files
const BASE_DIR = './android';
const GLOB_PATTERN = '**/*.java';

/**
 * Gets source directory for current folder
 *
 * Given folder, it checks if /android exists, if no - returns null
 * Tries to find /app folder in /android and if it exists - returns it
 * Otherwise returns /android
 */
const getSourceDirectory = (folder) => {
  if (!fs.existsSync(path.join(folder, BASE_DIR))) {
    return null;
  }

  if (fs.existsSync(path.join(folder, BASE_DIR, 'app'))) {
    return path.join(BASE_DIR, 'app');
  }

  return BASE_DIR;
};

/**
 * Gets package name by opening AndroidManifest.xml and reading
 * package attribute
 */
const getPackageName = (src) => {
  const manifest = new xml.XmlDocument(
    efs.loadFile(path.join(src, 'src/main/AndroidManifest.xml'))
  );

  return manifest.attr.package;
};

/**
 * Given package name, replaces . to separators to follow Java convention
 * and locate .java files
 */
const getPackageFolder = (packageName) => packageName.replace('.', path.sep);

/**
 * Gets package name (class that implements ReactPackage) by searching for its
 * declaration in all Java files present in the src
 */
const getPackageInstance = (src) => {
  const files = glob.sync(GLOB_PATTERN, {
    cwd: src,
  });

  const packages = files
    .map(filePath => efs.loadFile(path.join(src, filePath)))
    .map(file => file.match(/class (.*) implements ReactPackage/))
    .filter(match => match);

  // No packages exported, ignore
  if (packages.length === 0) {
    return null;
  }

  return packages[0][1];
};

/**
 * Gets android project config by analyzing given folder and taking some
 * defaults specified by user into consideration
 */
exports.projectConfig = function projectConfigAndroid(folder, userConfig) {
  const sourceDir = userConfig.sourceDir || getSourceDirectory(folder);

  if (!sourceDir) {
    return null;
  }

  const src = path.join(folder, sourceDir);
  const packageName = userConfig.packageName || getPackageName(src);
  const packageFolder = userConfig.packageFolder || getPackageFolder(packageName);

  return {
    src: src,
    folder: folder,
    project: path.join(src, userConfig.project || 'build.gradle'),
    settings: path.join(folder, BASE_DIR, userConfig.settings || 'settings.gradle'),
    assetsPath: path.join(src, userConfig.assetsPath || 'src/main/assets'),
    mainActivity: path.join(src, userConfig.mainActivity || `src/main/java/${packageFolder}/MainActivity.java`),
  };
};

/**
 * Same as projectConfigAndroid except it returns different config that applies to packages
 * only
 */
exports.dependencyConfig = function dependencyConfigAndroid(folder, userConfig) {
  const sourceDir = userConfig.sourceDir || getSourceDirectory(folder);

  if (!sourceDir) {
    return null;
  }

  const src = path.join(folder, sourceDir);
  const packageName = userConfig.packageName || getPackageName(src);
  const packageInstance = userConfig.packageInstance || getPackageInstance(src);

  // This module has no package to export
  if (!packageInstance) {
    return null;
  }

  return {
    src: src,
    folder: folder,
    packageImportPath: `import ${packageName}.${packageInstance}`,
    packageInstance: `new ${packageInstance}()`,
  };
};
<|endoftext|>


<commit_before>'use strict';

pinpointApp.directive('filterInformation', [ '$filter', '$base64',
    function ($filter, $base64) {
        return {
            restrict: 'EA',
            replace: true,
            templateUrl: 'views/filterInformation.html',
            scope : {
                namespace : '@' // string value
            },
            link: function postLink(scope, element, attrs) {

                // define private variables;

                // define private variables of methods;
                var initialize, reset;

                /**
                 * initialize
                 * @param oServerMapFilterVo
                 */
                initialize = function (oServerMapFilterVo) {
                    reset();
                    if (oServerMapFilterVo.getRequestUrlPattern()) {
                        scope.urlPattern = $base64.decode(oServerMapFilterVo.getRequestUrlPattern());
                    }
                    scope.includeException = oServerMapFilterVo.getIncludeException() ? 'Failed Only' : 'Success + Failed';

                    if (angular.isNumber(oServerMapFilterVo.getResponseFrom()) &&
                        oServerMapFilterVo.getResponseTo()) {
                        var responseTime = [];
                        responseTime.push($filter('number')(oServerMapFilterVo.getResponseFrom()));
                        responseTime.push('ms');
                        responseTime.push('~');
                        if (oServerMapFilterVo.getResponseTo() === 'max') {
                            responseTime.push('30,000+');
                        } else {
                            responseTime.push($filter('number')(oServerMapFilterVo.getResponseTo()));
                        }
                        responseTime.push('ms');

                        scope.responseTime = responseTime.join(' ');
                    }

                    var fromAgentName = oServerMapFilterVo.getFromAgentName();
                    var toAgentName = oServerMapFilterVo.getToAgentName();
                    if (fromAgentName || toAgentName) {
                        scope.agentFilterInfo = (fromAgentName || 'all') + ' -> ' + (toAgentName || 'all');
                    }

                };

                /**
                 * reset
                 */
                reset = function () {
                    scope.urlPattern = 'none';
                    scope.responseTime = 'none';
                    scope.includeException = 'none';
                };

                /**
                 * scope event on filterInformation.initialize.namespace
                 */
                scope.$on('filterInformation.initialize.' + scope.namespace, function (e, oServerMapFilterVo) {
                    initialize(oServerMapFilterVo);
                });
            }
        };
    }
]);
<commit_msg>[임대현] [NOBTS] sidebar, filter information bug fix<commit_after>'use strict';

pinpointApp.directive('filterInformation', [ '$filter', '$base64',
    function ($filter, $base64) {
        return {
            restrict: 'EA',
            replace: true,
            templateUrl: 'views/filterInformation.html',
            scope : {
                namespace : '@' // string value
            },
            link: function postLink(scope, element, attrs) {

                // define private variables;

                // define private variables of methods;
                var initialize, reset;

                /**
                 * initialize
                 * @param oServerMapFilterVo
                 */
                initialize = function (oServerMapFilterVo) {
                    reset();
                    if (oServerMapFilterVo.getRequestUrlPattern()) {
                        scope.urlPattern = $base64.decode(oServerMapFilterVo.getRequestUrlPattern());
                    }
                    scope.includeException = oServerMapFilterVo.getIncludeException() ? 'Failed Only' : 'Success + Failed';

                    if (angular.isNumber(oServerMapFilterVo.getResponseFrom()) &&
                        oServerMapFilterVo.getResponseTo()) {
                        var responseTime = [];
                        responseTime.push($filter('number')(oServerMapFilterVo.getResponseFrom()));
                        responseTime.push('ms');
                        responseTime.push('~');
                        if (oServerMapFilterVo.getResponseTo() === 'max') {
                            responseTime.push('30,000+');
                        } else {
                            responseTime.push($filter('number')(oServerMapFilterVo.getResponseTo()));
                        }
                        responseTime.push('ms');

                        scope.responseTime = responseTime.join(' ');
                    }

                    var fromAgentName = oServerMapFilterVo.getFromAgentName();
                    var toAgentName = oServerMapFilterVo.getToAgentName();
                    if (fromAgentName || toAgentName) {
                        scope.agentFilterInfo = (fromAgentName || 'all') + ' -> ' + (toAgentName || 'all');
                    } else {
                        scope.agentFilterInfo = false;
                    }

                };

                /**
                 * reset
                 */
                reset = function () {
                    scope.urlPattern = 'none';
                    scope.responseTime = 'none';
                    scope.includeException = 'none';
                };

                /**
                 * scope event on filterInformation.initialize.namespace
                 */
                scope.$on('filterInformation.initialize.' + scope.namespace, function (e, oServerMapFilterVo) {
                    initialize(oServerMapFilterVo);
                });
            }
        };
    }
]);
<|endoftext|>