<commit_before>'use strict';

/**
 * Module dependencies.
 */
var
  util      = require('util'),
  cheerio   = require('cheerio'),
  request   = require('request'),
  Provider  = require('../../lib/provider');

var noop    = function () {};

var EPost = function () {
  Provider.call(this);
  this.id = 'epost';
  this.name = '우체국';
  this.source = 'website';
  this.TRACKING_REGEXP = /^[0-9]{13}$/;
};

util.inherits(EPost, Provider);

EPost.prototype.fetch = function (tracking, done) {
  done = done || noop;

  request({
    method: 'GET',
    url: 'https://service.epost.go.kr/trace.RetrieveDomRigiTraceList.comm',
    qs: {
      sid1: tracking,
      displayHeader: 'N'
    },
    timeout: 1000*30
  }, function (e, res, body) {
    if (e) { return done(e); }

    if (res.statusCode !== 200) {
      return done(new Error('response status isnt 200'));
    }

    done(null, body);
  });
};

EPost.prototype.parse = function (body, done) {
  done = done || noop;

  process.nextTick(function () {
    var $;

    try {
      $ = cheerio.load(body);
    } catch (e) {
      return done(e);
    }

    var
      $tables = $('table'),
      $overall = $tables.filter(function (index, el) {
        return ~$(el).find('th').first().text().indexOf('등기번호');
      }).find('td');

    if (~$overall.text().indexOf('배달정보를 찾지 못했습니다')) {
      return done(null, null);
    }

    if (!$overall.length) {
      return done(new Error('Cannot find element'));
    }

    var payload = {
      provider: {
        id: this.id,
        name: this.name,
        source: this.source
      },
      tracking: $overall.eq(0).text().trim(),
      remarks: $overall.eq(3).text().trim(),
      status: $overall.eq(4).text().trim()
    };

    [$overall.eq(1), $overall.eq(2)].forEach(function ($el) {
      $el.find('br').replaceWith('\n');
    });

    var
      sentChunks = $overall.eq(1).text().split('\n'),
      receivedChunks = $overall.eq(2).text().split('\n');

    payload.sender = sentChunks[0].trim();
    payload.sentAt = sentChunks[1].trim().replace(/[\/\.]/g, '-');
    payload.recipient = receivedChunks[0].trim();
    payload.receivedAt = receivedChunks[1].trim().replace(/[\/\.]/g, '-');

    payload.histories = $tables.filter(function (index, el) {
      return ~$(el).children('caption').text().indexOf('배송진행현황');
    }).find('tr').map(function (index, el) {
      var $columns = $(el).children('td');

      return {
        date: $columns.eq(0).text().trim().replace(/[\/\.]/g, '-') +
            ' ' + $columns.eq(1).text().trim(),
        location: $columns.eq(2).text().trim(),
        status: $columns.eq(3).text().replace(/\s+/g, ' ').trim()
      };
    }).get();

    done(null, payload);
  }.bind(this));
};

module.exports = exports = EPost;<commit_msg>epost/website: `histories.date` is now instance of `Date`<commit_after>'use strict';

/**
 * Module dependencies.
 */
var
  util      = require('util'),
  cheerio   = require('cheerio'),
  moment    = require('moment'),
  request   = require('request'),
  Provider  = require('../../lib/provider');

var noop    = function () {};

var EPost = function () {
  Provider.call(this);
  this.id = 'epost';
  this.name = '우체국';
  this.source = 'website';
  this.TRACKING_REGEXP = /^[0-9]{13}$/;
};

util.inherits(EPost, Provider);

EPost.prototype.fetch = function (tracking, done) {
  done = done || noop;

  request({
    method: 'GET',
    url: 'https://service.epost.go.kr/trace.RetrieveDomRigiTraceList.comm',
    qs: {
      sid1: tracking,
      displayHeader: 'N'
    },
    timeout: 1000*30
  }, function (e, res, body) {
    if (e) { return done(e); }

    if (res.statusCode !== 200) {
      return done(new Error('response status isnt 200'));
    }

    done(null, body);
  });
};

EPost.prototype.parse = function (body, done) {
  done = done || noop;

  process.nextTick(function () {
    var $;

    try {
      $ = cheerio.load(body);
    } catch (e) {
      return done(e);
    }

    var
      $tables = $('table'),
      $overall = $tables.filter(function (index, el) {
        return ~$(el).find('th').first().text().indexOf('등기번호');
      }).find('td');

    if (~$overall.text().indexOf('배달정보를 찾지 못했습니다')) {
      return done(null, null);
    }

    if (!$overall.length) {
      return done(new Error('Cannot find element'));
    }

    var payload = {
      provider: {
        id: this.id,
        name: this.name,
        source: this.source
      },
      tracking: $overall.eq(0).text().trim(),
      remarks: $overall.eq(3).text().trim(),
      status: $overall.eq(4).text().trim()
    };

    [$overall.eq(1), $overall.eq(2)].forEach(function ($el) {
      $el.find('br').replaceWith('\n');
    });

    var
      sentChunks = $overall.eq(1).text().split('\n'),
      receivedChunks = $overall.eq(2).text().split('\n');

    payload.sender = sentChunks[0].trim();
    payload.sentAt = sentChunks[1].trim().replace(/[\/\.]/g, '-');
    payload.recipient = receivedChunks[0].trim();
    payload.receivedAt = receivedChunks[1].trim().replace(/[\/\.]/g, '-');

    payload.histories = $tables.filter(function (index, el) {
      return ~$(el).children('caption').text().indexOf('배송진행현황');
    }).find('tr').map(function (index, el) {
      var $columns = $(el).children('td');
      var $columns = $(el).children('td'),
          _date = $columns.eq(0).text().trim().replace(/[\/\.]/g, '-') +
              ' ' + $columns.eq(1).text().trim();

      return {
        date: moment(_date, 'YYYY-MM-DD HH:mm').toDate(),
        location: $columns.eq(2).text().trim(),
        status: $columns.eq(3).text().replace(/\s+/g, ' ').trim()
      };
    }).get();

    done(null, payload);
  }.bind(this));
};

module.exports = exports = EPost;<|endoftext|>


<commit_before>mwUI.Backbone.Utils.concatUrlParts = function () {
  var urlParts = _.toArray(arguments), cleanedUrlParts = [];

  //remove empty strings
  urlParts = _.compact(urlParts);

  _.forEach(urlParts, function (url, index) {
    if (index === 0) {
      //remove only trailing slash
      url = url.replace(/\/$/g, '');
    } else {
      //Removing leading and trailing slash
      url = url.replace(/^\/|\/$/g, '');
    }
    cleanedUrlParts.push(url);
  });

  return cleanedUrlParts.join('/');
};<commit_msg>use short function with same name<commit_after>mwUI.Backbone.Utils.concatUrlParts = function () {
  var urlParts = _.toArray(arguments), cleanedUrlParts = [];

  //remove empty strings
  urlParts = _.compact(urlParts);

  _.each(urlParts, function (url, index) {
    if (index === 0) {
      //remove only trailing slash
      url = url.replace(/\/$/g, '');
    } else {
      //Removing leading and trailing slash
      url = url.replace(/^\/|\/$/g, '');
    }
    cleanedUrlParts.push(url);
  });

  return cleanedUrlParts.join('/');
};<|endoftext|>


