<commit_before>define(function (require, exports, module) {
  /**
   *
   * @param option
   * {
   * el, //list wrap element,optional if listEl is specified
   * listEl,// list element,optional if el is specified
   * processEl,//process element,optional if el is specified
   * listCls, //[optional]css class to find the slide list,default ".list"
   * processCls, //[optional]css class to find the slide process,default ".process"
   *
   * vertical, //[optional]slide direction,default horizontal(false)
   * itemLen, //[optional]width(or height) for each item
   * itemCount,//[optional]total item length for the list
   * totalLen,//[optional]total width(or height) for the list
   *
   * enableDrag, //[optional]enable drag to move,default false
   * enableLoop, //[optional]enable infinite loop,default false
   * enableAutorun, //[optional]enable auto move,default false
   * enableProcess, //[optional]enable default navigation process UI,default false
   *
   * moveTimeout, //[optional]time out for next move,default 100ms
   * moveDuration, //[optional]time out for one move duration,default 640
   * moveRate, //[optional]speed for animate one move,default 1.3
   * dragAnim, //[optional]drag move animation timing function,default 'cubic-bezier(0.075, 0.82, 0.165, 1)'
   * moveAnim, //[optional]auto move animation timing function,default 'ease'
   *
   *
   * onMove, //[optional]on moving event listener
   * onFirst, //[optional]on first slide event listener
   * onLast, //[optional]on last slide event listener
   * onTouchstart, //[optional]on touchstart event listener
   * onTouchend, //[optional]on touchend  event listener
   * onTouchmove //[optional]on touchmove  event listener
   * }
   * @constructor Slider
   */
  function Slider(option) {
    option = option || {};
    var me = this,
      emptyFn = function () {
      },
      el = option.listEl || option.el.find(option.listCls || '.list'),
      pEl = option.processEl || el.siblings(option.processCls || '.process'),
      isMoving = false,
      moveTimeout = option.moveTimeout || 100,
      moveDuration = option.moveDuration || 640,
      moveRate = option.moveRate || 1.3,
      vertical = option.vertical,
      index = 0,
      totalLen,
      itemCount,
      itemLen,
      orientation = true,
      lastMove = 0,
      autoTimer = 0,
      loopTimer = 0,
      loopCls = 'slider-duplicate',
      moveToFn = vertical?moveToY:moveToX;
    resetSize();
    calculateSize();
    var enableProcess = option.enableProcess,
      enableAutorun = option.enableAutorun,
      enableDrag = option.enableDrag,
      enableLoop = option.enableLoop;
    var onMove = option.onMove || emptyFn,
      onFirst = option.onFirst || emptyFn,
      onLast = option.onLast || emptyFn,
      onTouchstart = option.onTouchstart || emptyFn,
      onTouchend = option.onTouchend || emptyFn,
      onTouchmove = option.onTouchmove || emptyFn;
    var dragAnim = option.dragAnim||'cubic-bezier(0.075, 0.82, 0.165, 1)',//'cubic-bezier(0.1, 0.57, 0.1, 1)';
      moveAnim = option.moveAnim||'ease';
    var drag = {
      moved: false,
      timer: 0,
      dirX: 0,
      distX: 0,
      dirY: 0,
      distY: 0,
      moveDistX: 0,
      maxMove: itemLen / 2,
      startTime: 0,
      endTime: 0,
      resetMaxMove: function () {
        drag.maxMove = itemLen / 2;
      },
      distPos: function(){
        return drag[vertical?'distY':'distX'];
      },
      reset: function () {
        drag.moved = false;
        drag.isSwipe = false;
        drag.dirX = 0;
        drag.distX = 0;
        drag.dirY = 0;
        drag.distY = 0;
        drag.timer = 0;
        drag.timer && cancelRequestAnimFrame(drag.timer);
      },
      move: function () {
        if (!drag.moved) {
          return;
        }
        var mX = -(index+(enableLoop?1:0)) * itemLen,
          dx = Math.round(Math.abs(drag.distPos()) / moveRate);
        drag.moveDistX = dx;
        if (dx > itemLen * 9 / 10) {
          drag.endDrag();
          return;
        } else if (drag.distPos() > 0) {
          mX += dx;
        } else {
          mX -= dx;
        }

        moveToFn(mX,0,dragAnim);
        lastMove = -mX;
      },
      endDrag: function () {
        drag.moved = false;
        var mX = -index * itemLen,
          dx = drag.moveDistX;
        if (drag.isSwipe) {
          drag.distPos() > 0 ? me.pre() : me.next();
        } else {
          if (drag.distPos() > 0) {
            mX += dx;
          } else {
            mX -= dx;
          }
          if (mX >= 0 || mX <= -(totalLen - itemLen) || dx < drag.maxMove) {
            move();
          } else {
            drag.distPos() > 0 ? me.pre() : me.next();
          }
        }

        drag.reset();
        me.startAutoRun();
      }
    };

    function touchStart(e) {
      if (itemCount < 2 || isMoving) {
        return;
      }
      drag.startTime = new Date().getTime();
      onTouchstart();
      me.stopAutoRun();
      totalLen = totalLen || el.width();
      itemLen = itemLen || (totalLen / itemCount);
      drag.resetMaxMove();
      var touch = e.touches[0];
      drag.moved = true;
      drag.dirX = touch.pageX;
      drag.distX = 0;
      drag.dirY = touch.pageY;
      drag.distY = 0;
      (function animloop() {
        if (!drag.moved) {
          drag.reset();
          return;
        }
        drag.move();
        drag.timer = requestAnimFrame(animloop);
      })();
    }

    function touchMove(e) {
      var touch = e.touches[0];
      drag.distX = touch.pageX - drag.dirX;
      drag.distY = touch.pageY - drag.dirY;
      onTouchmove(Math.abs(drag.distX), Math.abs(drag.distY));
    }

    function touchEnd(e) {
      drag.endTime = new Date().getTime();
      if (drag.moved) {
        drag.isSwipe = drag.endTime - drag.startTime <= 200 && Math.abs(drag.distPos()) > 30;
        drag.endDrag();
      }
      onTouchend(Math.abs(drag.distX), Math.abs(drag.distY));
    }

    if (enableDrag) {
      el.touchstart = el.touchstart || touchStart;
      el.touchmove = el.touchmove || touchMove;
      el.touchend = el.touchend || touchEnd;
      el.off('touchstart', el.touchstart);
      el.off('touchmove', el.touchmove);
      el.off('touchend', el.touchend);
      el.on('touchstart', el.touchstart);
      el.on('touchmove', el.touchmove);
      el.on('touchend', el.touchend);
    }

    this.next = function () {
      if (isMoving) {
        return;
      }
      index++;
      move();
    }
    this.pre = function () {
      if (isMoving) {
        return;
      }
      index--;
      move();
    }
    function move() {
      if (isMoving) {
        return;
      }
      isMoving = true;
      setTimeout(function () {
        isMoving = false;
      }, moveTimeout);
      if(!enableLoop){
        if (index > itemCount - 1) {
          index = itemCount - 1;
          onLast(index);
        } else if (index < 0) {
          index = 0;
          onFirst(index);
        }
      }
      var mx = (index+(enableLoop?1:0)) * itemLen,
        absm = Math.abs(lastMove - mx),
        mtime = Math.min(moveDuration,(moveDuration / itemLen) * absm),
        animate = moveAnim;

      if (drag.isSwipe) {
        var velocity = drag.moveDistX * moveRate / (drag.endTime - drag.startTime);
        mtime = velocity * absm;
        animate = dragAnim;
      }

      lastMove = mx;
      //修正android差1px的问题
      //mx = (mx>0&&$.os.android)?(mx+1):mx;
      moveToFn(-mx,mtime,animate);

      stopLoopHelper();
      if(enableLoop){
        var loopm;
        if (index > itemCount - 1) {
          loopm = itemLen;
          index = 0;
          lastMove = itemLen;
          onLast(index);
        } else if (index < 0) {
          loopm = itemLen*itemCount;
          index = itemCount - 1;
          onFirst(index);
        }
        loopTimer = loopm!==undefined && setTimeout(function(){
            moveToFn(-loopm);
        },mtime);
      }
      runProcess();
      onMove(index);
    }

    function moveToX(x,time,anim){
      moveTo(x,0,time,anim);
    }
    function moveToY(x,time,anim){
      moveTo(0,x,time,anim);
    }
    function moveTo(x,y,time,anim){
      el.css({
        '-webkit-transform': 'translate3d('+(x||0)+'px'+','+(y||0)+'px,0)',
        '-webkit-transition': '-webkit-transform '+(time||0)+'ms ' + (anim||moveAnim)
      });
    }

    this.reset = function () {
      index = 0;
      orientation = true;
      me.stopAutoRun();
      pEl.hide();
      resetSize();
      calculateSize();
      renderLoop();
      lastMove = enableLoop?itemLen:0;
      moveToFn(-lastMove);
      drag.reset();
      renderProcess();
      me.startAutoRun();
    }
    this.refresh = function(){
      me.stopAutoRun();
      pEl.hide();
      resetSize();
      calculateSize();
      renderLoop();
      renderProcess();
      me.startAutoRun();
    }
    this.stopAutoRun = function () {
      autoTimer && clearInterval(autoTimer);
      stopLoopHelper();
    }
    function stopLoopHelper(){
      loopTimer && clearInterval(loopTimer);
    }
    function moveOrientation() {
      calculateSize();
      if (!enableLoop && index == itemCount - 1) {
        orientation = false;
      } else if (index == 0) {
        orientation = true;
      }
      if (!orientation) {
        me.pre();
      } else {
        me.next();
      }
    }

    this.startAutoRun = function () {
      if (enableAutorun && itemCount > 1) {
        autoTimer = setInterval(function () {
          if (drag.moved) {
            return;
          }//如果拖动就停止
          moveOrientation();
        }, 3000);
      }
    }
    function renderProcess() {
      if (enableProcess && itemCount > 1) {
        var tmp = [];
        for (var i = 0; i < itemCount; i++) {
          tmp.push('

');
        }
        pEl.html(tmp.join(''));
        pEl.show();
        runProcess();
      }
    }

    function renderLoop(){
      if (enableLoop){
        el.find('.'+loopCls).remove();
        var cels = [].slice.call(el.children()),
          first = cels.pop().cloneNode(true),
          last = cels.shift().cloneNode(true);
        first.classList.add(loopCls);
        last.classList.add(loopCls);
        el.prepend(first);
        el.append(last);
      }
    }

    function runProcess() {
      if (!enableProcess) {
        return;
      }
      var processChild = pEl.find('div');
      processChild.removeClass('on');
      $(processChild[index]).addClass('on');
    }

    function resetSize(){
      el.find('.'+loopCls).remove();
      itemLen = option.itemLen || 0;
      itemCount = option.itemCount || 0;
      totalLen = option.totalLen || (itemCount*itemLen) || 0;
    }
    function calculateSize(){
      var child = el.children();
      itemLen = itemLen || child.eq(0)[vertical?'height':'width']();
      itemCount = itemCount || child.length;
      totalLen = totalLen || (itemLen*itemCount);
    }

    this.reset();
  }

  return Slider;
});
<commit_msg>added moveTo & methods comments<commit_after>define(function (require, exports, module) {
  /**
   *
   * @param option
   * {
   * el, //list wrap element,optional if listEl is specified
   * listEl,// list element,optional if el is specified
   * processEl,//process element,optional if el is specified
   * listCls, //[optional]css class to find the slide list,default ".list"
   * processCls, //[optional]css class to find the slide process,default ".process"
   *
   * vertical, //[optional]slide direction,default horizontal(false)
   * itemLen, //[optional]width(or height) for each item
   * itemCount,//[optional]total item length for the list
   * totalLen,//[optional]total width(or height) for the list
   *
   * enableDrag, //[optional]enable drag to move,default false
   * enableLoop, //[optional]enable infinite loop,default false
   * enableAutorun, //[optional]enable auto play,default false
   * enableProcess, //[optional]enable default navigation process UI,default false
   *
   * moveTimeout, //[optional]time out for next move,default 100ms
   * moveDuration, //[optional]time out for one move duration,default 640
   * moveRate, //[optional]speed for animate one move,default 1.3
   * dragAnim, //[optional]drag move animation timing function,default 'cubic-bezier(0.075, 0.82, 0.165, 1)'
   * moveAnim, //[optional]auto move animation timing function,default 'ease'
   *
   *
   * onMove, //[optional]on moving event listener
   * onFirst, //[optional]on first slide event listener
   * onLast, //[optional]on last slide event listener
   * onTouchstart, //[optional]on touchstart event listener
   * onTouchend, //[optional]on touchend  event listener
   * onTouchmove //[optional]on touchmove  event listener
   * }
   *
   * @method next() //move to next slide
   * @method pre() //move to pre slide
   * @method moveTo(index) //move to specified index slide,start from 0
   * @method reset() //reset to default state
   * @method refresh() //refresh for content changed
   * @method startAutoRun() //start to auto play
   * @method stopAutoRun() //stop auto play
   * @constructor Slider
   */
  function Slider(option) {
    option = option || {};
    var me = this,
      emptyFn = function () {
      },
      el = option.listEl || option.el.find(option.listCls || '.list'),
      pEl = option.processEl || el.siblings(option.processCls || '.process'),
      isMoving = false,
      moveTimeout = option.moveTimeout || 100,
      moveDuration = option.moveDuration || 640,
      moveRate = option.moveRate || 1.3,
      vertical = option.vertical,
      index = 0,
      totalLen,
      itemCount,
      itemLen,
      orientation = true,
      lastMove = 0,
      autoTimer = 0,
      loopTimer = 0,
      loopCls = 'slider-duplicate',
      moveToFn = vertical?moveToY:moveToX;
    resetSize();
    calculateSize();
    var enableProcess = option.enableProcess,
      enableAutorun = option.enableAutorun,
      enableDrag = option.enableDrag,
      enableLoop = option.enableLoop;
    var onMove = option.onMove || emptyFn,
      onFirst = option.onFirst || emptyFn,
      onLast = option.onLast || emptyFn,
      onTouchstart = option.onTouchstart || emptyFn,
      onTouchend = option.onTouchend || emptyFn,
      onTouchmove = option.onTouchmove || emptyFn;
    var dragAnim = option.dragAnim||'cubic-bezier(0.075, 0.82, 0.165, 1)',//'cubic-bezier(0.1, 0.57, 0.1, 1)';
      moveAnim = option.moveAnim||'ease';
    var drag = {
      moved: false,
      timer: 0,
      dirX: 0,
      distX: 0,
      dirY: 0,
      distY: 0,
      moveDistX: 0,
      maxMove: itemLen / 2,
      startTime: 0,
      endTime: 0,
      resetMaxMove: function () {
        drag.maxMove = itemLen / 2;
      },
      distPos: function(){
        return drag[vertical?'distY':'distX'];
      },
      reset: function () {
        drag.moved = false;
        drag.isSwipe = false;
        drag.dirX = 0;
        drag.distX = 0;
        drag.dirY = 0;
        drag.distY = 0;
        drag.timer = 0;
        drag.timer && cancelRequestAnimFrame(drag.timer);
      },
      move: function () {
        if (!drag.moved) {
          return;
        }
        var mX = -(index+(enableLoop?1:0)) * itemLen,
          dx = Math.round(Math.abs(drag.distPos()) / moveRate);
        drag.moveDistX = dx;
        if (dx > itemLen * 9 / 10) {
          drag.endDrag();
          return;
        } else if (drag.distPos() > 0) {
          mX += dx;
        } else {
          mX -= dx;
        }

        moveToFn(mX,0,dragAnim);
        lastMove = -mX;
      },
      endDrag: function () {
        drag.moved = false;
        var mX = -index * itemLen,
          dx = drag.moveDistX;
        if (drag.isSwipe) {
          drag.distPos() > 0 ? me.pre() : me.next();
        } else {
          if (drag.distPos() > 0) {
            mX += dx;
          } else {
            mX -= dx;
          }
          if (mX >= 0 || mX <= -(totalLen - itemLen) || dx < drag.maxMove) {
            move();
          } else {
            drag.distPos() > 0 ? me.pre() : me.next();
          }
        }

        drag.reset();
        me.startAutoRun();
      }
    };

    function touchStart(e) {
      if (itemCount < 2 || isMoving) {
        return;
      }
      drag.startTime = new Date().getTime();
      onTouchstart();
      me.stopAutoRun();
      totalLen = totalLen || el.width();
      itemLen = itemLen || (totalLen / itemCount);
      drag.resetMaxMove();
      var touch = e.touches[0];
      drag.moved = true;
      drag.dirX = touch.pageX;
      drag.distX = 0;
      drag.dirY = touch.pageY;
      drag.distY = 0;
      (function animloop() {
        if (!drag.moved) {
          drag.reset();
          return;
        }
        drag.move();
        drag.timer = requestAnimFrame(animloop);
      })();
    }

    function touchMove(e) {
      var touch = e.touches[0];
      drag.distX = touch.pageX - drag.dirX;
      drag.distY = touch.pageY - drag.dirY;
      onTouchmove(Math.abs(drag.distX), Math.abs(drag.distY));
    }

    function touchEnd(e) {
      drag.endTime = new Date().getTime();
      if (drag.moved) {
        drag.isSwipe = drag.endTime - drag.startTime <= 200 && Math.abs(drag.distPos()) > 30;
        drag.endDrag();
      }
      onTouchend(Math.abs(drag.distX), Math.abs(drag.distY));
    }

    if (enableDrag) {
      el.touchstart = el.touchstart || touchStart;
      el.touchmove = el.touchmove || touchMove;
      el.touchend = el.touchend || touchEnd;
      el.off('touchstart', el.touchstart);
      el.off('touchmove', el.touchmove);
      el.off('touchend', el.touchend);
      el.on('touchstart', el.touchstart);
      el.on('touchmove', el.touchmove);
      el.on('touchend', el.touchend);
    }

    function move() {
      if (isMoving) {
        return;
      }
      isMoving = true;
      setTimeout(function () {
        isMoving = false;
      }, moveTimeout);
      if(!enableLoop){
        if (index > itemCount - 1) {
          index = itemCount - 1;
          onLast(index);
        } else if (index < 0) {
          index = 0;
          onFirst(index);
        }
      }
      var mx = (index+(enableLoop?1:0)) * itemLen,
        absm = Math.abs(lastMove - mx),
        mtime = Math.min(moveDuration,(moveDuration / itemLen) * absm),
        animate = moveAnim;

      if (drag.isSwipe) {
        var velocity = drag.moveDistX * moveRate / (drag.endTime - drag.startTime);
        mtime = velocity * absm;
        animate = dragAnim;
      }

      lastMove = mx;
      //修正android差1px的问题
      //mx = (mx>0&&$.os.android)?(mx+1):mx;
      moveToFn(-mx,mtime,animate);

      stopLoopHelper();
      if(enableLoop){
        var loopm;
        if (index > itemCount - 1) {
          loopm = itemLen;
          index = 0;
          lastMove = itemLen;
          onLast(index);
        } else if (index < 0) {
          loopm = itemLen*itemCount;
          index = itemCount - 1;
          onFirst(index);
        }
        loopTimer = loopm!==undefined && setTimeout(function(){
            moveToFn(-loopm);
        },mtime);
      }
      runProcess();
      onMove(index);
    }

    function moveToX(x,time,anim){
      moveTo(x,0,time,anim);
    }
    function moveToY(x,time,anim){
      moveTo(0,x,time,anim);
    }
    function moveTo(x,y,time,anim){
      el.css({
        '-webkit-transform': 'translate3d('+(x||0)+'px'+','+(y||0)+'px,0)',
        '-webkit-transition': '-webkit-transform '+(time||0)+'ms ' + (anim||moveAnim)
      });
    }

    this.next = function () {
      if (isMoving) {
        return;
      }
      index++;
      move();
    }

    this.pre = function () {
      if (isMoving) {
        return;
      }
      index--;
      move();
    }

    this.moveTo = function(idx){
      index = idx;
      move();
    }

    this.reset = function () {
      index = 0;
      orientation = true;
      me.stopAutoRun();
      pEl.hide();
      resetSize();
      calculateSize();
      renderLoop();
      lastMove = enableLoop?itemLen:0;
      moveToFn(-lastMove);
      drag.reset();
      renderProcess();
      me.startAutoRun();
    }

    this.refresh = function(){
      me.stopAutoRun();
      pEl.hide();
      resetSize();
      calculateSize();
      renderLoop();
      renderProcess();
      me.startAutoRun();
    }

    this.startAutoRun = function () {
      if (enableAutorun && itemCount > 1) {
        autoTimer = setInterval(function () {
          if (drag.moved) {
            return;
          }//如果拖动就停止
          moveOrientation();
        }, 3000);
      }
    }

    this.stopAutoRun = function () {
      autoTimer && clearInterval(autoTimer);
      stopLoopHelper();
    }

    function stopLoopHelper(){
      loopTimer && clearInterval(loopTimer);
    }

    function moveOrientation() {
      calculateSize();
      if (!enableLoop && index == itemCount - 1) {
        orientation = false;
      } else if (index == 0) {
        orientation = true;
      }
      if (!orientation) {
        me.pre();
      } else {
        me.next();
      }
    }

    function renderProcess() {
      if (enableProcess && itemCount > 1) {
        var tmp = [];
        for (var i = 0; i < itemCount; i++) {
          tmp.push('

');
        }
        pEl.html(tmp.join(''));
        pEl.show();
        runProcess();
      }
    }

    function renderLoop(){
      if (enableLoop){
        el.find('.'+loopCls).remove();
        var cels = [].slice.call(el.children()),
          first = cels.pop().cloneNode(true),
          last = cels.shift().cloneNode(true);
        first.classList.add(loopCls);
        last.classList.add(loopCls);
        el.prepend(first);
        el.append(last);
      }
    }

    function runProcess() {
      if (!enableProcess) {
        return;
      }
      var processChild = pEl.find('div');
      processChild.removeClass('on');
      $(processChild[index]).addClass('on');
    }

    function resetSize(){
      el.find('.'+loopCls).remove();
      itemLen = option.itemLen || 0;
      itemCount = option.itemCount || 0;
      totalLen = option.totalLen || (itemCount*itemLen) || 0;
    }
    function calculateSize(){
      var child = el.children();
      itemLen = itemLen || child.eq(0)[vertical?'height':'width']();
      itemCount = itemCount || child.length;
      totalLen = totalLen || (itemLen*itemCount);
    }

    this.reset();
  }

  return Slider;
});
<|endoftext|>


<commit_before>d2Directives.directive('d2NumberValidator', function() {

    return {
        require: 'ngModel',
        restrict: 'A',
        link: function (scope, element, attrs, ngModel) {

            function setValidity(numberType, isRequired){
                if(numberType === 'NUMBER'){
                    ngModel.$validators.number = function(value) {
                    	value = value === 0 ? value.toString(): value;
                        return value === 'null' || !value ? !isRequired : dhis2.validation.isNumber(value);
                    };
                }
                else if(numberType === 'INTEGER_POSITIVE'){
                    ngModel.$validators.posInt = function(value) {
                    	value = value === 0 ? value.toString(): value;
                        return value === 'null' || !value ? !isRequired : dhis2.validation.isPositiveInt(value);
                    };
                }
                else if(numberType === 'INTEGER_NEGATIVE'){
                    ngModel.$validators.negInt = function(value) {
                    	value = value === 0 ? value.toString(): value;
                        return value === 'null' || !value ? !isRequired : dhis2.validation.isNegativeInt(value);
                    };
                }
                else if(numberType === 'INTEGER_ZERO_OR_POSITIVE'){
                    ngModel.$validators.zeroPositiveInt = function(value) {
                    	value = value === 0 ? value.toString(): value;
                        return value === 'null' || !value ? !isRequired : dhis2.validation.isZeroOrPositiveInt(value);
                    };
                }
                else if(numberType === 'INTEGER'){
                    ngModel.$validators.int = function(value) {
                    	value = value === 0 ? value.toString(): value;
                        return value === 'null' || !value ? !isRequired : dhis2.validation.isInt(value);
                    };
                }
            }

            var numberType = attrs.numberType;
            var isRequired = attrs.ngRequired === 'true';
            setValidity(numberType, isRequired);
        }
    };
})

.directive("d2DateValidator", function(DateUtils, CalendarService, $parse) {
    return {
        restrict: "A",
        require: "ngModel",
        link: function(scope, element, attrs, ngModel) {

            var isRequired = attrs.ngRequired === 'true';

            ngModel.$validators.dateValidator = function(value) {
                if(!value){
                    return !isRequired;
                }
                var convertedDate = DateUtils.format(angular.copy(value));
                var isValid = value === convertedDate;
                return isValid;
            };

            ngModel.$validators.futureDateValidator = function(value) {
                if(!value){
                    return !isRequired;
                }
                var maxDate = $parse(attrs.maxDate)(scope);
                var convertedDate = DateUtils.format(angular.copy(value));
                var isValid = value === convertedDate;
                if(isValid){
                    isValid = maxDate === 0 ? !moment(convertedDate).isAfter(DateUtils.getToday()) : isValid;
                }
                return isValid;
            };
        }
    };
})

.directive("d2CustomCoordinateValidator", function() {
    return {
        restrict: "A",
        require: "ngModel",
        link: function(scope, element, attrs, ngModel) {

            var isRequired = attrs.ngRequired === 'true';

            ngModel.$validators.customCoordinateValidator = function(value) {
                if(!value){
                    return !isRequired;
                }

                var coordinate = value.split(",");

                if( !coordinate || coordinate.length !== 2 ){
                    return false;
                }

                if( !dhis2.validation.isNumber(coordinate[0]) ){
                    return false;
                }

                if( !dhis2.validation.isNumber(coordinate[1]) ){
                    return false;
                }

                return coordinate[0] >= -180 && coordinate[0] <= 180 && coordinate[1] >= -90 && coordinate[1] <= 90;
            };
        }
    };
})

.directive("d2CoordinateValidator", function() {
    return {
        restrict: "A",
        require: "ngModel",
        link: function(scope, element, attrs, ngModel) {

            var isRequired = attrs.ngRequired === 'true';

            if(attrs.name === 'latitude'){
                ngModel.$validators.latitudeValidator = function(value) {
                    if(!value){
                        return !isRequired;
                    }

                    if(!dhis2.validation.isNumber(value)){
                        return false;
                    }
                    return value >= -90 && value <= 90;
                };
            }

            if(attrs.name === 'longitude'){
                ngModel.$validators.longitudeValidator = function(value) {
                    if(!value){
                        return !isRequired;
                    }

                    if(!dhis2.validation.isNumber(value)){
                        return false;
                    }
                    return value >= -180 && value <= 180;
                };
            }
        }
    };
})

.directive("d2OptionValidator", function($translate, NotificationService) {
    return {
        restrict: "A",
        require: "ngModel",
        link: function(scope, element, attrs, ngModel) {

            var isRequired = attrs.ngRequired === 'true';

            ngModel.$validators.optionValidator = function(value) {

                var res = !value ? !isRequired : true;

                if(!res){
                    var headerText = $translate.instant("validation_error");
                    var bodyText = $translate.instant("option_required");
                    NotificationService.showNotifcationDialog(headerText, bodyText);
                }
                return res;
            };
        }
    };
})

.directive("d2AttributeValidator", function($q, TEIService, SessionStorageService) {
    return {
        restrict: "A",
        require: "ngModel",
        link: function(scope, element, attrs, ngModel) {

            function uniqunessValidatior(attributeData){

                ngModel.$asyncValidators.uniqunessValidator = function (modelValue, viewValue) {
                    var pager = {pageSize: 1, page: 1, toolBarDisplay: 5};
                    var deferred = $q.defer(), currentValue = modelValue || viewValue, programUrl = null, ouMode = 'ALL';

                    if (currentValue) {

                        attributeData.value = currentValue;
                        var attUrl = 'filter=' + attributeData.id + ':EQ:' + attributeData.value;
                        var ouId = SessionStorageService.get('ouSelected');

                        if(attrs.selectedProgram && attributeData.programScope){
                            programUrl = 'program=' + attrs.selectedProgram;
                        }

                        if(attributeData.orgUnitScope){
                            ouMode = 'SELECTED';
                        }

                        TEIService.search(ouId, ouMode, null, programUrl, attUrl, pager, true).then(function(data) {
                            if(attrs.selectedTeiId){
                                if(data && data.rows && data.rows.length && data.rows[0] && data.rows[0].length && data.rows[0][0] !== attrs.selectedTeiId){
                                    deferred.reject();
                                }
                            }
                            else{
                                if (data.rows.length > 0) {
                                    deferred.reject();
                                }
                            }
                            deferred.resolve();
                        });
                    }
                    else {
                        deferred.resolve();
                    }

                    return deferred.promise;
                };
            }

            scope.$watch(attrs.ngDisabled, function(value){
                var attributeData = scope.$eval(attrs.attributeData);
                if(!value){
                    if( attributeData && attributeData.unique && !value ){
                        uniqunessValidatior(attributeData);
                    }
                }
            });
        }
    };
});<commit_msg>bug fix in date comparing<commit_after>d2Directives.directive('d2NumberValidator', function() {

    return {
        require: 'ngModel',
        restrict: 'A',
        link: function (scope, element, attrs, ngModel) {

            function setValidity(numberType, isRequired){
                if(numberType === 'NUMBER'){
                    ngModel.$validators.number = function(value) {
                    	value = value === 0 ? value.toString(): value;
                        return value === 'null' || !value ? !isRequired : dhis2.validation.isNumber(value);
                    };
                }
                else if(numberType === 'INTEGER_POSITIVE'){
                    ngModel.$validators.posInt = function(value) {
                    	value = value === 0 ? value.toString(): value;
                        return value === 'null' || !value ? !isRequired : dhis2.validation.isPositiveInt(value);
                    };
                }
                else if(numberType === 'INTEGER_NEGATIVE'){
                    ngModel.$validators.negInt = function(value) {
                    	value = value === 0 ? value.toString(): value;
                        return value === 'null' || !value ? !isRequired : dhis2.validation.isNegativeInt(value);
                    };
                }
                else if(numberType === 'INTEGER_ZERO_OR_POSITIVE'){
                    ngModel.$validators.zeroPositiveInt = function(value) {
                    	value = value === 0 ? value.toString(): value;
                        return value === 'null' || !value ? !isRequired : dhis2.validation.isZeroOrPositiveInt(value);
                    };
                }
                else if(numberType === 'INTEGER'){
                    ngModel.$validators.int = function(value) {
                    	value = value === 0 ? value.toString(): value;
                        return value === 'null' || !value ? !isRequired : dhis2.validation.isInt(value);
                    };
                }
            }

            var numberType = attrs.numberType;
            var isRequired = attrs.ngRequired === 'true';
            setValidity(numberType, isRequired);
        }
    };
})

.directive("d2DateValidator", function(DateUtils, CalendarService, $parse) {
    return {
        restrict: "A",
        require: "ngModel",
        link: function(scope, element, attrs, ngModel) {

        	var calendarSetting = CalendarService.getSetting();
            var isRequired = attrs.ngRequired === 'true';

            ngModel.$validators.dateValidator = function(value) {
                if(!value){
                    return !isRequired;
                }
                var convertedDate = DateUtils.format(angular.copy(value));
                var isValid = value === convertedDate;
                return isValid;
            };

            ngModel.$validators.futureDateValidator = function(value) {
                if(!value){
                    return !isRequired;
                }
                var maxDate = $parse(attrs.maxDate)(scope);
                var convertedDate = DateUtils.format(angular.copy(value));
                var isValid = value === convertedDate;
                if(isValid){
                	isValid = maxDate === 0 ? !moment(convertedDate, calendarSetting.momentFormat).isAfter(moment(DateUtils.getToday(), calendarSetting.momentFormat)) : isValid;
                }
                return isValid;
            };
        }
    };
})

.directive("d2CustomCoordinateValidator", function() {
    return {
        restrict: "A",
        require: "ngModel",
        link: function(scope, element, attrs, ngModel) {

            var isRequired = attrs.ngRequired === 'true';

            ngModel.$validators.customCoordinateValidator = function(value) {
                if(!value){
                    return !isRequired;
                }

                var coordinate = value.split(",");

                if( !coordinate || coordinate.length !== 2 ){
                    return false;
                }

                if( !dhis2.validation.isNumber(coordinate[0]) ){
                    return false;
                }

                if( !dhis2.validation.isNumber(coordinate[1]) ){
                    return false;
                }

                return coordinate[0] >= -180 && coordinate[0] <= 180 && coordinate[1] >= -90 && coordinate[1] <= 90;
            };
        }
    };
})

.directive("d2CoordinateValidator", function() {
    return {
        restrict: "A",
        require: "ngModel",
        link: function(scope, element, attrs, ngModel) {

            var isRequired = attrs.ngRequired === 'true';

            if(attrs.name === 'latitude'){
                ngModel.$validators.latitudeValidator = function(value) {
                    if(!value){
                        return !isRequired;
                    }

                    if(!dhis2.validation.isNumber(value)){
                        return false;
                    }
                    return value >= -90 && value <= 90;
                };
            }

            if(attrs.name === 'longitude'){
                ngModel.$validators.longitudeValidator = function(value) {
                    if(!value){
                        return !isRequired;
                    }

                    if(!dhis2.validation.isNumber(value)){
                        return false;
                    }
                    return value >= -180 && value <= 180;
                };
            }
        }
    };
})

.directive("d2OptionValidator", function($translate, NotificationService) {
    return {
        restrict: "A",
        require: "ngModel",
        link: function(scope, element, attrs, ngModel) {

            var isRequired = attrs.ngRequired === 'true';

            ngModel.$validators.optionValidator = function(value) {

                var res = !value ? !isRequired : true;

                if(!res){
                    var headerText = $translate.instant("validation_error");
                    var bodyText = $translate.instant("option_required");
                    NotificationService.showNotifcationDialog(headerText, bodyText);
                }
                return res;
            };
        }
    };
})

.directive("d2AttributeValidator", function($q, TEIService, SessionStorageService) {
    return {
        restrict: "A",
        require: "ngModel",
        link: function(scope, element, attrs, ngModel) {

            function uniqunessValidatior(attributeData){

                ngModel.$asyncValidators.uniqunessValidator = function (modelValue, viewValue) {
                    var pager = {pageSize: 1, page: 1, toolBarDisplay: 5};
                    var deferred = $q.defer(), currentValue = modelValue || viewValue, programUrl = null, ouMode = 'ALL';

                    if (currentValue) {

                        attributeData.value = currentValue;
                        var attUrl = 'filter=' + attributeData.id + ':EQ:' + attributeData.value;
                        var ouId = SessionStorageService.get('ouSelected');

                        if(attrs.selectedProgram && attributeData.programScope){
                            programUrl = 'program=' + attrs.selectedProgram;
                        }

                        if(attributeData.orgUnitScope){
                            ouMode = 'SELECTED';
                        }

                        TEIService.search(ouId, ouMode, null, programUrl, attUrl, pager, true).then(function(data) {
                            if(attrs.selectedTeiId){
                                if(data && data.rows && data.rows.length && data.rows[0] && data.rows[0].length && data.rows[0][0] !== attrs.selectedTeiId){
                                    deferred.reject();
                                }
                            }
                            else{
                                if (data.rows.length > 0) {
                                    deferred.reject();
                                }
                            }
                            deferred.resolve();
                        });
                    }
                    else {
                        deferred.resolve();
                    }

                    return deferred.promise;
                };
            }

            scope.$watch(attrs.ngDisabled, function(value){
                var attributeData = scope.$eval(attrs.attributeData);
                if(!value){
                    if( attributeData && attributeData.unique && !value ){
                        uniqunessValidatior(attributeData);
                    }
                }
            });
        }
    };
});<|endoftext|>


<commit_before>
define(['app', '../../directives/map/zoom-map'], function() { 'use strict';
	return ['$scope','locale','$http', '$location',
    function ($scope,locale, $http, $location) {

		$scope.code      = $route.current.params.code;
		//=======================================================================
		//
		//=======================================================================
		$http.get('/api/v2013/countries/'+$scope.code.toUpperCase(), {
			cache: true,
		}).then(function(res) {

				$scope.country =  res.data;
				$scope.country.code = $scope.country.code.toLowerCase();
				$scope.country.name = $scope.country.name[locale];
				$scope.country.cssClass='flag-icon-'+$scope.country.code;

			$scope.country = res.data;
			console.log($scope.country);
		});

console.log('$location.search();',$scope.code);

		//=======================================================================
		//
		//=======================================================================
		$scope.actionCountryProfile= function (code){
			$location.url('/actions/countries/'+code.toUpperCase());
		};

		//=======================================================================
		//
		//=======================================================================
		$scope.actionRegister = function () {
			$location.url('/actions/submit');
		};

    }];
});
<commit_msg>replacing dependants removed mysteriously<commit_after>
define(['app', '../../directives/map/zoom-map'], function() { 'use strict';
	return ['$scope','locale','$http', '$location', '$route',
    function ($scope,locale, $http, $location,$route) {

		$scope.code      = $route.current.params.code;
		//=======================================================================
		//
		//=======================================================================
		$http.get('/api/v2013/countries/'+$scope.code.toUpperCase(), {
			cache: true,
		}).then(function(res) {

				$scope.country =  res.data;
				$scope.country.code = $scope.country.code.toLowerCase();
				$scope.country.name = $scope.country.name[locale];
				$scope.country.cssClass='flag-icon-'+$scope.country.code;

			$scope.country = res.data;
			console.log($scope.country);
		});

console.log('$location.search();',$scope.code);

		//=======================================================================
		//
		//=======================================================================
		$scope.actionCountryProfile= function (code){
			$location.url('/actions/countries/'+code.toUpperCase());
		};

		//=======================================================================
		//
		//=======================================================================
		$scope.actionRegister = function () {
			$location.url('/actions/submit');
		};

    }];
});
<|endoftext|>


<commit_before>var _ = require('underscore');
var BaseAnalysisFormModel = require('./base-analysis-form-model');
var template = require('./intersection-form.tpl');
var ColumnOptions = require('../column-options');

var AGGREGATE_INTERSECTION_FIELDS = 'type,aggregate_function,aggregate_column';
var INTERSECTION_FIELDS = 'type';
/**
 * Form model for the intersection analysis
 */
module.exports = BaseAnalysisFormModel.extend({
  initialize: function () {
    BaseAnalysisFormModel.prototype.initialize.apply(this, arguments);

    this.listenTo(this._analysisSourceOptionsModel, 'change:fetching', this._setSchema);

    var nodeDefModel = this._layerDefinitionModel.findAnalysisDefinitionNodeModel(this.get('source'));

    this._columnOptions = new ColumnOptions({}, {
      nodeDefModel: nodeDefModel
    });

    this.listenTo(this._columnOptions, 'columnsFetched', this._setSchema);

    this.on('change:type', this._setSchema, this);
    this.on('change', this._onChange, this);

    this._setSchema();
  },

  _getFormFieldNames: function () {
    return this.get('type') === 'aggregate-intersection'
      ? AGGREGATE_INTERSECTION_FIELDS
      : INTERSECTION_FIELDS;
  },

  _formatAttrs: function (formAttrs) {
    var customFormattedFormAttrs = _.pick(formAttrs, ['id', 'source', 'target'].concat(this._getFormFieldNames().split(',')));
    return BaseAnalysisFormModel.prototype._formatAttrs.call(this, customFormattedFormAttrs);
  },

  getTemplate: function () {
    return template;
  },

  getTemplateData: function () {
    return {
      dataFields: this._getFormFieldNames()
    };
  },

  _filterSchemaFieldsByType: function (schema) {
    // Always include the source and target fields in addition to the type-specific fields
    return _.pick(schema, ['source', 'target'].concat(this._getFormFieldNames().split(',')));
  },

  /**
   * @override {BaseAnalysisFormModel._setSchema}
   */
  _setSchema: function () {
    BaseAnalysisFormModel.prototype._setSchema.call(this, this._filterSchemaFieldsByType({
      source: {
        type: 'Select',
        text: _t('editor.layers.analysis-form.source'),
        options: [ this.get('source') ],
        editorAttrs: { disabled: true }
      },
      target: {
        type: 'Select',
        title: _t('editor.layers.analysis-form.target'),
        options: this._getSourceOptionsForSource('target', '*'),
        validators: ['required'],
        editorAttrs: {
          disabled: this._isSourceDisabled('target')
        }
      },
      type: {
        type: 'Radio',
        title: _t('editor.layers.analysis-form.data-values'),
        options: [
          { label: 'Filter', val: 'intersection' },
          { label: 'Aggregate', val: 'aggregate-intersection' }
        ]
      },
      aggregate_column: {
        type: 'Select',
        title: _t('editor.layers.analysis-form.column'),
        options: this._columnOptions.filterByType('number'),
        validators: ['required']
      },
      aggregate_function: {
        type: 'Select',
        title: _t('editor.layers.analysis-form.operation'),
        options: ['count', 'sum', 'avg', 'min', 'max'],
        validators: ['required']
      }
    }));
  },

  _getTargetNodes: function () {
    var letter = this._layerDefinitionModel.get('letter');
    var layers = this._layerDefinitionModel.collection.reject(function (l) {
      return l.get('letter') === letter;
    });

    return _.chain(layers)
    .map(function (l) { return l.get('source'); })
    .compact()
    .sort()
    .value();
  },

  _isSourceDisabled: function (sourceAttrName) {
    return this._isPrimarySource(sourceAttrName) || this._isFetchingOptions();
  },

  _isPrimarySource: function (sourceAttrName) {
    return sourceAttrName === this.get('primary_source_name');
  },

  _isFetchingOptions: function () {
    return this._analysisSourceOptionsModel.get('fetching');
  },

  _getSourceOptionsForSource: function (sourceAttrName, requiredSimpleGeometryType) {
    var currentSource = this.get(sourceAttrName);

    if (this._isPrimarySource(sourceAttrName)) {
      return [currentSource];
    } else if (this._isFetchingOptions()) {
      return [{
        val: currentSource,
        label: 'loading…'
      }];
    } else {
      // fetched
      var sourceId = this._layerDefinitionModel.get('source');
      return this._analysisSourceOptionsModel
        .getSelectOptions(requiredSimpleGeometryType)
        .filter(function (d) {
          // Can't select own layer as source, so exclude it
          return d.val !== sourceId;
        });
    }
  },

  _onChange: function () {
    if (this.changed.target) {
      this._analysisSourceOptionsModel.createSourceNodeUnlessExisting(this.changed.target);
    }
  }
});
<commit_msg>Reorder binding<commit_after>var _ = require('underscore');
var BaseAnalysisFormModel = require('./base-analysis-form-model');
var template = require('./intersection-form.tpl');
var ColumnOptions = require('../column-options');

var AGGREGATE_INTERSECTION_FIELDS = 'type,aggregate_function,aggregate_column';
var INTERSECTION_FIELDS = 'type';
/**
 * Form model for the intersection analysis
 */
module.exports = BaseAnalysisFormModel.extend({
  initialize: function () {
    BaseAnalysisFormModel.prototype.initialize.apply(this, arguments);

    var nodeDefModel = this._layerDefinitionModel.findAnalysisDefinitionNodeModel(this.get('source'));

    this._columnOptions = new ColumnOptions({}, {
      nodeDefModel: nodeDefModel
    });

    this.listenTo(this._analysisSourceOptionsModel, 'change:fetching', this._setSchema);
    this.listenTo(this._columnOptions, 'columnsFetched', this._setSchema);

    this.on('change:type', this._setSchema, this);
    this.on('change', this._onChange, this);

    this._setSchema();
  },

  _getFormFieldNames: function () {
    return this.get('type') === 'aggregate-intersection'
      ? AGGREGATE_INTERSECTION_FIELDS
      : INTERSECTION_FIELDS;
  },

  _formatAttrs: function (formAttrs) {
    var customFormattedFormAttrs = _.pick(formAttrs, ['id', 'source', 'target'].concat(this._getFormFieldNames().split(',')));
    return BaseAnalysisFormModel.prototype._formatAttrs.call(this, customFormattedFormAttrs);
  },

  getTemplate: function () {
    return template;
  },

  getTemplateData: function () {
    return {
      dataFields: this._getFormFieldNames()
    };
  },

  _filterSchemaFieldsByType: function (schema) {
    // Always include the source and target fields in addition to the type-specific fields
    return _.pick(schema, ['source', 'target'].concat(this._getFormFieldNames().split(',')));
  },

  /**
   * @override {BaseAnalysisFormModel._setSchema}
   */
  _setSchema: function () {
    BaseAnalysisFormModel.prototype._setSchema.call(this, this._filterSchemaFieldsByType({
      source: {
        type: 'Select',
        text: _t('editor.layers.analysis-form.source'),
        options: [ this.get('source') ],
        editorAttrs: { disabled: true }
      },
      target: {
        type: 'Select',
        title: _t('editor.layers.analysis-form.target'),
        options: this._getSourceOptionsForSource('target', '*'),
        validators: ['required'],
        editorAttrs: {
          disabled: this._isSourceDisabled('target')
        }
      },
      type: {
        type: 'Radio',
        title: _t('editor.layers.analysis-form.data-values'),
        options: [
          { label: 'Filter', val: 'intersection' },
          { label: 'Aggregate', val: 'aggregate-intersection' }
        ]
      },
      aggregate_column: {
        type: 'Select',
        title: _t('editor.layers.analysis-form.column'),
        options: this._columnOptions.filterByType('number'),
        validators: ['required']
      },
      aggregate_function: {
        type: 'Select',
        title: _t('editor.layers.analysis-form.operation'),
        options: ['count', 'sum', 'avg', 'min', 'max'],
        validators: ['required']
      }
    }));
  },

  _getTargetNodes: function () {
    var letter = this._layerDefinitionModel.get('letter');
    var layers = this._layerDefinitionModel.collection.reject(function (l) {
      return l.get('letter') === letter;
    });

    return _.chain(layers)
    .map(function (l) { return l.get('source'); })
    .compact()
    .sort()
    .value();
  },

  _isSourceDisabled: function (sourceAttrName) {
    return this._isPrimarySource(sourceAttrName) || this._isFetchingOptions();
  },

  _isPrimarySource: function (sourceAttrName) {
    return sourceAttrName === this.get('primary_source_name');
  },

  _isFetchingOptions: function () {
    return this._analysisSourceOptionsModel.get('fetching');
  },

  _getSourceOptionsForSource: function (sourceAttrName, requiredSimpleGeometryType) {
    var currentSource = this.get(sourceAttrName);

    if (this._isPrimarySource(sourceAttrName)) {
      return [currentSource];
    } else if (this._isFetchingOptions()) {
      return [{
        val: currentSource,
        label: 'loading…'
      }];
    } else {
      // fetched
      var sourceId = this._layerDefinitionModel.get('source');
      return this._analysisSourceOptionsModel
        .getSelectOptions(requiredSimpleGeometryType)
        .filter(function (d) {
          // Can't select own layer as source, so exclude it
          return d.val !== sourceId;
        });
    }
  },

  _onChange: function () {
    if (this.changed.target) {
      this._analysisSourceOptionsModel.createSourceNodeUnlessExisting(this.changed.target);
    }
  }
});
<|endoftext|>


<commit_before> define(['app','underscore',
   '/app/views/forms/view/record-loader.directive.html.js',
   '/app/views/directives/document-list.partial.html.js',
   '/app/views/forms/view/view-abs-checkpoint.directive.js',
   '/app/views/forms/view/view-abs-checkpoint-communique.directive.js',
   '/app/views/forms/view/view-abs-permit.directive.js',
   '/app/views/forms/view/view-authority.directive.js',
   '/app/views/forms/view/view-authority-reference.directive.js',
   '/app/views/forms/view/view-contact.directive.js',
   '/app/views/forms/view/view-contact-reference.directive.js',
   '/app/views/forms/view/view-database.directive.js',
   '/app/views/forms/view/view-measure.directive.js',
   '/app/views/forms/view/view-organization.directive.js',
   '/app/views/forms/view/view-organization-reference.directive.js',
   '/app/views/forms/view/view-resource.directive.js',
   '/app/js/directives/angucomplete-extended.js',
   '/app/js/common.js', 'jqvmap', 'jqvmapworld',
   '/app/views/countries/country-map-list-directive.html.js',
   './countries-commonJS.js'
 ], function(app,_) {

   app.controller("ProfileController", ["$scope", "authHttp", "$routeParams", "linqjs", "$filter", "realm",
                "commonjs", "$q", '$element', '$timeout','countriescommonjs','IStorage',
     function($scope, $http, $routeParams, linqjs, $filter, realm, commonjs, $q,
                $element, $timeout, countriescommonjs, IStorage) {

       function resetList(){
           $scope.showCPCSent = true;
           $scope.showIRCC = true;
           $scope.showMSR = true;
           $scope.showContacts = true;
           $scope.showCPCRecv = true;
       }
       resetList();
       $scope.show = function(type) {
         if (type=='map' || type=='list') {
           $element.find('#countryDetails').slideUp('slow');
           $element.find('#worldMap').slideDown('slow');

         } else {
           $element.find('#worldMap').slideUp('slow');
           $element.find('#countryDetails').slideDown('slow');
           resetList()
         }

         $scope.$broadcast('showDetails', {data:type});
       }

       $scope.loadCountryDetails = function(countryCode) {

         $scope.code = countryCode || $routeParams.code;
         //fix for EU
         if($scope.code.toLowerCase() == 'eu')
            $scope.code = 'eur';

         $scope.documentCount = 0;
         $scope.currentPage = 0;
         $scope.searchText = '';
         $scope.autocompleteData = [];
         $scope.absch_nfp = null;
         //*******************************************************
         if ($scope.code) {
           $scope.show('profile');
           $http.get('/api/v2013/countries/' + $scope.code.toUpperCase(), {
             cache: true
           }).then(function(response) {
             $scope.country = response.data;
             $scope.searchText = '';
             $scope.autocompleteData = [];
             $scope.entryIntoForceDate = moment($scope.country.treaties.XXVII8b.deposit).add(90, 'days');
           });
           //*******************************************************
           var schema = [ "absPermit", "absCheckpoint", "absCheckpointCommunique", "authority", "measure", "database"]
           var schemQuery = ' (schema_s:' + schema.join(' OR schema_s:') + ' OR (schema_s:focalPoint AND (type_ss:NP-FP OR type_ss:ABS-IC)))';
           var queryURL = '/api/v2013/index/select?cb=1394816088237&fl=id,identifier_s,title_t,description_t,url_ss,schema_EN_t,date_dt,' +
                            'government_s,government_EN_t,schema_s,number_d,aichiTarget_ss,reference_s,sender_s,meeting_ss,recipient_ss,' +
                            'symbol_s,eventCity_EN_t,eventCountry_EN_t,startDate_s,endDate_s,body_s,code_s,meeting_s,group_s,function_t,' +
                            'department_t,organization_t,summary_EN_t,reportType_EN_t,completion_EN_t,jurisdiction_EN_t,development_EN_t' +
                            ',type_ss,email_ss,fax_ss,telephone_s,government_CEN_s,type_EN_t,status_EN_t,entryIntoForce_dt, usage_CEN_ss,keywords_CEN_ss,'+
                            'date_s,informedConsents_s,permit_ss,originCountries_CEN_ss,checkpoint_CEN_ss,createdDate_dt,geneticRessourceUsers_s'+
                            '' +
                            '&q=(realm_ss:' + realm.value.toLowerCase() + ' OR realm_ss:absch) AND ((' + schemQuery +
                            ' AND government_s:' + $scope.code.toLowerCase() + ') OR (originCountries_ss:'+
                            $scope.code.toLowerCase() + ' OR permitSourceCountry_ss:' + $scope.code.toLowerCase() + '))' +
                            '&rows=100&sort=createdDate_dt+desc,+title_t+asc&start=0&wt=json';
            var queryCPCRevURL = '/api/v2013/index/select?cb=1394816088237&fl=id,identifier_s,title_t,keywords_CEN_ss'+
                             'checkpoint_CEN_ss,createdDate_dt,geneticRessourceUsers_s,government_s,permit_ss,' +
                             '&q=(realm_ss:' + realm.value.toLowerCase() + ' OR realm_ss:absch) AND schema_s:absCheckpointCommunique AND (originCountries_ss:'+
                             $scope.code.toLowerCase() + ' OR permitSourceCountry_ss:' + $scope.code.toLowerCase() + ')' +
                             '&rows=100&sort=createdDate_dt+desc,+title_t+asc&start=0&wt=json';
           var queryProfile = $http.get(queryURL, {cache: true})
           var queryCPCRecv = $http.get(queryCPCRevURL, {cache: true})

           $q.all([queryProfile,queryCPCRecv])
            .then(function(results) {
             $scope.absch_nfp = results[0].data.response.docs;
             $scope.cpcReceived = results[1].data.response.docs;
              console.log($scope.absch_nfp);
              $scope.absch_nfp.forEach(function(document){

                  if(document.schema_s == "focalPoint" ){
                      document.description_t = document.description_t.replace(/\n/g, '
');
                  }
                  else if(document.schema_s == "authority" || document.schema_s == "database" ||
                     document.schema_s == "absCheckpoint"){
                         document.description_t = '';
                         $q.when(IStorage.documents.get(document.identifier_s))
                         .then(function(data) {
                             var doc = data.data
                             var details = '';
                            if(doc.address)
                                details += $filter("lstring")(doc.address) + '
';
                            if(doc.city)
                                details += $filter("lstring")(doc.city)  + '
';
                            if(doc.postalCode)
                                details += $filter("lstring")(doc.postalCode)  + '
';
                            if(document.government_CEN_s)
                                details += $filter("lstring")(JSON.parse(document.government_CEN_s));

                            document.description_t = details;
                            document.telephones = doc.phones
                            document.emails = doc.emails

                         });
                  }
                  else if(document.schema_s=="absCheckpointCommunique"){

                      if(document.geneticRessourceUsers_s){
                        document.geneticRessourceUsers = $scope.parseJSON(document.geneticRessourceUsers_s);
                      }
                    //   if(document.permit_ss){
                    //       document.permit = [];
                    //       _.each(document.permit_ss, function(permit){
                    //           $q.when(IStorage.documents.get(permit))
                    //               .then(function(data) {
                    //                   document.permit.push(data.data);
                    //            });
                      //
                    //       });
                    //   }
                  }

              });

              $scope.cpcReceived.forEach(function(document){
                  if(document.geneticRessourceUsers_s){
                    document.geneticRessourceUsers = $scope.parseJSON(document.geneticRessourceUsers_s);
                  }
              });

           });
         }
       }
       $scope.loadCountryDetails();

       $scope.$watch('absch_nfp', function(value) {

         if (!value) return;

         $scope.getFacets(value);

       });

       $scope.getFacets = function(data) {

         var linqObj = linqjs.from(data);
         $scope.nationalAuthority = linqObj.count(function(schema) {

           return schema.schema_s.toLowerCase() == 'authority';
         });
         //console.log(response.data.response.docs);
         $scope.nfpCount = linqObj.count(function(schema) {
           // console.log(schema.schema_EN_t.toLowerCase() + ' ' + 'national focal point'.toLowerCase());
           return schema.schema_s.toLowerCase() == 'focalpoint'.toLowerCase();
         });

         $scope.nationalMeasure = linqObj.count(function(schema) {
           return schema.schema_s.toLowerCase() == 'measure';
         });

         $scope.Permit = linqObj.count(function(schema) {
           return schema.schema_s.toLowerCase() == 'abspermit';
         });

         $scope.absCheckpoint = linqObj.count(function(schema) {
           return schema.schema_s.toLowerCase() == 'abscheckpoint';
         });

         $scope.absCheckpointCommunique = linqObj.count(function(schema) {
           return schema.schema_s.toLowerCase() == 'abscheckpointcommunique';
         });

         $scope.database = linqObj.count(function(schema) {
           return schema.schema_s.toLowerCase() == 'database';
         });
         $scope.resource = linqObj.count(function(schema) {
           return schema.schema_s.toLowerCase() == 'resource';
         });
       }

       $scope.$watch('searchText.$', function(value) {

         if (undefined == value || value == null || $scope.absch_nfp == null) return;
         $scope.getFacets($filter('filter')($scope.absch_nfp.response.docs, value));

       });

       $scope.showlist = false;

       $scope.$on('mapDetailsLoad', function(evt, data){
           $scope.mapDetails = data.mapDetails;
           $scope.type = 'party';
          if ($routeParams.code && $routeParams.code.toUpperCase() != 'RAT')
            $scope.show('profile');
          else
            $scope.show('map');
       })

       $scope.updateMap = function(type){

            $scope.type = type;
            if(type=='ratified')
                $scope.searchFilter=countriescommonjs.isRatified;
            else if(type=='inbetweenParty')
                $scope.searchFilter=countriescommonjs.isInbetweenParty;
            else if(type=='signatory')
                $scope.searchFilter=countriescommonjs.isSignatory;
            else if(type=='nonParties')
                $scope.searchFilter=countriescommonjs.isNonParties;
            else if(type=='party')
                $scope.searchFilter=countriescommonjs.isPartyToCBD;

            $scope.$broadcast('updateMap', {data:{'type':type,'searchFilter':$scope.searchFilter}});

       }
       $scope.countriescommonjs = countriescommonjs;
       $scope.$on('loadCountryProfile', function(evt, evtData){
           $scope.loadCountryDetails(evtData.data.countryCode);
       })

       $scope.isContactInformation = function(entity){

           return entity && (entity.schema_s == "focalPoint" ||
                    entity.schema_s == "authority" || entity.schema_s == "database" ||
                    entity.schema_s == "absCheckpoint")
       }

       $scope.isMeasure = function(entity){

           return entity && entity.schema_s == "measure";
       }
       $scope.isCheckpointCommunique = function(entity){

           return entity && entity.schema_s == "absCheckpointCommunique";
       }

      $scope.isPermit = function(entity){

          return entity && entity.schema_s == "absPermit";
      }

      $scope.isCheckpointCommuniqueReceived = function(entity){
          return entity && entity.schema_s == "absCheckpointCommunique"
          && (entity.originCountries_ss==$scope.code  || entity.permitSourceCountry_ss==$scope.code);
      }

       $scope.showDetails = function(document){
           //$scope.currentDocument = documentId;
           if(!document.data){
                var doc = IStorage.documents.get(document.identifier_s);
                var docInfo = IStorage.documents.get(document.identifier_s,{ info: true});
                $q.all([doc,docInfo])
                  .then(function(result){
                      document.data = result[0].data;
                      document.data.info = result[1].data;
                   });
            }
       };

       $scope.getTitle = function(schema,type, schemaFull){
           if(schema == 'focalPoint'){

                if(_.contains(type,'NP-FP'))
                    return 'Nagoya Protocol Focal Point';
                else if(_.contains(type,'ABS-IC'))
                    return 'Nagoya Protocol ICNP Focal Point';
                else if(_.contains(type,'CBD-FP1') ||  _.contains(type,'CBD-FP2'))
                    return 'CBD National Focal Point';
                else
                    return 'National Focal Point';
           }
           else
            return schemaFull;

       }

       $scope.parseJSON = function(value){
           if(value)
            return JSON.parse(value);
       }
     }
   ]);

 })
<commit_msg>fix EU<commit_after> define(['app','underscore',
   '/app/views/forms/view/record-loader.directive.html.js',
   '/app/views/directives/document-list.partial.html.js',
   '/app/views/forms/view/view-abs-checkpoint.directive.js',
   '/app/views/forms/view/view-abs-checkpoint-communique.directive.js',
   '/app/views/forms/view/view-abs-permit.directive.js',
   '/app/views/forms/view/view-authority.directive.js',
   '/app/views/forms/view/view-authority-reference.directive.js',
   '/app/views/forms/view/view-contact.directive.js',
   '/app/views/forms/view/view-contact-reference.directive.js',
   '/app/views/forms/view/view-database.directive.js',
   '/app/views/forms/view/view-measure.directive.js',
   '/app/views/forms/view/view-organization.directive.js',
   '/app/views/forms/view/view-organization-reference.directive.js',
   '/app/views/forms/view/view-resource.directive.js',
   '/app/js/directives/angucomplete-extended.js',
   '/app/js/common.js', 'jqvmap', 'jqvmapworld',
   '/app/views/countries/country-map-list-directive.html.js',
   './countries-commonJS.js'
 ], function(app,_) {

   app.controller("ProfileController", ["$scope", "authHttp", "$routeParams", "linqjs", "$filter", "realm",
                "commonjs", "$q", '$element', '$timeout','countriescommonjs','IStorage',
     function($scope, $http, $routeParams, linqjs, $filter, realm, commonjs, $q,
                $element, $timeout, countriescommonjs, IStorage) {

       function resetList(){
           $scope.showCPCSent = true;
           $scope.showIRCC = true;
           $scope.showMSR = true;
           $scope.showContacts = true;
           $scope.showCPCRecv = true;
       }
       resetList();
       $scope.show = function(type) {
         if (type=='map' || type=='list') {
           $element.find('#countryDetails').slideUp('slow');
           $element.find('#worldMap').slideDown('slow');

         } else {
           $element.find('#worldMap').slideUp('slow');
           $element.find('#countryDetails').slideDown('slow');
           resetList()
         }

         $scope.$broadcast('showDetails', {data:type});
       }

       $scope.loadCountryDetails = function(countryCode) {

         $scope.code = countryCode || $routeParams.code;

         $scope.documentCount = 0;
         $scope.currentPage = 0;
         $scope.searchText = '';
         $scope.autocompleteData = [];
         $scope.absch_nfp = null;
         //*******************************************************
         if ($scope.code) {
         //fix for EU
         if($scope.code.toLowerCase() == 'eu')
            $scope.code = 'eur';
           $scope.show('profile');
           $http.get('/api/v2013/countries/' + $scope.code.toUpperCase(), {
             cache: true
           }).then(function(response) {
             $scope.country = response.data;
             $scope.searchText = '';
             $scope.autocompleteData = [];
             $scope.entryIntoForceDate = moment($scope.country.treaties.XXVII8b.deposit).add(90, 'days');
           });
           //*******************************************************
           var schema = [ "absPermit", "absCheckpoint", "absCheckpointCommunique", "authority", "measure", "database"]
           var schemQuery = ' (schema_s:' + schema.join(' OR schema_s:') + ' OR (schema_s:focalPoint AND (type_ss:NP-FP OR type_ss:ABS-IC)))';
           var queryURL = '/api/v2013/index/select?cb=1394816088237&fl=id,identifier_s,title_t,description_t,url_ss,schema_EN_t,date_dt,' +
                            'government_s,government_EN_t,schema_s,number_d,aichiTarget_ss,reference_s,sender_s,meeting_ss,recipient_ss,' +
                            'symbol_s,eventCity_EN_t,eventCountry_EN_t,startDate_s,endDate_s,body_s,code_s,meeting_s,group_s,function_t,' +
                            'department_t,organization_t,summary_EN_t,reportType_EN_t,completion_EN_t,jurisdiction_EN_t,development_EN_t' +
                            ',type_ss,email_ss,fax_ss,telephone_s,government_CEN_s,type_EN_t,status_EN_t,entryIntoForce_dt, usage_CEN_ss,keywords_CEN_ss,'+
                            'date_s,informedConsents_s,permit_ss,originCountries_CEN_ss,checkpoint_CEN_ss,createdDate_dt,geneticRessourceUsers_s'+
                            '' +
                            '&q=(realm_ss:' + realm.value.toLowerCase() + ' OR realm_ss:absch) AND ((' + schemQuery +
                            ' AND government_s:' + $scope.code.toLowerCase() + ') OR (originCountries_ss:'+
                            $scope.code.toLowerCase() + ' OR permitSourceCountry_ss:' + $scope.code.toLowerCase() + '))' +
                            '&rows=100&sort=createdDate_dt+desc,+title_t+asc&start=0&wt=json';
            var queryCPCRevURL = '/api/v2013/index/select?cb=1394816088237&fl=id,identifier_s,title_t,keywords_CEN_ss'+
                             'checkpoint_CEN_ss,createdDate_dt,geneticRessourceUsers_s,government_s,permit_ss,' +
                             '&q=(realm_ss:' + realm.value.toLowerCase() + ' OR realm_ss:absch) AND schema_s:absCheckpointCommunique AND (originCountries_ss:'+
                             $scope.code.toLowerCase() + ' OR permitSourceCountry_ss:' + $scope.code.toLowerCase() + ')' +
                             '&rows=100&sort=createdDate_dt+desc,+title_t+asc&start=0&wt=json';
           var queryProfile = $http.get(queryURL, {cache: true})
           var queryCPCRecv = $http.get(queryCPCRevURL, {cache: true})

           $q.all([queryProfile,queryCPCRecv])
            .then(function(results) {
             $scope.absch_nfp = results[0].data.response.docs;
             $scope.cpcReceived = results[1].data.response.docs;
              console.log($scope.absch_nfp);
              $scope.absch_nfp.forEach(function(document){

                  if(document.schema_s == "focalPoint" ){
                      document.description_t = document.description_t.replace(/\n/g, '
');
                  }
                  else if(document.schema_s == "authority" || document.schema_s == "database" ||
                     document.schema_s == "absCheckpoint"){
                         document.description_t = '';
                         $q.when(IStorage.documents.get(document.identifier_s))
                         .then(function(data) {
                             var doc = data.data
                             var details = '';
                            if(doc.address)
                                details += $filter("lstring")(doc.address) + '
';
                            if(doc.city)
                                details += $filter("lstring")(doc.city)  + '
';
                            if(doc.postalCode)
                                details += $filter("lstring")(doc.postalCode)  + '
';
                            if(document.government_CEN_s)
                                details += $filter("lstring")(JSON.parse(document.government_CEN_s));

                            document.description_t = details;
                            document.telephones = doc.phones
                            document.emails = doc.emails

                         });
                  }
                  else if(document.schema_s=="absCheckpointCommunique"){

                      if(document.geneticRessourceUsers_s){
                        document.geneticRessourceUsers = $scope.parseJSON(document.geneticRessourceUsers_s);
                      }
                    //   if(document.permit_ss){
                    //       document.permit = [];
                    //       _.each(document.permit_ss, function(permit){
                    //           $q.when(IStorage.documents.get(permit))
                    //               .then(function(data) {
                    //                   document.permit.push(data.data);
                    //            });
                      //
                    //       });
                    //   }
                  }

              });

              $scope.cpcReceived.forEach(function(document){
                  if(document.geneticRessourceUsers_s){
                    document.geneticRessourceUsers = $scope.parseJSON(document.geneticRessourceUsers_s);
                  }
              });

           });
         }
       }
       $scope.loadCountryDetails();

       $scope.$watch('absch_nfp', function(value) {

         if (!value) return;

         $scope.getFacets(value);

       });

       $scope.getFacets = function(data) {

         var linqObj = linqjs.from(data);
         $scope.nationalAuthority = linqObj.count(function(schema) {

           return schema.schema_s.toLowerCase() == 'authority';
         });
         //console.log(response.data.response.docs);
         $scope.nfpCount = linqObj.count(function(schema) {
           // console.log(schema.schema_EN_t.toLowerCase() + ' ' + 'national focal point'.toLowerCase());
           return schema.schema_s.toLowerCase() == 'focalpoint'.toLowerCase();
         });

         $scope.nationalMeasure = linqObj.count(function(schema) {
           return schema.schema_s.toLowerCase() == 'measure';
         });

         $scope.Permit = linqObj.count(function(schema) {
           return schema.schema_s.toLowerCase() == 'abspermit';
         });

         $scope.absCheckpoint = linqObj.count(function(schema) {
           return schema.schema_s.toLowerCase() == 'abscheckpoint';
         });

         $scope.absCheckpointCommunique = linqObj.count(function(schema) {
           return schema.schema_s.toLowerCase() == 'abscheckpointcommunique';
         });

         $scope.database = linqObj.count(function(schema) {
           return schema.schema_s.toLowerCase() == 'database';
         });
         $scope.resource = linqObj.count(function(schema) {
           return schema.schema_s.toLowerCase() == 'resource';
         });
       }

       $scope.$watch('searchText.$', function(value) {

         if (undefined == value || value == null || $scope.absch_nfp == null) return;
         $scope.getFacets($filter('filter')($scope.absch_nfp.response.docs, value));

       });

       $scope.showlist = false;

       $scope.$on('mapDetailsLoad', function(evt, data){
           $scope.mapDetails = data.mapDetails;
           $scope.type = 'party';
          if ($routeParams.code && $routeParams.code.toUpperCase() != 'RAT')
            $scope.show('profile');
          else
            $scope.show('map');
       })

       $scope.updateMap = function(type){

            $scope.type = type;
            if(type=='ratified')
                $scope.searchFilter=countriescommonjs.isRatified;
            else if(type=='inbetweenParty')
                $scope.searchFilter=countriescommonjs.isInbetweenParty;
            else if(type=='signatory')
                $scope.searchFilter=countriescommonjs.isSignatory;
            else if(type=='nonParties')
                $scope.searchFilter=countriescommonjs.isNonParties;
            else if(type=='party')
                $scope.searchFilter=countriescommonjs.isPartyToCBD;

            $scope.$broadcast('updateMap', {data:{'type':type,'searchFilter':$scope.searchFilter}});

       }
       $scope.countriescommonjs = countriescommonjs;
       $scope.$on('loadCountryProfile', function(evt, evtData){
           $scope.loadCountryDetails(evtData.data.countryCode);
       })

       $scope.isContactInformation = function(entity){

           return entity && (entity.schema_s == "focalPoint" ||
                    entity.schema_s == "authority" || entity.schema_s == "database" ||
                    entity.schema_s == "absCheckpoint")
       }

       $scope.isMeasure = function(entity){

           return entity && entity.schema_s == "measure";
       }
       $scope.isCheckpointCommunique = function(entity){

           return entity && entity.schema_s == "absCheckpointCommunique";
       }

      $scope.isPermit = function(entity){

          return entity && entity.schema_s == "absPermit";
      }

      $scope.isCheckpointCommuniqueReceived = function(entity){
          return entity && entity.schema_s == "absCheckpointCommunique"
          && (entity.originCountries_ss==$scope.code  || entity.permitSourceCountry_ss==$scope.code);
      }

       $scope.showDetails = function(document){
           //$scope.currentDocument = documentId;
           if(!document.data){
                var doc = IStorage.documents.get(document.identifier_s);
                var docInfo = IStorage.documents.get(document.identifier_s,{ info: true});
                $q.all([doc,docInfo])
                  .then(function(result){
                      document.data = result[0].data;
                      document.data.info = result[1].data;
                   });
            }
       };

       $scope.getTitle = function(schema,type, schemaFull){
           if(schema == 'focalPoint'){

                if(_.contains(type,'NP-FP'))
                    return 'Nagoya Protocol Focal Point';
                else if(_.contains(type,'ABS-IC'))
                    return 'Nagoya Protocol ICNP Focal Point';
                else if(_.contains(type,'CBD-FP1') ||  _.contains(type,'CBD-FP2'))
                    return 'CBD National Focal Point';
                else
                    return 'National Focal Point';
           }
           else
            return schemaFull;

       }

       $scope.parseJSON = function(value){
           if(value)
            return JSON.parse(value);
       }
     }
   ]);

 })
<|endoftext|>


<commit_before>import { stripIndents } from 'common-tags';
import Vue from 'vue';

let app = null;

function renderRoot(options) {
  if (app) app.$destroy();

  app = new Vue(options);
}

export default function render({
  story,
  selectedKind,
  selectedStory,
  showMain,
  showError,
  showException,
}) {
  Vue.config.errorHandler = showException;

  const component = story();

  if (!component) {
    showError({
      title: `Expecting a Vue component from the story: "${selectedStory}" of "${selectedKind}".`,
      description: stripIndents`
        Did you forget to return the Vue component from the story?
        Use "() => ({ template: '<my-comp></my-comp>' })" or "() => ({ components: MyComp, template: '<my-comp></my-comp>' })" when defining the story.
      `,
    });
    return;
  }

  showMain();
  renderRoot({
    el: '#root',
    render(h) {
      return h('div', { attrs: { id: 'root' } }, [h(component)]);
    },
  });
}
<commit_msg>Add updateComponent function that will forceUpdate the last story instead of recreate it<commit_after>import { stripIndents } from 'common-tags';
import Vue from 'vue';

let root = null;

function updateComponent(component) {
  const [lastStory] = root.$children;

  if (!lastStory) {
    return false;
  }

  if (typeof component.data !== 'function') {
    return false;
  }

  const data = component.data();

  if (!data) {
    return false;
  }

  Object.entries(data).forEach(([key, value]) => {
    lastStory[key] = value;
  });

  lastStory.$forceUpdate();

  return true;
}

function renderRoot({ forceRender, component }) {
  if (root) {
    if (forceRender === true && updateComponent(component)) {
      return;
    }

    root.$destroy();
  }

  root = new Vue({
    el: '#root',
    render(h) {
      return h('div', { attrs: { id: 'root' } }, [h(component)]);
    },
  });
}

export default function render({
  story,
  selectedKind,
  selectedStory,
  showMain,
  showError,
  showException,
  forceRender,
}) {
  Vue.config.errorHandler = showException;

  const component = story();

  if (!component) {
    showError({
      title: `Expecting a Vue component from the story: "${selectedStory}" of "${selectedKind}".`,
      description: stripIndents`
        Did you forget to return the Vue component from the story?
        Use "() => ({ template: '<my-comp></my-comp>' })" or "() => ({ components: MyComp, template: '<my-comp></my-comp>' })" when defining the story.
      `,
    });
    return;
  }

  showMain();

  renderRoot({ forceRender, component });
}
<|endoftext|>


<commit_before>var InviteNewUserController = Ember.Controller.extend({
    //Used to set the initial value for the dropdown
    authorRole: Ember.computed(function () {
        var self = this;
        return this.store.find('role').then(function (roles) {
            var authorRole = roles.findBy('name', 'Author');
            //Initialize role as well.
            self.set('role', authorRole);
            self.set('authorRole', authorRole);
            return authorRole;
        });
    }),

    confirm: {
        accept: {
            text: 'send invitation now'
        },
        reject: {
            buttonClass: 'hidden'
        }
    },

    actions: {
        setRole: function (role) {
            this.set('role', role);
        },
        confirmAccept: function () {
            var email = this.get('email'),
                role = this.get('role'),
                self = this,
                newUser;

            newUser = self.store.createRecord('user', {
                email: email,
                status: 'invited',
                role: role
            });

            newUser.save().then(function () {
                var notificationText = 'Invitation sent! (' + email + ')';

                // If sending the invitation email fails, the API will still return a status of 201
                // but the user's status in the response object will be 'invited-pending'.
                if (newUser.get('status') === 'invited-pending') {
                    self.notifications.showWarn('Invitation email was not sent.  Please try resending.');
                } else {
                    self.notifications.showSuccess(notificationText);
                }
            }).catch(function (errors) {
                newUser.deleteRecord();
                self.notifications.showErrors(errors);
            }).finally(function () {
                //Reset
                self.set('email', '');
                self.set('role', self.get('authorRole'));
                //Make sure the modal closes on confirm, no matter the
                //method used to close it (enter in input vs Confirm click)
                self.send('closeModal');
            });
        },

        confirmReject: function () {
            return false;
        }
    }
});

export default InviteNewUserController;
<commit_msg>Close invite user modal immediately after submit.<commit_after>var InviteNewUserController = Ember.Controller.extend({
    //Used to set the initial value for the dropdown
    authorRole: Ember.computed(function () {
        var self = this;
        return this.store.find('role').then(function (roles) {
            var authorRole = roles.findBy('name', 'Author');
            //Initialize role as well.
            self.set('role', authorRole);
            self.set('authorRole', authorRole);
            return authorRole;
        });
    }),

    confirm: {
        accept: {
            text: 'send invitation now'
        },
        reject: {
            buttonClass: 'hidden'
        }
    },

    actions: {
        setRole: function (role) {
            this.set('role', role);
        },

        confirmAccept: function () {
            var email = this.get('email'),
                role = this.get('role'),
                self = this,
                newUser;

            // reset the form and close the modal
            self.set('email', '');
            self.set('role', self.get('authorRole'));
            self.send('closeModal');

            newUser = self.store.createRecord('user', {
                email: email,
                status: 'invited',
                role: role
            });

            newUser.save().then(function () {
                var notificationText = 'Invitation sent! (' + email + ')';

                // If sending the invitation email fails, the API will still return a status of 201
                // but the user's status in the response object will be 'invited-pending'.
                if (newUser.get('status') === 'invited-pending') {
                    self.notifications.showWarn('Invitation email was not sent.  Please try resending.');
                } else {
                    self.notifications.showSuccess(notificationText);
                }
            }).catch(function (errors) {
                newUser.deleteRecord();
                self.notifications.showErrors(errors);
            });
        },

        confirmReject: function () {
            return false;
        }
    }
});

export default InviteNewUserController;
<|endoftext|>