<commit_before>(function ($) {

/*
*
*  provides feedback form for zammad
*

<button id="feedback-form">Feedback</button>

*/

  var pluginName = 'ZammadForm',
  defaults = {
    debug: false,
    noCSS: false,
    showTitle: false,
    messageTitle: 'Zammad Form',
    messageSubmit: 'Submit',
    messageThankYou: 'Thank you for your inquiry! We\'ll contact you soon as possible.',
    messageNoConfig: 'Unable to load form config from server. Maybe featrue is disabled.',
    attributes: [
      {
        display: 'Name',
        name: 'name',
        tag: 'input',
        type: 'text',
        placeholder: 'Your Name',
      },
      {
        display: 'Email',
        name: 'email',
        tag: 'input',
        type: 'email',
        placeholder: 'Your Email',
      },
      {
        display: 'Message',
        name: 'body',
        tag: 'textarea',
        placeholder: 'Your Message...',
        rows: 7,
      },
    ]
  };

  function Plugin(element, options) {
    this.element  = element;
    this.$element = $(element)

    this.options = $.extend({}, defaults, options);

    this._defaults = defaults;
    this._name     = pluginName;

    this._endpoint_config = '/api/v1/form_config'
    this._endpoint_submit = '/api/v1/form_submit'
    this._script_location = '/assets/form/form.js'
    this._css_location    = '/assets/form/form.css'

    this._src = document.getElementById('zammad_form_script').src
    this.css_location = this._src.replace(this._script_location, this._css_location)
    this.endpoint_config = this._src.replace(this._script_location, this._endpoint_config)
    this.endpoint_submit = this._src.replace(this._script_location, this._endpoint_submit)

    this._config = {}

    this.init();
  }

  Plugin.prototype.init = function () {
    var _this = this,
      params = {}

    _this.log('debug', 'init', this._src)

    if (!_this.options.noCSS) {
      _this.loadCss(_this.css_location)
    }

    _this.log('debug', 'endpoint_config: ' + _this.endpoint_config)
    _this.log('debug', 'endpoint_submit: ' + _this.endpoint_submit)

    // load config
    if (this.options.test) {
      params.test = true
    }
    $.ajax({
      url: _this.endpoint_config,
      data: params
    }).done(function(data) {
      _this.log('debug', 'config:', data)
      _this._config = data
    }).fail(function(jqXHR, textStatus, errorThrown) {
      if (jqXHR.status == 401) {
        _this.log('error', 'Faild to load form config, feature is disabled!')
      }
      else {
        _this.log('error', 'Faild to load form config!')
      }
      _this.noConfig()
    });

    // show form
    if (!this.options.modal) {
      _this.render()
    }

    // bind form on call
    else {
      this.$element.off('click.zammad-form').on('click.zammad-form', function (e) {
        e.preventDefault()
        _this.render()
        return true
      })
    }
  }

  // load css
  Plugin.prototype.loadCss = function(filename) {
    if (document.createStyleSheet) {
      document.createStyleSheet(filename)
    }
    else {
      $('<link rel="stylesheet" type="text/css" href="' + filename + '" />').appendTo('head')
    }
  }

  // send
  Plugin.prototype.submit = function() {
    var _this = this

    // check min modal open time
    if (_this.modalOpenTime) {
      var currentTime = new Date().getTime()
      var diff = currentTime - _this.modalOpenTime.getTime()
      _this.log('debug', 'currentTime', currentTime)
      _this.log('debug', 'modalOpenTime', _this.modalOpenTime.getTime())
      _this.log('debug', 'diffTime', diff)
      if (diff < 1000*8) {
        alert('Sorry, you look like an robot!')
        return
      }
    }

    // disable form
    _this.$form.find('button').prop('disabled', true)

    $.ajax({
      method: 'post',
      url: _this.endpoint_submit,
      data: _this.getParams(),
    }).done(function(data) {

      // removed errors
      _this.$form.find('.has-error').removeClass('has-error')

      // set errors
      if (data.errors) {
        $.each(data.errors, function( key, value ) {
          _this.$form.find('[name=' + key + ']').closest('.form-group').addClass('has-error')
        })
        _this.$form.find('button').prop('disabled', false)
        return
      }

      // ticket has been created
      _this.thanks()

    }).fail(function() {
      _this.$form.find('button').prop('disabled', false)
      alert('Faild to submit form!')
    });
  }

  // get params
  Plugin.prototype.getParams = function() {
    var _this = this,
      params = {}

    $.each( _this.$form.serializeArray(), function(index, item) {
      params[item.name] = item.value
    })

    if (!params.title) {
      params.title = this.options.messageTitle
    }

    if (this.options.test) {
      params.test = true
    }
    _this.log('debug', 'params', params)
    return params
  }

  Plugin.prototype.closeModal = function() {
    if (this.$modal) {
      this.$modal.remove()
    }
  }

  // render form
  Plugin.prototype.render = function(e) {
    var _this = this
    _this.closeModal()
    _this.modalOpenTime = new Date()
    _this.log('debug', 'modalOpenTime:', _this.modalOpenTime)

    var element = '
\

\

\
        <form class="zammad-form"></form>\

\

'

    if (!this.options.modal) {
      element = '
<form class="zammad-form"></form>
'
    }

    var $element = $(element)
    var $form = $element.find('form')
    if (this.options.showTitle && this.options.messageTitle != '') {
      $form.append('
' + this.options.messageTitle + '
')
    }
    $.each(this.options.attributes, function(index, value) {
      var item = $('
' + value.display + '
')
      if (value.tag == 'input') {
        item.append('<input class="form-control" name="' + value.name + '" type="' + value.type + '" placeholder="' + value.placeholder + '">')
      }
      else if (value.tag == 'textarea') {
        item.append('<textarea class="form-control" name="' + value.name + '" placeholder="' + value.placeholder + '" rows="' + value.rows + '"></textarea>')
      }
      $form.append(item)
    })
    $form.append('<button type="submit" class="btn">' + this.options.messageSubmit + '</button')

    this.$modal = $element
    this.$form  = $form

    // bind on close
    $element.find('.js-close').off('click.zammad-form').on('click.zammad-form', function (e) {
      e.preventDefault()
      _this.closeModal()
      return true
    })

    // bind form submit
    $element.off('submit.zammad-form').on('submit.zammad-form', function (e) {
      e.preventDefault()
      _this.submit()
      return true
    })

    // show form
    if (!this.options.modal) {
      _this.$element.html($element)
    }

    // append modal to body
    else {
      $('body').append($element)
    }

  }

  // thanks
  Plugin.prototype.thanks = function(e) {
    var message = $('
' + this.options.messageThankYou + '
')
    this.$form.html(message)
  }

  // unable to load config
  Plugin.prototype.noConfig = function(e) {
    var message = $('
' + this.options.messageNoConfig + '
')
    if (this.$form) {
      this.$form.html(message)
    }
    this.$element.html(message)
  }

  // log method
  Plugin.prototype.log = function() {
    var args = Array.prototype.slice.call(arguments)
    var level = args.shift()
    if (!this.options.debug && level == 'debug') {
      return
    }
    args.unshift(this._name + '||' + level)
    console.log.apply(console, args)

    var logString = ''
    $.each( args, function(index, item) {
      logString = logString + ' '
      if (typeof item == 'object') {
        logString = logString + JSON.stringify(item)
      }
      else if (item && item.toString) {
        logString = logString + item.toString()
      }
      else {
        logString = logString + item
      }
    })
    $('.js-logDisplay').prepend('
' + logString + '
')
  }

  $.fn[pluginName] = function (options) {
    return this.each(function () {
      var instance = $.data(this, 'plugin_' + pluginName)
      if (instance) {
        instance.$element.empty()
        $.data(this, 'plugin_' + pluginName, undefined)
      }
      $.data(
        this, 'plugin_' + pluginName,
        new Plugin(this, options)
      );
    });
  }

}(jQuery));<commit_msg>Added form css prefix support.<commit_after>(function ($) {

/*
*
*  provides feedback form for zammad
*

<button id="feedback-form">Feedback</button>

*/

  var pluginName = 'ZammadForm',
  defaults = {
    debug: false,
    noCSS: false,
    prefixCSS: 'zammad-form-',
    showTitle: false,
    messageTitle: 'Zammad Form',
    messageSubmit: 'Submit',
    messageThankYou: 'Thank you for your inquiry! We\'ll contact you soon as possible.',
    messageNoConfig: 'Unable to load form config from server. Maybe featrue is disabled.',
    attributes: [
      {
        display: 'Name',
        name: 'name',
        tag: 'input',
        type: 'text',
        placeholder: 'Your Name',
      },
      {
        display: 'Email',
        name: 'email',
        tag: 'input',
        type: 'email',
        placeholder: 'Your Email',
      },
      {
        display: 'Message',
        name: 'body',
        tag: 'textarea',
        placeholder: 'Your Message...',
        rows: 7,
      },
    ]
  };

  function Plugin(element, options) {
    this.element  = element;
    this.$element = $(element)

    this.options = $.extend({}, defaults, options);

    this._defaults = defaults;
    this._name     = pluginName;

    this._endpoint_config = '/api/v1/form_config'
    this._endpoint_submit = '/api/v1/form_submit'
    this._script_location = '/assets/form/form.js'
    this._css_location    = '/assets/form/form.css'

    this._src = document.getElementById('zammad_form_script').src
    this.css_location = this._src.replace(this._script_location, this._css_location)
    this.endpoint_config = this._src.replace(this._script_location, this._endpoint_config)
    this.endpoint_submit = this._src.replace(this._script_location, this._endpoint_submit)

    this._config = {}

    this.init();
  }

  Plugin.prototype.init = function () {
    var _this = this,
      params = {}

    _this.log('debug', 'init', this._src)

    if (!_this.options.noCSS) {
      _this.loadCss(_this.css_location)
    }

    _this.log('debug', 'endpoint_config: ' + _this.endpoint_config)
    _this.log('debug', 'endpoint_submit: ' + _this.endpoint_submit)

    // load config
    if (this.options.test) {
      params.test = true
    }
    $.ajax({
      url: _this.endpoint_config,
      data: params
    }).done(function(data) {
      _this.log('debug', 'config:', data)
      _this._config = data
    }).fail(function(jqXHR, textStatus, errorThrown) {
      if (jqXHR.status == 401) {
        _this.log('error', 'Faild to load form config, feature is disabled!')
      }
      else {
        _this.log('error', 'Faild to load form config!')
      }
      _this.noConfig()
    });

    // show form
    if (!this.options.modal) {
      _this.render()
    }

    // bind form on call
    else {
      this.$element.off('click.zammad-form').on('click.zammad-form', function (e) {
        e.preventDefault()
        _this.render()
        return true
      })
    }
  }

  // load css
  Plugin.prototype.loadCss = function(filename) {
    if (document.createStyleSheet) {
      document.createStyleSheet(filename)
    }
    else {
      $('<link rel="stylesheet" type="text/css" href="' + filename + '" />').appendTo('head')
    }
  }

  // send
  Plugin.prototype.submit = function() {
    var _this = this

    // check min modal open time
    if (_this.modalOpenTime) {
      var currentTime = new Date().getTime()
      var diff = currentTime - _this.modalOpenTime.getTime()
      _this.log('debug', 'currentTime', currentTime)
      _this.log('debug', 'modalOpenTime', _this.modalOpenTime.getTime())
      _this.log('debug', 'diffTime', diff)
      if (diff < 1000*8) {
        alert('Sorry, you look like an robot!')
        return
      }
    }

    // disable form
    _this.$form.find('button').prop('disabled', true)

    $.ajax({
      method: 'post',
      url: _this.endpoint_submit,
      data: _this.getParams(),
    }).done(function(data) {

      // removed errors
      _this.$form.find('.has-error').removeClass('has-error')

      // set errors
      if (data.errors) {
        $.each(data.errors, function( key, value ) {
          _this.$form.find('[name=' + key + ']').closest('.form-group').addClass('has-error')
        })
        _this.$form.find('button').prop('disabled', false)
        return
      }

      // ticket has been created
      _this.thanks()

    }).fail(function() {
      _this.$form.find('button').prop('disabled', false)
      alert('Faild to submit form!')
    });
  }

  // get params
  Plugin.prototype.getParams = function() {
    var _this = this,
      params = {}

    $.each( _this.$form.serializeArray(), function(index, item) {
      params[item.name] = item.value
    })

    if (!params.title) {
      params.title = this.options.messageTitle
    }

    if (this.options.test) {
      params.test = true
    }
    _this.log('debug', 'params', params)
    return params
  }

  Plugin.prototype.closeModal = function() {
    if (this.$modal) {
      this.$modal.remove()
    }
  }

  // render form
  Plugin.prototype.render = function(e) {
    var _this = this
    _this.closeModal()
    _this.modalOpenTime = new Date()
    _this.log('debug', 'modalOpenTime:', _this.modalOpenTime)

    var element = "
\

\

\
        <form class=\"zammad-form\"></form>\

\

"

    if (!this.options.modal) {
      element = '
<form class="zammad-form"></form>
'
    }

    var $element = $(element)
    var $form = $element.find('form')
    if (this.options.showTitle && this.options.messageTitle != '') {
      $form.append('
' + this.options.messageTitle + '
')
    }
    $.each(this.options.attributes, function(index, value) {
      var item = $('
' + value.display + '
')
      if (value.tag == 'input') {
        item.append('<input class="form-control" name="' + value.name + '" type="' + value.type + '" placeholder="' + value.placeholder + '">')
      }
      else if (value.tag == 'textarea') {
        item.append('<textarea class="form-control" name="' + value.name + '" placeholder="' + value.placeholder + '" rows="' + value.rows + '"></textarea>')
      }
      $form.append(item)
    })
    $form.append('<button type="submit" class="btn">' + this.options.messageSubmit + '</button')

    this.$modal = $element
    this.$form  = $form

    // bind on close
    $element.find('.js-close').off('click.zammad-form').on('click.zammad-form', function (e) {
      e.preventDefault()
      _this.closeModal()
      return true
    })

    // bind form submit
    $element.off('submit.zammad-form').on('submit.zammad-form', function (e) {
      e.preventDefault()
      _this.submit()
      return true
    })

    // show form
    if (!this.options.modal) {
      _this.$element.html($element)
    }

    // append modal to body
    else {
      $('body').append($element)
    }

  }

  // thanks
  Plugin.prototype.thanks = function(e) {
    var message = $('
' + this.options.messageThankYou + '
')
    this.$form.html(message)
  }

  // unable to load config
  Plugin.prototype.noConfig = function(e) {
    var message = $('
' + this.options.messageNoConfig + '
')
    if (this.$form) {
      this.$form.html(message)
    }
    this.$element.html(message)
  }

  // log method
  Plugin.prototype.log = function() {
    var args = Array.prototype.slice.call(arguments)
    var level = args.shift()
    if (!this.options.debug && level == 'debug') {
      return
    }
    args.unshift(this._name + '||' + level)
    console.log.apply(console, args)

    var logString = ''
    $.each( args, function(index, item) {
      logString = logString + ' '
      if (typeof item == 'object') {
        logString = logString + JSON.stringify(item)
      }
      else if (item && item.toString) {
        logString = logString + item.toString()
      }
      else {
        logString = logString + item
      }
    })
    $('.js-logDisplay').prepend('
' + logString + '
')
  }

  $.fn[pluginName] = function (options) {
    return this.each(function () {
      var instance = $.data(this, 'plugin_' + pluginName)
      if (instance) {
        instance.$element.empty()
        $.data(this, 'plugin_' + pluginName, undefined)
      }
      $.data(
        this, 'plugin_' + pluginName,
        new Plugin(this, options)
      );
    });
  }

}(jQuery));<|endoftext|>


<commit_before>angular.module('mwUI.Menu')

  .directive('mwMenuTopBar', function ($rootScope) {
    return {
      transclude: {
        'brand': '?img',
        'entries': '?div'
      },
      templateUrl: 'uikit/mw-menu/directives/templates/mw_menu_top_bar.html',
      require: '^?mwUi',
      link: function(scope, el, attrs, mwUiCtrl){
        if(mwUiCtrl){
          mwUiCtrl.addClass('has-mw-menu-top-bar');
        }

        scope.closeMenu = function () {
          var collapseEl = el.find('.navbar-collapse');

          if (collapseEl.hasClass('in')) {
            collapseEl.collapse('hide');
          }
        };

        var throttledCloseMenu = _.throttle(scope.closeMenu, 200),
          unBindLocationListener = $rootScope.$on('$locationChangeStart', throttledCloseMenu);

        angular.element(window).on('resize', throttledCloseMenu);

        scope.$on('$destroy', function(){
          unBindLocationListener();
          angular.element(window).off('resize', throttledCloseMenu);
          if(mwUiCtrl){
            mwUiCtrl.removeClass('has-mw-menu-top-bar');
          }
        });
      }
    };
  });<commit_msg>Indent code<commit_after>angular.module('mwUI.Menu')

  .directive('mwMenuTopBar', function ($rootScope) {
    return {
      transclude: {
        'brand': '?img',
        'entries': '?div'
      },
      templateUrl: 'uikit/mw-menu/directives/templates/mw_menu_top_bar.html',
      require: '^?mwUi',
      link: function (scope, el, attrs, mwUiCtrl) {
        if (mwUiCtrl) {
          mwUiCtrl.addClass('has-mw-menu-top-bar');
        }

        scope.closeMenu = function () {
          var collapseEl = el.find('.navbar-collapse');

          if (collapseEl.hasClass('in')) {
            collapseEl.collapse('hide');
          }
        };

        var throttledCloseMenu = _.throttle(scope.closeMenu, 200),
          unBindLocationListener = $rootScope.$on('$locationChangeStart', throttledCloseMenu);

        angular.element(window).on('resize', throttledCloseMenu);

        scope.$on('$destroy', function () {
          unBindLocationListener();
          angular.element(window).off('resize', throttledCloseMenu);
          if (mwUiCtrl) {
            mwUiCtrl.removeClass('has-mw-menu-top-bar');
          }
        });
      }
    };
  });<|endoftext|>


<commit_before><commit_msg>mark dialog containers for debuggability<commit_after><|endoftext|>


<commit_before>var diff = function(){

	// File lines (modified as program goes on)
	var f0,f1;

	// Insertions for files f0 and f1.
	// Contains a line number (after which a line insertion indicator
	// is placed)
	var ins0,ins1;

	// List of [line id, css class] to apply line styles
	var style;

	// List of associated ids or classes
	var assocs;

	// Initialization
	function init(){
		ins0 = [];
		ins1 = [];
		style = [];
		assocs = [];
	}

	// Load files to diff
	function load(file0, file1){
		init();
		f0 = file0.split("\n");
		f1 = file1.split("\n");
	}

	// Evaluate differences JSON object
	function evalDifferences(differences){
		for (var i = 0;i < differences.length;i++){

			var student = differences[i].student;
			var instructor = differences[i].instructor;

			assocs.push([]);
			markDifference(f0,ins0,student,i,"stu_");
			markDifference(f1,ins1,instructor,i,"ins_");

		}
	}

	// Change a line specified by difference object
	function markDifference(lines,ins, difference, changeID,id_prepend){
		assocs[changeID] = (assocs[changeID] || []);
		if (difference.line){
			var changes = difference.line;
			for (var i = 0;i < changes.length;i++){
				var change = changes[i];
				var line_id = "#" + id_prepend + "line" + change.line_number;
				if (change.line_number){
					if (!change.word_number){
						style.push([line_id, "bad-line"]);
						assocs[changeID].push(line_id);
					}else{
						// TODO Automate all these steps inside highlight.js
						var line = change.line_number;
						// Convert word range to multiple connected word ranges
						var subranges = enrange(change.word_number);
						// will contain all tags
						var surround = [];

						// Convert subranges to character ranges and add
						// surround tags
						for (var k = 0;k < subranges.length;k++){
							subranges[k] = word_to_character_range(lines[line], subranges[k]);
							surround.push(["",""]);
						}

						// tag all strings in string with desired elements
						lines[line] = tagString(lines[line], subranges, surround);
						assocs[changeID].push(".bad-seg-" + line);
					}
				}else{
					console.log("ERROR: NO LINE NUMBER IN DIFFERENCE");
				}
			}
		}else if (difference.start){
			ins.push(difference.start);
			console.log("#" + id_prepend + "ins" + difference.start);
			assocs[changeID].push("#" + id_prepend + "ins" + difference.start);
		}else{
			console.log("Couldn't interpret difference : ",difference);
		}
	}

	// Display files on page
	function display(){

		// Display lines from diff
		displayLines(f0,ins0,document.getElementById("diff0"),"stu_");
		displayLines(f1,ins1,document.getElementById("diff1"),"ins_");

		// Load generated css
		for (var i = 0;i < style.length;i++){
			$(style[i][0]).addClass(style[i][1]);
		}

		// Create association events
		for (var i = 0;i < assocs.length;i++){
			var selectors = assocs[i];
			setup_line_hover(selectors);
		}
	}

	// Setup line selectors for hover event
	function setup_line_hover(selectors){
		// Function called when group is hovered over
		var event_function_hover_on = function(e){
			for (var u = 0;u<selectors.length;u++){
				$(selectors[u]).addClass("line-hover");
			}
		};
		// Function called when group is no longer hovered over
		var event_function_hover_off = function(e){
			for (var u = 0;u<selectors.length;u++){
				$(selectors[u]).removeClass("line-hover");
			}
		};
		// Set each elements event
		for (var u = 0;u < selectors.length;u++){
			$(selectors[u]).hover(event_function_hover_on,
				event_function_hover_off);
		}
	}

	// Put lines in element on page
	function displayLines(lines,inserts, element, id_preprend){
		var html = "";
		var line_number = 0;
		for (var i = 0;i < lines.length;i++){
			if (inserts.indexOf(i) != -1){
				// html += "Insert
";
				html += "

";
			}else{
				html += "
"+(line_number+1)+"" + lines[i] + "
";
				line_number ++;
			}
		}
		element.innerHTML = html;
	}

	return {
		load : load,
		evalDifferences : evalDifferences,
		display : display
	};
}();
<commit_msg>diff complete - problem with test json files<commit_after>var diff = function(){

	// File lines (modified as program goes on)
	var f0,f1;

	// Insertions for files f0 and f1.
	// Contains a line number (after which a line insertion indicator
	// is placed)
	var ins0,ins1;

	// List of [line id, css class] to apply line styles
	var style;

	// List of associated ids or classes
	var assocs;

	// Initialization
	function init(){
		ins0 = [];
		ins1 = [];
		style = [];
		assocs = [];
	}

	// Load files to diff
	function load(file0, file1){
		init();
		f0 = file0.split("\n");
		f1 = file1.split("\n");
	}

	// Evaluate differences JSON object
	function evalDifferences(differences){
		for (var i = 0;i < differences.length;i++){

			var student = differences[i].student;
			var instructor = differences[i].instructor;

			assocs.push([]);
			markDifference(f0,ins0,student,i,"stu_");
			markDifference(f1,ins1,instructor,i,"ist_");

		}
	}

	// Change a line specified by difference object
	function markDifference(lines,ins, difference, changeID,id_prepend){
		assocs[changeID] = (assocs[changeID] || []);
		if (difference.line){
			var changes = difference.line;
			for (var i = 0;i < changes.length;i++){
				var change = changes[i];
				var line_id = "#" + id_prepend + "line" + change.line_number;
				if (change.line_number){
					if (!change.word_number){
						console.log(id_prepend,"Bad line at ",change.line_number);
						style.push([line_id, "bad-line"]);
						assocs[changeID].push(line_id);
					}else{
						// TODO Automate all these steps inside highlight.js
						var line = change.line_number;
						// Convert word range to multiple connected word ranges
						var subranges = enrange(change.word_number);
						// will contain all tags
						var surround = [];

						// Convert subranges to character ranges and add
						// surround tags
						for (var k = 0;k < subranges.length;k++){
							subranges[k] = word_to_character_range(lines[line], subranges[k]);
							surround.push(["",""]);
						}

						// tag all strings in string with desired elements
						lines[line] = tagString(lines[line], subranges, surround);
						assocs[changeID].push(".bad-seg-" + line);
					}
				}else{
					console.log("ERROR: NO LINE NUMBER IN DIFFERENCE");
				}
			}
		}else if (difference.start !== undefined){
			console.log(id_prepend,"Insert line at ",difference.start);
			// difference.start += ins.length;
			ins.push(difference.start);
			// console.log("#" + id_prepend + "ins" + difference.start);
			assocs[changeID].push("#" + id_prepend + "ins" + difference.start);
		}else{
			console.log("Couldn't interpret difference : ",difference);
		}
	}

	// Display files on page
	function display(){

		// Display lines from diff
		displayLines(f0,ins0,document.getElementById("diff0"),"stu_");
		displayLines(f1,ins1,document.getElementById("diff1"),"ist_");

		// Load generated css
		for (var i = 0;i < style.length;i++){
			console.log(style[i]);
			$(style[i][0]).addClass(style[i][1]);
		}

		// Create association events
		for (var i = 0;i < assocs.length;i++){
			var selectors = assocs[i];
			setup_line_hover(selectors);
		}
	}

	// Setup line selectors for hover event
	function setup_line_hover(selectors){
		// Function called when group is hovered over
		var event_function_hover_on = function(e){
			for (var u = 0;u<selectors.length;u++){
				$(selectors[u]).addClass("line-hover");
			}
		};
		// Function called when group is no longer hovered over
		var event_function_hover_off = function(e){
			for (var u = 0;u<selectors.length;u++){
				$(selectors[u]).removeClass("line-hover");
			}
		};
		// Set each elements event
		for (var u = 0;u < selectors.length;u++){
			$(selectors[u]).hover(event_function_hover_on,
				event_function_hover_off);
		}
	}

	// Put lines in element on page
	function displayLines(lines,inserts, element, id_preprend){
		var html = "";
		var line_number = 0;
		for (var i = 0;i < lines.length;i++){
			if (inserts.indexOf(i) != -1){
				// html += "Insert
";
				html += "

";
			}
			html += "
"+(line_number+1)+"" + lines[i] + "
";
			line_number ++;
		}
		element.innerHTML = html;
	}

	return {
		load : load,
		evalDifferences : evalDifferences,
		display : display
	};
}();
<|endoftext|>


<commit_before>var say = require('../../utils/say');
var global = require('../../global');

module.exports = function (unitPaymentOrder) {

    var items = unitPaymentOrder.items.map(unitPaymentOrderItem => {
        return unitPaymentOrderItem.unitReceiptNote.items.map(receiptNoteItem => {
            return {
                product: receiptNoteItem.product.name,
                prNo: receiptNoteItem.purchaseOrder.purchaseRequest.no,
                unitReceiptNoteNo: unitPaymentOrderItem.unitReceiptNote.no,
                quantity: receiptNoteItem.deliveredQuantity,
                uom: receiptNoteItem.deliveredUom.unit,
                price: receiptNoteItem.pricePerDealUnit
            };
        });
    });

    items = [].concat.apply([], items);

    var receiptNoteDates = unitPaymentOrder.items.map(unitPaymentOrderItem => {
        return new Date(unitPaymentOrderItem.unitReceiptNote.date)
    })
    var maxReceiptNoteDate = Math.max.apply(null, receiptNoteDates);

    var iso = "FM-PB-00-06-014/R1";
    var number = unitPaymentOrder.no;
    var currency = unitPaymentOrder.currency.code;
    var locale = global.config.locale;

    var moment = require('moment');
    moment.locale(locale.name);

    var initialValue = {
        price: 0,
        quntity: 0
    };

    var sum = (items.length > 0 ? items : [initialValue])
        .map(item => item.price * item.quantity)
        .reduce(function (prev, curr, index, arr) {
            return prev + curr;
        }, 0);

    var incomeTax = unitPaymentOrder.useIncomeTax ? sum * 0.1 : 0;
    var vat = unitPaymentOrder.useVat ? sum * (unitPaymentOrder.vatRate / 100) : 0;

    var header = [{
        columns: [
            {
                width: '40%',
                stack: [{
                    text: 'PT DAN LIRIS',
                    style: ['size20', 'bold']
                }, {
                        text: 'BANARAN, GROGOL, SUKOHARJO',
                        style: ['size08']
                    }]
            }, {
                width: '30%',
                columns: [{
                    width: '50%',
                    stack: [{
                        text: 'NOTA KREDIT',
                        style: ['size20', 'bold']
                    }, {
                            text: unitPaymentOrder.paymentMethod === 'KREDIT' ? '' : unitPaymentOrder.paymentMethod,
                            style: ['size08', 'center']
                        }]
                }]
            }, {
                width: '40%',
                columns: [{
                    width: '60%',
                    stack: [{
                        alignment: "left",
                        text: iso,
                        style: ['size08']
                    }, {
                            alignment: "left",
                            text: 'SUKOHARJO, ' + `${moment(unitPaymentOrder.date).format(locale.date.format)}`,
                            style: ['size08']
                        }, {
                            alignment: "left",
                            text: '( ' + unitPaymentOrder.supplier.code + ' )  ' + unitPaymentOrder.supplier.name,
                            style: ['size08']
                        }, {
                            alignment: "left",
                            text: unitPaymentOrder.supplier.address,
                            style: ['size08']
                        }
                    ]
                }]
            }
        ]
    }, '\n']

    var subHeader = [{
        columns: [
            {
                width: '60%',
                stack: [{
                    columns: [{
                        width: '25%',
                        text: "Nota Pembelian"
                    }, {
                            width: '5%',
                            text: ":"
                        }, {
                            width: '*',
                            text: unitPaymentOrder.category.name
                        }],
                    style: ['size08']
                }, {
                        columns: [{
                            width: '25%',
                            text: "Untuk"
                        }, {
                                width: '5%',
                                text: ":"
                            }, {
                                width: '*',
                                text: unitPaymentOrder.division.name
                            }],
                        style: ['size08']
                    }
                ]
            },
            {
                width: '10%',
                text: ''
            },
            {
                width: '40%',
                columns: [{
                    width: '10%',
                    text: 'Nomor '
                }, {
                        width: '5%',
                        text: ': '
                    }, {
                        width: '*',
                        text: number
                    }],
                style: ['size08']
            }
        ]
    }, '\n'];

    var line = [{
        canvas: [{
            type: 'line',
            x1: 0,
            y1: 5,
            x2: 378,
            y2: 5,
            lineWidth: 0.5
        }
        ]
    }, '\n'];

    var thead = [
        {
            text: 'No.',
            style: 'tableHeader'
        }, {
            text: 'Nama Barang',
            style: 'tableHeader'
        }, {
            text: 'Jumlah',
            style: 'tableHeader'
        }, {
            text: 'Harga Satuan',
            style: 'tableHeader'
        }, {
            text: 'Harga Total',
            style: 'tableHeader'
        },
        {
            text: 'Nomor Order',
            style: 'tableHeader'
        },
        {
            text: 'Nomor Bon Unit',
            style: 'tableHeader'
        }
    ];

    var tbody = items.map(function (item, index) {
        return [{
            text: (index + 1).toString() || '',
            style: ['size08', 'center']
        }, {
                text: item.product,
                style: ['size08', 'left']
            }, {
                text: item.quantity + ' ' + item.uom,
                style: ['size08', 'right']
            }, {
                columns: [{
                    width: '10%',
                    text: `${currency}`
                }, {
                        width: '*',
                        text: item.price.toLocaleString(locale, locale.currencyNotaItern2),
                        style: ['right']
                    }],
                style: ['size08']
            }, {
                columns: [{
                    width: '10%',
                    text: `${currency}`
                }, {
                        width: '*',
                        text: parseFloat(item.price * item.quantity).toLocaleString(locale, locale.currencyNotaItern),
                        style: ['right']
                    }],
                style: ['size08']
            }, {
                text: item.prNo,
                style: ['size08', 'center']
            }, {
                text: item.unitReceiptNoteNo,
                style: ['size08', 'center']
            }];
    });

    tbody = tbody.length > 0 ? tbody : [
        [{
            text: "tidak ada barang",
            style: ['size08', 'center'],
            colSpan: 7
        }, "", "", "", "", ""]
    ];

    var table = [{
        table: {
            widths: ['5%', '25%', '10%', '15%', '17%', '15%', '13%'],
            headerRows: 1,
            body: [].concat([thead], tbody)
        }
    }];

    var closing = ['\n',
        {
            columns: [
                {
                    width: '40%',
                    stack: ['\n',
                        {
                            columns: [{
                                width: '50%',
                                text: unitPaymentOrder.useVat ? `PPh ${unitPaymentOrder.vat.name} ${unitPaymentOrder.vatRate} %` : ""
                            },
                                {
                                    width: '5%',
                                    text: unitPaymentOrder.useVat ? ":" : ""
                                },
                                {
                                    width: '10%',
                                    text: unitPaymentOrder.useVat ? currency : ""
                                },
                                {
                                    width: '*',
                                    text: unitPaymentOrder.useVat ? parseFloat(Math.round(vat * 100) / 100).toLocaleString(locale, locale.currencyNotaItern) : "",
                                    style: 'right'
                                }]
                        }, {
                            columns: [{
                                width: '50%',
                                text: unitPaymentOrder.useVat ? "Jumlah dibayar Ke Supplier" : ""
                            },
                                {
                                    width: '5%',
                                    text: unitPaymentOrder.useVat ? ":" : ""
                                },
                                {
                                    width: '10%',
                                    text: unitPaymentOrder.useVat ? currency : ""
                                },
                                {
                                    width: '*',
                                    text: unitPaymentOrder.useVat ?parseFloat(Math.round(((sum + incomeTax) - vat) * 100) / 100).toLocaleString(locale, locale.currencyNotaItern) : "",
                                    style: 'right'
                                }]
                        }]
                },
                {
                    width: '20%',
                    text: ''
                },
                {
                    width: '40%',
                    stack: [
                        {
                            columns: [{
                                width: '45%',
                                text: "Jumlah . . . . . . . . . . . . . . ."
                            },
                                {
                                    width: '10%',
                                    text: currency
                                },
                                {
                                    width: '*',
                                    text: parseFloat(Math.round(sum * 100) / 100).toLocaleString(locale, locale.currencyNotaItern),
                                    style: 'right'
                                }]
                        }, {
                            columns: [{
                                width: '45%',
                                text: "PPn 10 %. . . . . . . . . . . . . ."
                            },
                                {
                                    width: '10%',
                                    text: unitPaymentOrder.useIncomeTax ? currency : '-'
                                },
                                {
                                    width: '*',
                                    text: unitPaymentOrder.useIncomeTax ? parseFloat(Math.round(incomeTax * 100) / 100).toLocaleString(locale, locale.currencyNotaItern) : '',
                                    style: 'right'
                                }]
                        }, {
                            columns: [{
                                width: '45%',
                                text: "T O T A L. . . . . . . . . . . . . ."
                            },
                                {
                                    width: '10%',
                                    text: currency
                                },
                                {
                                    width: '*',
                                    text: parseFloat(Math.round((sum + incomeTax) * 100) / 100).toLocaleString(locale, locale.currencyNotaItern),
                                    style: 'right'
                                }]
                        }]
                }
            ],
            style: ['size08']
        }, '\n',
        {
            width: '25%',
            text: `Terbilang : ${say((sum + incomeTax) - vat,unitPaymentOrder.currency.description)}`,
            style: ['size09', 'bold']
        }, '\n',
        {
            columns: [
                {
                    width: '50%',
                    stack: [
                        {
                            columns: [{
                                width: '40%',
                                text: "Perjanjian Pembayaran"
                            },
                                {
                                    width: '5%',
                                    text: ":"
                                },
                                {
                                    width: '*',
                                    text: moment(unitPaymentOrder.dueDate).format(locale.date.format)
                                }]
                        }, {
                            columns: [{
                                width: '40%',
                                text: "Invoice"
                            },
                                {
                                    width: '5%',
                                    text: ":"
                                },
                                {
                                    width: '*',
                                    text: unitPaymentOrder.invoceNo + ', ' + moment(unitPaymentOrder.invoceDate).format(locale.date.format) || '-'
                                }]
                        }, {
                            columns: [{
                                width: '40%',
                                text: "Ket."
                            },
                                {
                                    width: '5%',
                                    text: ":"
                                },
                                {
                                    width: '*',
                                    text: unitPaymentOrder.remark || '-'
                                }]
                        }]
                },
                {
                    width: '10%',
                    text: ''
                },
                {
                    width: '40%',
                    stack: [
                        {
                            columns: [{
                                width: '45%',
                                text: "Barang Datang"
                            },
                                {
                                    width: '5%',
                                    text: ":"
                                },
                                {
                                    width: '*',
                                    text: moment(maxReceiptNoteDate).format(locale.date.format)
                                }]
                        }, {
                            columns: [{
                                width: '45%',
                                text: "Nomor Faktur Pajak PPN"
                            },
                                {
                                    width: '5%',
                                    text: ":"
                                },
                                {
                                    width: '*',
                                    text: unitPaymentOrder.incomeTaxNo || '-'
                                }]
                        }, {
                            columns: [{
                                width: '45%',
                                text: "Pembayaran"
                            },
                                {
                                    width: '5%',
                                    text: ":"
                                },
                                {
                                    width: '*',
                                    text: unitPaymentOrder.paymentMethod || ''
                                }]
                        }]
                }
            ],
            style: ['size08']
        }
    ];

    var footer = ['\n', {
        columns: [{
            width: '25%',
            stack: ['Diperiksa,', 'Verifikasi', '\n\n\n\n', '(                               )'],
            style: ['center']
        }, {
                width: '25%',
                stack: ['Mengetahui,', 'Pimpinan Bagian', '\n\n\n\n', '(                               )'],
                style: ['center']
            }, {
                width: '25%',
                stack: ['Tanda Terima,', 'Bagian Pembelian', '\n\n\n\n', '(                               )'],
                style: ['center']
            }, {
                width: '25%',
                stack: ['Dibuat Oleh,', ' ', '\n\n\n\n', `(  ${unitPaymentOrder._createdBy}  )`],
                style: ['center']
            }],
        style: ['size08']
    }];

    var dd = {
        pageSize: 'A5',
        pageOrientation: 'landscape',
        pageMargins: 20,
        content: [].concat(header, subHeader, table, closing, footer),
        styles: {
            size06: {
                fontSize: 6
            },
            size07: {
                fontSize: 7
            },
            size08: {
                fontSize: 8
            },
            size09: {
                fontSize: 9
            },
            size10: {
                fontSize: 10
            },
            size15: {
                fontSize: 15
            },
            bold: {
                bold: true
            },
            center: {
                alignment: 'center'
            },
            left: {
                alignment: 'left'
            },
            right: {
                alignment: 'right'
            },
            justify: {
                alignment: 'justify'
            },
            tableHeader: {
                bold: true,
                fontSize: 8,
                color: 'black',
                alignment: 'center'
            }
        }
    };

    return dd;
}<commit_msg>update columns currency<commit_after>var say = require('../../utils/say');
var global = require('../../global');

module.exports = function (unitPaymentOrder) {

    var items = unitPaymentOrder.items.map(unitPaymentOrderItem => {
        return unitPaymentOrderItem.unitReceiptNote.items.map(receiptNoteItem => {
            return {
                product: receiptNoteItem.product.name,
                prNo: receiptNoteItem.purchaseOrder.purchaseRequest.no,
                unitReceiptNoteNo: unitPaymentOrderItem.unitReceiptNote.no,
                quantity: receiptNoteItem.deliveredQuantity,
                uom: receiptNoteItem.deliveredUom.unit,
                price: receiptNoteItem.pricePerDealUnit
            };
        });
    });

    items = [].concat.apply([], items);

    var receiptNoteDates = unitPaymentOrder.items.map(unitPaymentOrderItem => {
        return new Date(unitPaymentOrderItem.unitReceiptNote.date)
    })
    var maxReceiptNoteDate = Math.max.apply(null, receiptNoteDates);

    var iso = "FM-PB-00-06-014/R1";
    var number = unitPaymentOrder.no;
    var currency = unitPaymentOrder.currency.code;
    var locale = global.config.locale;

    var moment = require('moment');
    moment.locale(locale.name);

    var initialValue = {
        price: 0,
        quntity: 0
    };

    var sum = (items.length > 0 ? items : [initialValue])
        .map(item => item.price * item.quantity)
        .reduce(function (prev, curr, index, arr) {
            return prev + curr;
        }, 0);

    var incomeTax = unitPaymentOrder.useIncomeTax ? sum * 0.1 : 0;
    var vat = unitPaymentOrder.useVat ? sum * (unitPaymentOrder.vatRate / 100) : 0;

    var header = [{
        columns: [
            {
                width: '40%',
                stack: [{
                    text: 'PT DAN LIRIS',
                    style: ['size20', 'bold']
                }, {
                        text: 'BANARAN, GROGOL, SUKOHARJO',
                        style: ['size08']
                    }]
            }, {
                width: '30%',
                columns: [{
                    width: '50%',
                    stack: [{
                        text: 'NOTA KREDIT',
                        style: ['size20', 'bold']
                    }, {
                            text: unitPaymentOrder.paymentMethod === 'KREDIT' ? '' : unitPaymentOrder.paymentMethod,
                            style: ['size08', 'center']
                        }]
                }]
            }, {
                width: '40%',
                columns: [{
                    width: '60%',
                    stack: [{
                        alignment: "left",
                        text: iso,
                        style: ['size08']
                    }, {
                            alignment: "left",
                            text: 'SUKOHARJO, ' + `${moment(unitPaymentOrder.date).format(locale.date.format)}`,
                            style: ['size08']
                        }, {
                            alignment: "left",
                            text: '( ' + unitPaymentOrder.supplier.code + ' )  ' + unitPaymentOrder.supplier.name,
                            style: ['size08']
                        }, {
                            alignment: "left",
                            text: unitPaymentOrder.supplier.address,
                            style: ['size08']
                        }
                    ]
                }]
            }
        ]
    }, '\n']

    var subHeader = [{
        columns: [
            {
                width: '60%',
                stack: [{
                    columns: [{
                        width: '25%',
                        text: "Nota Pembelian"
                    }, {
                            width: '5%',
                            text: ":"
                        }, {
                            width: '*',
                            text: unitPaymentOrder.category.name
                        }],
                    style: ['size08']
                }, {
                        columns: [{
                            width: '25%',
                            text: "Untuk"
                        }, {
                                width: '5%',
                                text: ":"
                            }, {
                                width: '*',
                                text: unitPaymentOrder.division.name
                            }],
                        style: ['size08']
                    }
                ]
            },
            {
                width: '10%',
                text: ''
            },
            {
                width: '40%',
                columns: [{
                    width: '10%',
                    text: 'Nomor '
                }, {
                        width: '5%',
                        text: ': '
                    }, {
                        width: '*',
                        text: number
                    }],
                style: ['size08']
            }
        ]
    }, '\n'];

    var line = [{
        canvas: [{
            type: 'line',
            x1: 0,
            y1: 5,
            x2: 378,
            y2: 5,
            lineWidth: 0.5
        }
        ]
    }, '\n'];

    var thead = [
        {
            text: 'No.',
            style: 'tableHeader'
        }, {
            text: 'Nama Barang',
            style: 'tableHeader'
        }, {
            text: 'Jumlah',
            style: 'tableHeader'
        }, {
            text: 'Harga Satuan',
            style: 'tableHeader'
        }, {
            text: 'Harga Total',
            style: 'tableHeader'
        },
        {
            text: 'Nomor Order',
            style: 'tableHeader'
        },
        {
            text: 'Nomor Bon Unit',
            style: 'tableHeader'
        }
    ];

    var tbody = items.map(function (item, index) {
        return [{
            text: (index + 1).toString() || '',
            style: ['size08', 'center']
        }, {
                text: item.product,
                style: ['size08', 'left']
            }, {
                text: item.quantity + ' ' + item.uom,
                style: ['size08', 'right']
            }, {
                columns: [{
                    width: '20%',
                    text: `${currency}`
                }, {
                        width: '*',
                        text: item.price.toLocaleString(locale, locale.currencyNotaItern2),
                        style: ['right']
                    }],
                style: ['size08']
            }, {
                columns: [{
                    width: '20%',
                    text: `${currency}`
                }, {
                        width: '*',
                        text: parseFloat(item.price * item.quantity).toLocaleString(locale, locale.currencyNotaItern),
                        style: ['right']
                    }],
                style: ['size08']
            }, {
                text: item.prNo,
                style: ['size08', 'center']
            }, {
                text: item.unitReceiptNoteNo,
                style: ['size08', 'center']
            }];
    });

    tbody = tbody.length > 0 ? tbody : [
        [{
            text: "tidak ada barang",
            style: ['size08', 'center'],
            colSpan: 7
        }, "", "", "", "", ""]
    ];

    var table = [{
        table: {
            widths: ['5%', '25%', '10%', '15%', '17%', '15%', '13%'],
            headerRows: 1,
            body: [].concat([thead], tbody)
        }
    }];

    var closing = ['\n',
        {
            columns: [
                {
                    width: '40%',
                    stack: ['\n',
                        {
                            columns: [{
                                width: '50%',
                                text: unitPaymentOrder.useVat ? `PPh ${unitPaymentOrder.vat.name} ${unitPaymentOrder.vatRate} %` : ""
                            },
                                {
                                    width: '5%',
                                    text: unitPaymentOrder.useVat ? ":" : ""
                                },
                                {
                                    width: '10%',
                                    text: unitPaymentOrder.useVat ? currency : ""
                                },
                                {
                                    width: '*',
                                    text: unitPaymentOrder.useVat ? parseFloat(Math.round(vat * 100) / 100).toLocaleString(locale, locale.currencyNotaItern) : "",
                                    style: 'right'
                                }]
                        }, {
                            columns: [{
                                width: '50%',
                                text: unitPaymentOrder.useVat ? "Jumlah dibayar Ke Supplier" : ""
                            },
                                {
                                    width: '5%',
                                    text: unitPaymentOrder.useVat ? ":" : ""
                                },
                                {
                                    width: '10%',
                                    text: unitPaymentOrder.useVat ? currency : ""
                                },
                                {
                                    width: '*',
                                    text: unitPaymentOrder.useVat ?parseFloat(Math.round(((sum + incomeTax) - vat) * 100) / 100).toLocaleString(locale, locale.currencyNotaItern) : "",
                                    style: 'right'
                                }]
                        }]
                },
                {
                    width: '20%',
                    text: ''
                },
                {
                    width: '40%',
                    stack: [
                        {
                            columns: [{
                                width: '45%',
                                text: "Jumlah . . . . . . . . . . . . . . ."
                            },
                                {
                                    width: '10%',
                                    text: currency
                                },
                                {
                                    width: '*',
                                    text: parseFloat(Math.round(sum * 100) / 100).toLocaleString(locale, locale.currencyNotaItern),
                                    style: 'right'
                                }]
                        }, {
                            columns: [{
                                width: '45%',
                                text: "PPn 10 %. . . . . . . . . . . . . ."
                            },
                                {
                                    width: '10%',
                                    text: unitPaymentOrder.useIncomeTax ? currency : '-'
                                },
                                {
                                    width: '*',
                                    text: unitPaymentOrder.useIncomeTax ? parseFloat(Math.round(incomeTax * 100) / 100).toLocaleString(locale, locale.currencyNotaItern) : '',
                                    style: 'right'
                                }]
                        }, {
                            columns: [{
                                width: '45%',
                                text: "T O T A L. . . . . . . . . . . . . ."
                            },
                                {
                                    width: '10%',
                                    text: currency
                                },
                                {
                                    width: '*',
                                    text: parseFloat(Math.round((sum + incomeTax) * 100) / 100).toLocaleString(locale, locale.currencyNotaItern),
                                    style: 'right'
                                }]
                        }]
                }
            ],
            style: ['size08']
        }, '\n',
        {
            width: '25%',
            text: `Terbilang : ${say((sum + incomeTax) - vat,unitPaymentOrder.currency.description)}`,
            style: ['size09', 'bold']
        }, '\n',
        {
            columns: [
                {
                    width: '50%',
                    stack: [
                        {
                            columns: [{
                                width: '40%',
                                text: "Perjanjian Pembayaran"
                            },
                                {
                                    width: '5%',
                                    text: ":"
                                },
                                {
                                    width: '*',
                                    text: moment(unitPaymentOrder.dueDate).format(locale.date.format)
                                }]
                        }, {
                            columns: [{
                                width: '40%',
                                text: "Invoice"
                            },
                                {
                                    width: '5%',
                                    text: ":"
                                },
                                {
                                    width: '*',
                                    text: unitPaymentOrder.invoceNo + ', ' + moment(unitPaymentOrder.invoceDate).format(locale.date.format) || '-'
                                }]
                        }, {
                            columns: [{
                                width: '40%',
                                text: "Ket."
                            },
                                {
                                    width: '5%',
                                    text: ":"
                                },
                                {
                                    width: '*',
                                    text: unitPaymentOrder.remark || '-'
                                }]
                        }]
                },
                {
                    width: '10%',
                    text: ''
                },
                {
                    width: '40%',
                    stack: [
                        {
                            columns: [{
                                width: '45%',
                                text: "Barang Datang"
                            },
                                {
                                    width: '5%',
                                    text: ":"
                                },
                                {
                                    width: '*',
                                    text: moment(maxReceiptNoteDate).format(locale.date.format)
                                }]
                        }, {
                            columns: [{
                                width: '45%',
                                text: "Nomor Faktur Pajak PPN"
                            },
                                {
                                    width: '5%',
                                    text: ":"
                                },
                                {
                                    width: '*',
                                    text: unitPaymentOrder.incomeTaxNo || '-'
                                }]
                        }, {
                            columns: [{
                                width: '45%',
                                text: "Pembayaran"
                            },
                                {
                                    width: '5%',
                                    text: ":"
                                },
                                {
                                    width: '*',
                                    text: unitPaymentOrder.paymentMethod || ''
                                }]
                        }]
                }
            ],
            style: ['size08']
        }
    ];

    var footer = ['\n', {
        columns: [{
            width: '25%',
            stack: ['Diperiksa,', 'Verifikasi', '\n\n\n\n', '(                               )'],
            style: ['center']
        }, {
                width: '25%',
                stack: ['Mengetahui,', 'Pimpinan Bagian', '\n\n\n\n', '(                               )'],
                style: ['center']
            }, {
                width: '25%',
                stack: ['Tanda Terima,', 'Bagian Pembelian', '\n\n\n\n', '(                               )'],
                style: ['center']
            }, {
                width: '25%',
                stack: ['Dibuat Oleh,', ' ', '\n\n\n\n', `(  ${unitPaymentOrder._createdBy}  )`],
                style: ['center']
            }],
        style: ['size08']
    }];

    var dd = {
        pageSize: 'A5',
        pageOrientation: 'landscape',
        pageMargins: 20,
        content: [].concat(header, subHeader, table, closing, footer),
        styles: {
            size06: {
                fontSize: 6
            },
            size07: {
                fontSize: 7
            },
            size08: {
                fontSize: 8
            },
            size09: {
                fontSize: 9
            },
            size10: {
                fontSize: 10
            },
            size15: {
                fontSize: 15
            },
            bold: {
                bold: true
            },
            center: {
                alignment: 'center'
            },
            left: {
                alignment: 'left'
            },
            right: {
                alignment: 'right'
            },
            justify: {
                alignment: 'justify'
            },
            tableHeader: {
                bold: true,
                fontSize: 8,
                color: 'black',
                alignment: 'center'
            }
        }
    };

    return dd;
}<|endoftext|>


<commit_before><commit_msg>Restore backup flavor selection (SAAS-453)<commit_after><|endoftext|>


<commit_before>export default class ModelBase {
    static get _classNameKey() {
        return "__REACT_NATIVE_MODELS_CLASS_NAME__";
    }

    /**
     * Create private properties and getProperty/setProperty methods for them.
     *
     * @param {object} properties propertyName: propertyType
     * @returns {ModelBase}
     */
    constructor(properties) {
        for (const propertyName in properties) {
            if (ModelBase._isOwnProperty(propertyName, properties) === false) {
                continue;
            }

            if (propertyName.charAt(0) === "_") {
                throw new Error("Properties beginning at underscore not supported.");
            }

            const propertyType = properties[propertyName];
            const privatePropertyName = "_" + propertyName;
            const propertyNameCapitalized =
                propertyName.charAt(0).toUpperCase() +
                propertyName.slice(1);

            this[privatePropertyName] = null;
            this["set" + propertyNameCapitalized] = (value) => {
                if (ModelBase._checkType(value, propertyType) === false) {
                    throw new TypeError(`"${propertyName}" is of type "${ModelBase._getTypeName(value)}". Expected "${propertyType}".`);
                }

                this[privatePropertyName] = value;
            };

            this["get" + propertyNameCapitalized] = () => {
                return this[privatePropertyName];
            };
        }
    }

    /**
     * Create state object, equivalent this model.
     *
     * @returns {object} state
     */
    createState() {
        const state = Object.create(null);
        for (const propertyName in this) {
            if (ModelBase._isOwnProperty(propertyName, this) === false) {
                continue;
            }

            if (propertyName.charAt(0) !== "_") {
                continue;
            }

            const statePropery = propertyName.slice(1);
            state[statePropery] = this[propertyName];
        }

        return state;
    }

    /**
     * Populate members of the model from state.
     *
     * @param {object} state state
     */
    populateFromState(state) {
        // Create instance of ModelBase which has property's types in closure.
        const constructor = ModelBase._getConstructor(this.constructor.name);
        const typeCheckObject = new constructor();

        for (const propertyName in state) {
            if (ModelBase._isOwnProperty(propertyName, state) === false) {
                continue;
            }

            const privatePropertyName = "_" + propertyName;
            const propertyNameCapitalized =
                propertyName.charAt(0).toUpperCase() +
                propertyName.slice(1);

            if (!(privatePropertyName in this)) {
                throw new Error(`Property "${propertyName}" does not exists in "${this.constructor.name}".`);
            }

            // Should throw exception if type of property is invalid.
            const setter = "set" + propertyNameCapitalized;
            typeCheckObject[setter](state[propertyName]);

            this[privatePropertyName] = state[propertyName];
        }
    }

    /**
     * Create new instance of the model from givent state.
     *
     * @static
     * @param {object} state
     * @param {object} properties
     * @return {ModelBase}
     */
    static fromState(state, properties) {
        const classConstructor = ModelBase._getConstructor(this.name);
        const model = new classConstructor(properties);
        model.populateFromState(state);
        return model;
    }

    static _isOwnProperty(propertyName, object) {
        return Object.prototype.hasOwnProperty.apply(object, [propertyName]);
    }

    /**
     * Check type of value and return true if his matches with requiredType.
     *
     * @static
     * @param {any} value
     * @param {string} requiredType
     * @returns {boolean}
     */
    static _checkType(value, requiredType) {
        return ModelBase._getTypeName(value) === requiredType;
    }

    static _getTypeName(value) {
        if (value === undefined) {
            return "Undefined";
        }

        if (value === null) {
            return "Object";
        }

        if (value.constructor === undefined) {
            const typeName = typeof value;
            const typeNameCapitalized = typeName.charAt(0).toUpperCase() + typeName.slice(1);
            return typeNameCapitalized;
        }

        return value.constructor.name;
    }

    /**
     * Serialize self.
     *
     * @returns {string} JSON string
     */
    serialize() {
        return JSON.stringify(ModelBase._serialize(this));
    }

    /**
     * Serialize recursively instance of ModelBase.
     *
     * @static
     * @param {ModelBase} object
     * @returns {object}
     */
    static _serialize(object) {
        const container = Object.create(null);
        container[ModelBase._classNameKey] = object.constructor.name;

        const data = Object.create(null);
        for (const key in object) {
            if (ModelBase._isOwnProperty(key, object) === false) {
                continue;
            }

            if (key.charAt(0) !== "_") {
                continue;
            }

            const value = object[key];

            if (ModelBase._isObjectOrArray(value, "serialization")) {
                data[key] = ModelBase._processObjectOrArray(value, "serialization");
            } else {
                data[key] = ModelBase._processScalar(value, "serialization");
            }
        }

        container["data"] = data;
        return container;
    }

    /**
     * Deserialize JSON string
     *
     * @static
     * @param {string} JSONString
     */
    static deserialize(JSONString) {
        return ModelBase._deserialize(JSON.parse(JSONString));
    }

    /**
     * Deserialize instance of ModelBase.
     *
     * @static
     * @param {object} container
     * @return {ModelBase}
     */
    static _deserialize(container) {
        const className = container[ModelBase._classNameKey];

        if (className === undefined) {
            throw new Error("Invalid object");
        }

        const constructor = ModelBase._getConstructor(className);
        const instance = new constructor();
        const data = container["data"];

        for (const key in data) {
            if (ModelBase._isOwnProperty(key, data) === false) {
                continue;
            }

            const value = data[key];

            if (ModelBase._isObjectOrArray(value, "deserialization")) {
                instance[key] = ModelBase._processObjectOrArray(value, "deserialization");
            } else {
                instance[key] = ModelBase._processScalar(value, "deserialization");
            }
        }

        return instance;
    }

    /**
     * Check if value is plain object or array.
     *
     * @static
     * @param {any} value
     * @returns {boolean}
     */
    static _isObjectOrArray(value, action = "serialization") {
        if (value === undefined || value === null) {
            return false;
        }

        if (action === "serialization" && value instanceof ModelBase) {
            return false;
        }

        if (action === "deserialization" && value[ModelBase._classNameKey] !== undefined) {
            return false;
        }

        return ModelBase._checkType(value, "Object") || ModelBase._checkType(value, "Array");
    }

    /**
     * Serialize/deserialize instance of ModelBase, Number, Boolean, String, Date.
     *
     * @static
     * @param {any} scalar
     * @param {string} action One of "serialization" or "deserialization".
     * @returns {any}
     */
    static _processScalar(scalar, action = "serialization") {
        if (scalar === undefined || scalar === null) {
            return scalar;
        }

        if (action === "serialization") {
            if (scalar instanceof ModelBase) {
                return ModelBase._serialize(scalar);
            }

            if (scalar instanceof Date) {
                throw new Error("Serialization of Date objects not supported.");
            }

            if (scalar instanceof RegExp) {
                throw new Error("Serialization of RegExp objects not supported.");
            }
        }

        if (action === "deserialization") {
            if (scalar[ModelBase._classNameKey]) {
                return ModelBase._deserialize(scalar);
            }
        }

        return scalar; /* Number, Boolean, String */
    }

    /**
     * Serialize/deserialization recursively plain object or array.
     *
     * @param {any} iterable object or array
     * @param {string} action One of "serialization" or "deserialization".
     * @returns {any}
     */
    static _processObjectOrArray(iterable, action = "serialization") {
        let data = null;

        if (Array.isArray(iterable)) {
            data = [];
            for (let i = 0; i < iterable.length; i++) {
                const value = iterable[i];
                if (ModelBase._isObjectOrArray(value, action)) {
                    data.push(ModelBase._processObjectOrArray(value, action));
                } else {
                    data.push(ModelBase._processScalar(value, action));
                }
            }
        } else {
            data = Object.create(null);

            for (const key in iterable) {
                if (ModelBase._isOwnProperty(key, iterable) === false) {
                    continue;
                }

                const value = iterable[key];

                if (ModelBase._isObjectOrArray(value, action)) {
                    data[key] = ModelBase._processObjectOrArray(value, action);
                } else {
                    data[key] = ModelBase._processScalar(value, action);
                }
            }
        }

        return data;
    }

    static require(classConstructor) {
        if (classConstructor in ModelBase.classConstructors) {
            throw new Error(classConstructor.name + " alredy using.");
        }

        ModelBase.classConstructors[classConstructor.name] = classConstructor;
    }

    static _getConstructor(className) {
        if (!(className in ModelBase.classConstructors)) {
            throw new Error("Unknow class. Use ModelBase.require(" + className + ")");
        }

        return ModelBase.classConstructors[className];
    }
}

ModelBase.classConstructors = Object.create(null);
<commit_msg>Return back Object.prototype.toString.call(value) for type checking.<commit_after>export default class ModelBase {
    static get _classNameKey() {
        return "__REACT_NATIVE_MODELS_CLASS_NAME__";
    }

    /**
     * Create private properties and getProperty/setProperty methods for them.
     *
     * @param {object} properties propertyName: propertyType
     * @returns {ModelBase}
     */
    constructor(properties) {

        for (const propertyName in properties) {
            if (ModelBase._isOwnProperty(propertyName, properties) === false) {
                continue;
            }

            if (propertyName.charAt(0) === "_") {
                throw new Error("Properties beginning at underscore not supported.");
            }

            const propertyType = properties[propertyName];
            const privatePropertyName = "_" + propertyName;
            const propertyNameCapitalized =
                propertyName.charAt(0).toUpperCase() +
                propertyName.slice(1);

            this[privatePropertyName] = null;
            this["set" + propertyNameCapitalized] = (value) => {
                if (ModelBase._checkType(value, propertyType) === false) {
                    throw new TypeError(`"${propertyName}" is of type "${ModelBase._getTypeName(value)}". Expected "${propertyType}".`);
                }

                this[privatePropertyName] = value;
            };

            this["get" + propertyNameCapitalized] = () => {
                return this[privatePropertyName];
            };
        }
    }

    /**
     * Create state object, equivalent this model.
     *
     * @returns {object} state
     */
    createState() {
        const state = Object.create(null);
        for (const propertyName in this) {
            if (ModelBase._isOwnProperty(propertyName, this) === false) {
                continue;
            }

            if (propertyName.charAt(0) !== "_") {
                continue;
            }

            const statePropery = propertyName.slice(1);
            state[statePropery] = this[propertyName];
        }

        return state;
    }

    /**
     * Populate members of the model from state.
     *
     * @param {object} state state
     */
    populateFromState(state) {
        // Create instance of ModelBase which has property's types in closure.
        const constructor = ModelBase._getConstructor(this.constructor.name);
        const typeCheckObject = new constructor();

        for (const propertyName in state) {
            if (ModelBase._isOwnProperty(propertyName, state) === false) {
                continue;
            }

            const privatePropertyName = "_" + propertyName;
            const propertyNameCapitalized =
                propertyName.charAt(0).toUpperCase() +
                propertyName.slice(1);

            if (!(privatePropertyName in this)) {
                throw new Error(`Property "${propertyName}" does not exists in "${this.constructor.name}".`);
            }

            // Should throw exception if type of property is invalid.
            const setter = "set" + propertyNameCapitalized;
            typeCheckObject[setter](state[propertyName]);

            this[privatePropertyName] = state[propertyName];
        }
    }

    /**
     * Create new instance of the model from givent state.
     *
     * @static
     * @param {object} state
     * @param {object} properties
     * @return {ModelBase}
     */
    static fromState(state, properties) {
        const classConstructor = ModelBase._getConstructor(this.name);
        const model = new classConstructor(properties);
        model.populateFromState(state);
        return model;
    }

    static _isOwnProperty(propertyName, object) {
        return Object.prototype.hasOwnProperty.apply(object, [propertyName]);
    }

    /**
     * Check type of value and return true if his matches with requiredType.
     *
     * @static
     * @param {any} value
     * @param {string} requiredType
     * @returns {boolean}
     */
    static _checkType(value, requiredType) {
        return ModelBase._getTypeName(value) === requiredType;
    }

    static _getTypeName(value) {
        if (value === undefined) {
            return "Undefined";
        }

        if (value === null) {
            return "Object";
        }

        if (value.constructor === undefined) {
            const matches = Object.prototype.toString.call(value).match(/\[object (.+)\]/);

            if (matches === null) {
                throw new Error("Unknow type");
            }

            return matches[1];
        }

        return value.constructor.name;
    }

    /**
     * Serialize self.
     *
     * @returns {string} JSON string
     */
    serialize() {
        return JSON.stringify(ModelBase._serialize(this));
    }

    /**
     * Serialize recursively instance of ModelBase.
     *
     * @static
     * @param {ModelBase} object
     * @returns {object}
     */
    static _serialize(object) {
        const container = Object.create(null);
        container[ModelBase._classNameKey] = object.constructor.name;

        const data = Object.create(null);
        for (const key in object) {
            if (ModelBase._isOwnProperty(key, object) === false) {
                continue;
            }

            if (key.charAt(0) !== "_") {
                continue;
            }

            const value = object[key];

            if (ModelBase._isObjectOrArray(value, "serialization")) {
                data[key] = ModelBase._processObjectOrArray(value, "serialization");
            } else {
                data[key] = ModelBase._processScalar(value, "serialization");
            }
        }

        container["data"] = data;
        return container;
    }

    /**
     * Deserialize JSON string
     *
     * @static
     * @param {string} JSONString
     */
    static deserialize(JSONString) {
        return ModelBase._deserialize(JSON.parse(JSONString));
    }

    /**
     * Deserialize instance of ModelBase.
     *
     * @static
     * @param {object} container
     * @return {ModelBase}
     */
    static _deserialize(container) {
        const className = container[ModelBase._classNameKey];

        if (className === undefined) {
            throw new Error("Invalid object");
        }

        const constructor = ModelBase._getConstructor(className);
        const instance = new constructor();
        const data = container["data"];

        for (const key in data) {
            if (ModelBase._isOwnProperty(key, data) === false) {
                continue;
            }

            const value = data[key];

            if (ModelBase._isObjectOrArray(value, "deserialization")) {
                instance[key] = ModelBase._processObjectOrArray(value, "deserialization");
            } else {
                instance[key] = ModelBase._processScalar(value, "deserialization");
            }
        }

        return instance;
    }

    /**
     * Check if value is plain object or array.
     *
     * @static
     * @param {any} value
     * @returns {boolean}
     */
    static _isObjectOrArray(value, action = "serialization") {
        if (value === undefined || value === null) {
            return false;
        }

        if (action === "serialization" && value instanceof ModelBase) {
            return false;
        }

        if (action === "deserialization" && value[ModelBase._classNameKey] !== undefined) {
            return false;
        }

        return ModelBase._checkType(value, "Object") || ModelBase._checkType(value, "Array");
    }

    /**
     * Serialize/deserialize instance of ModelBase, Number, Boolean, String, Date.
     *
     * @static
     * @param {any} scalar
     * @param {string} action One of "serialization" or "deserialization".
     * @returns {any}
     */
    static _processScalar(scalar, action = "serialization") {
        if (scalar === undefined || scalar === null) {
            return scalar;
        }

        if (action === "serialization") {
            if (scalar instanceof ModelBase) {
                return ModelBase._serialize(scalar);
            }

            if (scalar instanceof Date) {
                throw new Error("Serialization of Date objects not supported.");
            }

            if (scalar instanceof RegExp) {
                throw new Error("Serialization of RegExp objects not supported.");
            }
        }

        if (action === "deserialization") {
            if (scalar[ModelBase._classNameKey]) {
                return ModelBase._deserialize(scalar);
            }
        }

        return scalar; /* Number, Boolean, String */
    }

    /**
     * Serialize/deserialization recursively plain object or array.
     *
     * @param {any} iterable object or array
     * @param {string} action One of "serialization" or "deserialization".
     * @returns {any}
     */
    static _processObjectOrArray(iterable, action = "serialization") {
        let data = null;

        if (Array.isArray(iterable)) {
            data = [];
            for (let i = 0; i < iterable.length; i++) {
                const value = iterable[i];
                if (ModelBase._isObjectOrArray(value, action)) {
                    data.push(ModelBase._processObjectOrArray(value, action));
                } else {
                    data.push(ModelBase._processScalar(value, action));
                }
            }
        } else {
            data = Object.create(null);

            for (const key in iterable) {
                if (ModelBase._isOwnProperty(key, iterable) === false) {
                    continue;
                }

                const value = iterable[key];

                if (ModelBase._isObjectOrArray(value, action)) {
                    data[key] = ModelBase._processObjectOrArray(value, action);
                } else {
                    data[key] = ModelBase._processScalar(value, action);
                }
            }
        }

        return data;
    }

    static require(classConstructor) {
        if (classConstructor in ModelBase.classConstructors) {
            throw new Error(classConstructor.name + " alredy using.");
        }

        ModelBase.classConstructors[classConstructor.name] = classConstructor;
    }

    static _getConstructor(className) {
        if (!(className in ModelBase.classConstructors)) {
            throw new Error("Unknow class. Use ModelBase.require(" + className + ")");
        }

        return ModelBase.classConstructors[className];
    }
}

ModelBase.classConstructors = Object.create(null);
<|endoftext|>


<commit_before>var _ = require('lodash'),
    utils =  require('../../../utils'),
    driver = utils.getDriver(),
    C = driver.constants;

module.exports = function(object, intent, roomObjects, roomTerrain, bulk, bulkUsers, roomController, stats, gameTime, roomInfo) {

    if(object.type != 'creep') {
        return;
    }
    if(object.spawning) {
        return;
    }

    var target = roomObjects[intent.id];
    if(!target || !C.CONSTRUCTION_COST[target.type]) {
        return;
    }
    if(Math.abs(target.x - object.x) > 1 || Math.abs(target.y - object.y) > 1) {
        return;
    }
    if(roomController && roomController.user != object.user && roomController.safeMode > gameTime) {
        return;
    }
    var rampart = _.find(roomObjects, {type: 'rampart', x: target.x, y: target.y});
    if(rampart) {
        target = rampart;
    }

    var power = utils.calcBodyEffectiveness(object.body, C.WORK, 'dismantle', C.DISMANTLE_POWER),
    effect = Math.min(power, target.hits),
    energyGain = Math.floor(effect * C.DISMANTLE_COST);

    if(effect) {

        object.energy += energyGain;
        bulk.update(object, {energy: object.energy});

        if (object.energy > object.energyCapacity) {
            require('./drop')(object, {amount: object.energy - object.energyCapacity, resourceType: 'energy'}, roomObjects, roomTerrain, bulk);
        }

        require('../_damage')(object, target, effect, 'melee', roomObjects, roomTerrain, bulk, roomController, stats, gameTime, roomInfo);
    }
};<commit_msg>Added fix for dismantle intent not being able to dismantle own structures under own ramparts.<commit_after>var _ = require('lodash'),
    utils =  require('../../../utils'),
    driver = utils.getDriver(),
    C = driver.constants;

module.exports = function(object, intent, roomObjects, roomTerrain, bulk, bulkUsers, roomController, stats, gameTime, roomInfo) {

    if(object.type != 'creep') {
        return;
    }
    if(object.spawning) {
        return;
    }

    var target = roomObjects[intent.id];
    if(!target || !C.CONSTRUCTION_COST[target.type]) {
        return;
    }
    if(Math.abs(target.x - object.x) > 1 || Math.abs(target.y - object.y) > 1) {
        return;
    }
    if(roomController && roomController.user != object.user && roomController.safeMode > gameTime) {
        return;
    }
    var rampart = _.find(roomObjects, {type: 'rampart', x: target.x, y: target.y});
    if(rampart && object.user != rampart.user) {
        target = rampart;
    }

    var power = utils.calcBodyEffectiveness(object.body, C.WORK, 'dismantle', C.DISMANTLE_POWER),
    effect = Math.min(power, target.hits),
    energyGain = Math.floor(effect * C.DISMANTLE_COST);

    if(effect) {

        object.energy += energyGain;
        bulk.update(object, {energy: object.energy});

        if (object.energy > object.energyCapacity) {
            require('./drop')(object, {amount: object.energy - object.energyCapacity, resourceType: 'energy'}, roomObjects, roomTerrain, bulk);
        }

        require('../_damage')(object, target, effect, 'melee', roomObjects, roomTerrain, bulk, roomController, stats, gameTime, roomInfo);
    }
};<|endoftext|>