<commit_before>import { update, rotate, zoom, setFocus } from 'usco-orbit-controls'
import { computeCameraToFitBounds, cameraOffsetToEntityBoundsCenter } from 'usco-camera-utils'

import { model } from '../modelUtils'
import {animationFrames, rafStream} from '../most/animationFrames'

import mat4 from 'gl-mat4'
import limitFlow from '../most/limitFlow'

export default function controlsStream (interactions, cameraData, focuses$, entityFocuses$, projection$) {
  let {settings, camera} = cameraData
  const {gestures} = interactions

  const rate$ = rafStream() // heartBeat

  /*let i = 0
  var newdiv = document.createElement("DIV")
  newdiv.style.zIndex = 99
  newdiv.style.position = 'absolute'
  newdiv.style.color = 'red'
  newdiv.style.top = '40px'
  let textNode = document.createTextNode("some text"+i)
  newdiv.appendChild(textNode)
  document.body.appendChild(newdiv)*/

  const dragMoves$ = gestures.dragMoves
    // .throttle(16) // FIXME: not sure, could be optimized some more
    .filter(x => x !== undefined)
    .map(function (data) {
      let delta = [data.delta.x, data.delta.y]
      if (data.type === 'touch') {
        // delta = delta.map(x => x / mobileReductor)
      }
      return delta
    })
    .map(function (delta) {
      const angle = [-Math.PI * delta[0], -Math.PI * delta[1]]
      return angle
    })
    .map(x => x.map(y => y * 0.1)) // empirical reduction factor

  const zooms$ = gestures.zooms
    .map(x => -x) // we invert zoom direction
    .startWith(0)
    .filter(x => !isNaN(x))
    .map(x => x * 2.5)
    //.throttle(10)

  // model/ state/ reducers
  function makeCameraModel () {
    function setProjection (state, input) {
      const projection = mat4.perspective([], state.fov, input.width / input.height, // context.viewportWidth / context.viewportHeight,
        state.near,
        state.far)
      //state = Object.assign({}, state, {projection})
      state.projection = projection
      state.aspect = input.width / input.height
      //state = Object.assign({}, state, update(settings, state)) // not sure
      return state
    }

    function applyRotation (state, angles) {
      //textNode.nodeValue= 'applyRotation'
      state = rotate(settings, state, angles) // mutating, meh
      return state
    }

    function applyZoom (state, zooms) {
      state = zoom(settings, state, zooms)//, {adjustPlanes: true}) // mutating, meh
      return state
    }

    function applyFocusOn (state, focuses) {
      state = setFocus(settings, state, focuses) // mutating, meh
      return state
    }

    function zoomToFit (state, input) {
      //console.log('zoomToFit', state.position, state.target,  input)
      let camera = state
      const {bounds, transforms} = input
      const offsetTargetAndPosition = cameraOffsetToEntityBoundsCenter({camera, bounds, transforms, axis: 2})
      camera = Object.assign({}, state, offsetTargetAndPosition)
      const phase2 = computeCameraToFitBounds({camera, bounds, transforms})
      state.targetTgt = phase2.target
      state.positionTgt = phase2.position
      return state
      //FIXME: just a test for zoomToFit for now
      //console.log('zoomToFit', state.position, state.target,  input)
      /*camera.near = 0.01
      settings.limits.minDistance = 0
      let camera = state
      const {bounds, transforms} = input
      camera = Object.assign({}, state, cameraOffsetToEntityBoundsCenter({camera, bounds, transforms, axis: 2}))
      camera = Object.assign({}, state, computeCameraToFitBounds({camera, bounds, transforms}))
      return camera*/
    }

    //this is used for 'continuous updates' for things like spin effects, autoRotate etc
    function updateState (state) {
      //i++
      //textNode.nodeValue= 'foo'+i
      //return state
      return Object.assign({}, state, update(settings, state))
    }

    const updateFunctions = {
      setProjection,
      applyZoom,
      applyRotation,
      //applyFocusOn,
      zoomToFit,
      updateState
    }
    const actions = {
      setProjection: projection$,
      applyZoom: zooms$,
      applyRotation: dragMoves$,
      //applyFocusOn: focuses$,
      zoomToFit: entityFocuses$,
      updateState: rate$
    }

    const cameraState$ = model(camera, actions, updateFunctions)

    return cameraState$
  }

  const cameraState$ = makeCameraModel()

  return cameraState$
    .thru(limitFlow(33))
  /*return rate$.sample(x => x,
    cameraState$
      .filter(x => x.changed)
      .merge(cameraState$.take(1))
  )*/
}
<commit_msg>refactor(controlsStream): overall minor cleanup<commit_after>import { update, rotate, zoom, setFocus } from 'usco-orbit-controls'
import { computeCameraToFitBounds, cameraOffsetToEntityBoundsCenter } from 'usco-camera-utils'

import { model } from '../modelUtils'
import {animationFrames, rafStream} from '../most/animationFrames'

import mat4 from 'gl-mat4'
import limitFlow from '../most/limitFlow'

export default function controlsStream (interactions, cameraData, focuses$, entityFocuses$, projection$) {
  let {settings, camera} = cameraData
  const {gestures} = interactions
  const rate$ = rafStream() // heartBeat

  console.log('camera', camera.near, 'settings', settings)
  /*let i = 0
  var newdiv = document.createElement("DIV")
  newdiv.style.zIndex = 99
  newdiv.style.position = 'absolute'
  newdiv.style.color = 'red'
  newdiv.style.top = '40px'
  let textNode = document.createTextNode("some text"+i)
  newdiv.appendChild(textNode)
  document.body.appendChild(newdiv)*/

  const dragMoves$ = gestures.dragMoves
    // .throttle(16) // FIXME: not sure, could be optimized some more
    .filter(x => x !== undefined)
    .map(function (data) {
      let delta = [data.delta.x, data.delta.y]
      if (data.type === 'touch') {
        // delta = delta.map(x => x / mobileReductor)
      }
      return delta
    })
    .map(function (delta) {
      const angle = [-Math.PI * delta[0], -Math.PI * delta[1]]
      return angle
    })
    .map(x => x.map(y => y * 0.1)) // empirical reduction factor

  const zooms$ = gestures.zooms
    .map(x => -x) // we invert zoom direction
    .startWith(0)
    .filter(x => !isNaN(x))
    .map(x => x * 2.5)
    //.throttle(10)

  // model/ state/ reducers
  function makeCameraModel () {
    function setProjection (state, input) {
      const projection = mat4.perspective([], state.fov, input.width / input.height, // context.viewportWidth / context.viewportHeight,
        state.near,
        state.far)
      state.projection = projection
      state.aspect = input.width / input.height
      //state = Object.assign({}, state, update(settings, state)) // not sure
      return state
    }

    function applyRotation (state, angles) {
      state = rotate(settings, state, angles) // mutating, meh
      return state
    }

    function applyZoom (state, zooms) {
      state = zoom(settings, state, zooms)//, {adjustPlanes: true}) // mutating, meh
      return state
    }

    function applyFocusOn (state, focuses) {
      state = setFocus(settings, state, focuses) // mutating, meh
      return state
    }

    function zoomToFit (state, input) {
      //console.log('zoomToFit', state.position, state.target,  input)
      let camera = state

      const {bounds, transforms} = input
      const offsetTargetAndPosition = cameraOffsetToEntityBoundsCenter({camera, bounds, transforms, axis: 2})
      camera = Object.assign({}, state, offsetTargetAndPosition)
      const phase2 = computeCameraToFitBounds({camera, bounds, transforms})
      state.targetTgt = phase2.target
      state.positionTgt = phase2.position
      return state
      //FIXME: just a test for zoomToFit for now
      //console.log('zoomToFit', state.position, state.target,  input)
      /*camera.near = 0.01
      settings.limits.minDistance = 0
      let camera = state
      const {bounds, transforms} = input
      camera = Object.assign({}, state, cameraOffsetToEntityBoundsCenter({camera, bounds, transforms, axis: 2}))
      camera = Object.assign({}, state, computeCameraToFitBounds({camera, bounds, transforms}))
      return camera*/
    }

    //this is used for 'continuous updates' for things like spin effects, autoRotate etc
    function updateState (state) {
      return Object.assign({}, state, update(settings, state))
    }

    const updateFunctions = {
      setProjection,
      applyZoom,
      applyRotation,
      //applyFocusOn,
      zoomToFit,
      updateState
    }
    const actions = {
      setProjection: projection$,
      applyZoom: zooms$,
      applyRotation: dragMoves$,
      //applyFocusOn: focuses$,
      zoomToFit: entityFocuses$,
      updateState: rate$
    }

    const cameraState$ = model(camera, actions, updateFunctions)

    return cameraState$
  }

  const cameraState$ = makeCameraModel()

  return cameraState$
    .thru(limitFlow(33))
  /*return rate$.sample(x => x,
    cameraState$
      .filter(x => x.changed)
      .merge(cameraState$.take(1))
  )*/
}
<|endoftext|>


<commit_before>/*
 * jquery-gpopover
 * http://github.com/markembling/jquery-gpopover
 *
 * A simple jQuery plugin for creating popover elements similar to Google's
 * new 'apps' launcher/switcher.
 *
 * Copyright (c) 2013 Mark Embling (markembling.info)
 * Licensed under the BSD (3 clause) license.
 */

;(function($){

    var GPopover = function(element, options) {
        this.options = null;
        this.$trigger = null;
        this.$popover = null;

        this.init(element, options);
    }

    GPopover.prototype.init = function(element, options) {
        var that = this;

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

        this.$trigger = $(element);
        this.$popover = $('#' + this.$trigger.data('popover'));

        this._addArrowElements();

        if (this.options.preventHide) {
            this._preventHideClickPropagation();
        }

        this.$trigger.click(function(e){
            if (! that.$popover.is(":visible")) {
                that.show();

                // Prevent this event from having any further effect
                e.preventDefault();
                e.stopPropagation();
            }
        });
    }

    GPopover.prototype.show = function() {
        var that = this;

        // Set width before showing
        this.$popover.width(this.options.width);

        // Show the popover
        this.$popover.fadeIn(this.options.fadeInDuration);

        // Set up hiding
        $(document).one('click.popoverHide', function() {
            // _hidePopover($popover, settings);
            that.hide();
        });

        // Sort out the position (must be done after showing)
        var triggerPos = this.$trigger.offset();
        this.$popover.offset({
            left: (triggerPos.left + (this.$trigger.outerWidth() / 2)) - (this.$popover.outerWidth() / 2),
            top: triggerPos.top + this.$trigger.outerHeight() + 10
            // the final 10 above allows room for the arrow above it
        });

        // Check and reposition if out of the viewport
        var positionXCorrection = this._repositionForViewportSides();

        // Set the position of the arrow elements
        this._setArrowPosition(positionXCorrection);

        // Call the callback
        this.options.onShow.call(this.$trigger, this.$popover);
    }

    GPopover.prototype.hide = function() {
        // Hide the popover
        this.$popover.fadeOut(this.options.fadeOutDuration);

        // Call the callback
        this.options.onHide.call(this.$trigger, this.$popover);
    }

    GPopover.prototype._addArrowElements = function() {
        this.$arrow = $('

');
        this.$arrowShadow = $('

');

        this.$popover.append(this.$arrow);
        this.$popover.append(this.$arrowShadow);
    }

    GPopover.prototype._preventHideClickPropagation = function() {
        /* Prevent clicks within the popover from being propagated
           to the document (and thus stop the popover from being
           hidden) */
        this.$popover.click(function(e) { e.stopPropagation(); });
    }

    GPopover.prototype._repositionForViewportSides = function() {
        var popoverOffsetLeft = this.$popover.offset().left,
            positionXCorrection = 0,
            $window = $(window);

        // Right edge
        if (popoverOffsetLeft + this.$popover.outerWidth() + this.options.viewportSideMargin > $window.width()) {
            var rightEdgeCorrection = -((popoverOffsetLeft + this.$popover.outerWidth() + this.options.viewportSideMargin) - $window.width());
            popoverOffsetLeft = popoverOffsetLeft + rightEdgeCorrection

            positionXCorrection = rightEdgeCorrection;
        }

        // Left edge
        if (popoverOffsetLeft < this.options.viewportSideMargin) {
            var leftEdgeCorrection = this.options.viewportSideMargin - popoverOffsetLeft;
            popoverOffsetLeft = popoverOffsetLeft + leftEdgeCorrection

            positionXCorrection += leftEdgeCorrection;
        }

        // Reposition the popover element if necessary
        if (positionXCorrection !== 0) {
            this.$popover.offset({ left: popoverOffsetLeft });
        }

        return positionXCorrection;
    }

    GPopover.prototype._setArrowPosition = function(positionXCorrection) {
        var leftPosition = (this.$popover.outerWidth() / 2) - (this.$arrow.outerWidth() / 2) - positionXCorrection;

        this.$arrow.css({ top: -7, left: leftPosition });
        this.$arrowShadow.css({ top: -8, left: leftPosition });
    }

    $.fn.gpopover = function(option) {
        return this.each(function(){
            var $this = $(this),
                data = $this.data('gpopover'),
                options = (typeof option == 'object' && option);

            // Initialise if not already done
            if (!data) {
                data = new GPopover(this, options);
                $this.data('gpopover', data);
            }

            // If the option parameter was a string, trigger the named function
            if (typeof option == 'string') data[option]();
        });

    };

    // Default settings
    $.fn.gpopover.defaults = {
        width: 250,             // Width of the popover
        fadeInDuration: 65,     // Duration of popover fade-in animation
        fadeOutDuration: 65,    // Duration of popover fade-out animation
        viewportSideMargin: 10, // Space to leave the side if out the viewport
        preventHide: false,     // Prevent hide when clicking within popover

        onShow: function() {},  // Called upon showing the popover
        onHide: function() {}   // Called upon hiding the popover
    };

})(jQuery);
<commit_msg>Don't let a trigger click prevent the document ever having a 'click' event<commit_after>/*
 * jquery-gpopover
 * http://github.com/markembling/jquery-gpopover
 *
 * A simple jQuery plugin for creating popover elements similar to Google's
 * new 'apps' launcher/switcher.
 *
 * Copyright (c) 2013 Mark Embling (markembling.info)
 * Licensed under the BSD (3 clause) license.
 */

;(function($){

    var GPopover = function(element, options) {
        this.options = null;
        this.$trigger = null;
        this.$popover = null;

        this.init(element, options);
    }

    GPopover.prototype.init = function(element, options) {
        var that = this;

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

        this.$trigger = $(element);
        this.$popover = $('#' + this.$trigger.data('popover'));

        this._addArrowElements();

        if (this.options.preventHide) {
            this._preventHideClickPropagation();
        }

        this.$trigger.click(function(e){
            if (! that.$popover.is(":visible")) {
                // Trigger a click on the parent element (that can bubble up)
                $(this).parent().click();

                that.show();

                // Prevent this event from having any further effect
                e.preventDefault();
                e.stopPropagation();
            }
        });
    }

    GPopover.prototype.show = function() {
        var that = this;

        // Set width before showing
        this.$popover.width(this.options.width);

        // Show the popover
        this.$popover.fadeIn(this.options.fadeInDuration);

        // Set up hiding
        $(document).one('click.popoverHide', function() {
            // _hidePopover($popover, settings);
            that.hide();
        });

        // Sort out the position (must be done after showing)
        var triggerPos = this.$trigger.offset();
        this.$popover.offset({
            left: (triggerPos.left + (this.$trigger.outerWidth() / 2)) - (this.$popover.outerWidth() / 2),
            top: triggerPos.top + this.$trigger.outerHeight() + 10
            // the final 10 above allows room for the arrow above it
        });

        // Check and reposition if out of the viewport
        var positionXCorrection = this._repositionForViewportSides();

        // Set the position of the arrow elements
        this._setArrowPosition(positionXCorrection);

        // Call the callback
        this.options.onShow.call(this.$trigger, this.$popover);
    }

    GPopover.prototype.hide = function() {
        // Hide the popover
        this.$popover.fadeOut(this.options.fadeOutDuration);

        // Call the callback
        this.options.onHide.call(this.$trigger, this.$popover);
    }

    GPopover.prototype._addArrowElements = function() {
        this.$arrow = $('

');
        this.$arrowShadow = $('

');

        this.$popover.append(this.$arrow);
        this.$popover.append(this.$arrowShadow);
    }

    GPopover.prototype._preventHideClickPropagation = function() {
        /* Prevent clicks within the popover from being propagated
           to the document (and thus stop the popover from being
           hidden) */
        this.$popover.click(function(e) { e.stopPropagation(); });
    }

    GPopover.prototype._repositionForViewportSides = function() {
        var popoverOffsetLeft = this.$popover.offset().left,
            positionXCorrection = 0,
            $window = $(window);

        // Right edge
        if (popoverOffsetLeft + this.$popover.outerWidth() + this.options.viewportSideMargin > $window.width()) {
            var rightEdgeCorrection = -((popoverOffsetLeft + this.$popover.outerWidth() + this.options.viewportSideMargin) - $window.width());
            popoverOffsetLeft = popoverOffsetLeft + rightEdgeCorrection

            positionXCorrection = rightEdgeCorrection;
        }

        // Left edge
        if (popoverOffsetLeft < this.options.viewportSideMargin) {
            var leftEdgeCorrection = this.options.viewportSideMargin - popoverOffsetLeft;
            popoverOffsetLeft = popoverOffsetLeft + leftEdgeCorrection

            positionXCorrection += leftEdgeCorrection;
        }

        // Reposition the popover element if necessary
        if (positionXCorrection !== 0) {
            this.$popover.offset({ left: popoverOffsetLeft });
        }

        return positionXCorrection;
    }

    GPopover.prototype._setArrowPosition = function(positionXCorrection) {
        var leftPosition = (this.$popover.outerWidth() / 2) - (this.$arrow.outerWidth() / 2) - positionXCorrection;

        this.$arrow.css({ top: -7, left: leftPosition });
        this.$arrowShadow.css({ top: -8, left: leftPosition });
    }

    $.fn.gpopover = function(option) {
        return this.each(function(){
            var $this = $(this),
                data = $this.data('gpopover'),
                options = (typeof option == 'object' && option);

            // Initialise if not already done
            if (!data) {
                data = new GPopover(this, options);
                $this.data('gpopover', data);
            }

            // If the option parameter was a string, trigger the named function
            if (typeof option == 'string') data[option]();
        });

    };

    // Default settings
    $.fn.gpopover.defaults = {
        width: 250,             // Width of the popover
        fadeInDuration: 65,     // Duration of popover fade-in animation
        fadeOutDuration: 65,    // Duration of popover fade-out animation
        viewportSideMargin: 10, // Space to leave the side if out the viewport
        preventHide: false,     // Prevent hide when clicking within popover

        onShow: function() {},  // Called upon showing the popover
        onHide: function() {}   // Called upon hiding the popover
    };

})(jQuery);
<|endoftext|>


<commit_before>'use strict';

// external deps
var ObjectId = require('mongodb').ObjectId;

// internal deps
require('mongodb-toolkit');
var BateeqModels = require('bateeq-models');
var generateCode = require('../../utils/code-generator');
var map = BateeqModels.map;

var TransferOutDoc = BateeqModels.inventory.TransferOutDoc;
var TransferOutItem = BateeqModels.inventory.TransferOutItem;

const moduleId = "EFR-KB/RTT";
const modulePackingList = "EFR-KB/PBR";
module.exports = class TokoTransferStokManager {
    constructor(db, user) {
        this.db = db;
        this.user = user;
        this.transferOutDocCollection = this.db.use(map.inventory.TransferOutDoc);
        var StorageManager = require('./storage-manager');
        this.storageManager = new StorageManager(db, user);

        var ArticleVariantManager = require('../core/article/article-variant-manager');
        this.articleVariantManager = new ArticleVariantManager(db, user);

        var InventoryManager = require('./inventory-manager');
        this.inventoryManager = new InventoryManager(db, user);

        var TrasferOutManager = require('./transfer-out-doc-manager');
        this.transferOutDocManager = new TrasferOutManager(db, user);

        var ModuleManager = require('../core/module-manager');
        this.moduleManager = new ModuleManager(db, user);

        var PusatReturTokoTerimaBarangReturManager = require('./efr-tb-brt-manager');
        this.pusatReturTokoTerimaBarangReturManager = new PusatReturTokoTerimaBarangReturManager(db, user);

        var SPKBarangJadiReturManager = require('../merchandiser/efr-pk-pbr-manager');
        this.spkBarangJadiReturManager = new SPKBarangJadiReturManager(db, user);

        var PusatBarangBaruKirimBarangJadiAksesorisManager = require('./efr-kb-exb-manager');
        this.pusatBarangBaruKirimBarangJadiAksesorisManager = new PusatBarangBaruKirimBarangJadiAksesorisManager(db, user);

    }

    read(paging) {
        var _paging = Object.assign({
            page: 1,
            size: 20,
            order: '_id',
            asc: true
        }, paging);

        return new Promise((resolve, reject) => {
            var regexModuleId = new RegExp(moduleId, "i");
            var filter = {
                _deleted: false,
                'code': {
                    '$regex': regexModuleId
                }
            };
            var query = _paging.keyword ? {
                '$and': [filter]
            } : filter;

            if (_paging.keyword) {
                var regex = new RegExp(_paging.keyword, "i");
                var filterCode = {
                    'code': {
                        '$regex': regex
                    }
                };
                var $or = {
                    '$or': [filterCode]
                };

                query['$and'].push($or);
            }

            this.transferOutDocCollection
                .where(query)
                .page(_paging.page, _paging.size)
                .orderBy(_paging.order, _paging.asc)
                .execute()
                .then(transferOutDocs => {
                    resolve(transferOutDocs);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getById(id) {
        return new Promise((resolve, reject) => {
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(transferOutDoc => {
                    resolve(transferOutDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getByIdOrDefault(id) {
        return new Promise((resolve, reject) => {
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleOrDefaultByQuery(query)
                .then(transferOutDoc => {
                    resolve(transferOutDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getSingleByQuery(query) {
        return new Promise((resolve, reject) => {
            this.transferOutDocCollection
                .single(query)
                .then(transferOutDoc => {
                    resolve(transferOutDoc);
                })
                .catch(e => {
                    reject(e);
                });
        })
    }

    getSingleOrDefaultByQuery(query) {
        return new Promise((resolve, reject) => {
            this.transferOutDocCollection
                .singleOrDefault(query)
                .then(transferOutDoc => {
                    resolve(transferOutDoc);
                })
                .catch(e => {
                    reject(e);
                });
        })
    }

    create(transferOutDoc) {
        return new Promise((resolve, reject) => {
            this._validate(transferOutDoc)
                .then(validTransferOutDoc => {
                    validTransferOutDoc.code = generateCode(moduleId);
                    this.storageManager.getByCode("PST-003")
                        .then(storage => {
                            var transferinDoc = {};
                            transferinDoc.source = validTransferOutDoc.source;
                            transferinDoc.sourceId = validTransferOutDoc.sourceId;
                            transferinDoc.destination = storage;
                            transferinDoc.destinationId = storage._id;
                            transferinDoc.items = validTransferOutDoc.items;
                            transferinDoc.reference = validTransferOutDoc.code;

                            var spkDoc = {};
                            spkDoc.source = storage;
                            spkDoc.sourceId = storage._id;
                            spkDoc.destination = validTransferOutDoc.destination;
                            spkDoc.destinationId = validTransferOutDoc.destinationId;
                            spkDoc.items = validTransferOutDoc.items;
                            spkDoc.packingList = generateCode(modulePackingList);
                            spkDoc.isDraft = false;
                            spkDoc.isReceived = false;
                            spkDoc.reference = validTransferOutDoc.code;

                            var ekspedisiDoc = {};
                            ekspedisiDoc.destination = validTransferOutDoc.destination;
                            ekspedisiDoc.destinationId = validTransferOutDoc.destinationId;
                            ekspedisiDoc.items = validTransferOutDoc.items;
                            ekspedisiDoc.expedition = "Dikirim Sendiri";
                            ekspedisiDoc.weight = 0;

                            this.transferOutDocManager.create(validTransferOutDoc)
                                .then(id => {
                                    this.pusatReturTokoTerimaBarangReturManager.create(transferinDoc);
                                    this.spkBarangJadiReturManager.create(spkDoc);
                                    this.pusatBarangBaruKirimBarangJadiAksesorisManager.create(ekspedisiDoc);
                                    resolve(id);
                                })
                                .catch(e => {
                                    reject(e);
                                })
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        })

    }

    update(transferOutDoc) {
        return new Promise((resolve, reject) => {
            this._validate(transferOutDoc)
                .then(validTransferOutDoc => {
                    this.transferOutDocManager.update(validTransferOutDoc)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(ex => {
                            reject(ex);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    delete(transferOutDoc) {
        return new Promise((resolve, reject) => {
            this._validate(transferOutDoc)
                .then(validTransferOutDoc => {
                    validTransferOutDoc._deleted = true;
                    this.transferOutDocManager.update(validTransferOutDoc)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    _validate(transferOutDoc) {
        var errors={};
        return new Promise((resolve, reject) => {
            var valid = transferOutDoc;
            this.moduleManager.getByCode(moduleId)
                .then(module => {
                    var config = module.config;
                    if (!valid.sourceId || valid.sourceId == '')
                        errors["sourceId"] = "sourceId is required";
                    else {
                        if (config) {
                            if (config.source) {
                                var isAny = false;
                                if (config.source.type == "selection") {
                                    for (var sourceId of config.source.value) {
                                        if (sourceId.toString() == valid.sourceId.toString()) {
                                            isAny = true;
                                            break;
                                        }
                                    }
                                }
                                else {
                                    if (config.source.value.toString() == valid.sourceId.toString())
                                        isAny = true;
                                }
                                if (!isAny)
                                    errors["sourceId"] = "sourceId is not valid";
                            }
                        }
                    }

                    if (!valid.destinationId || valid.destinationId == '')
                        errors["destinationId"] = "destinationId is required";
                    else {
                        if (config) {
                            if (config.destination) {
                                var isAny = false;
                                if (config.destination.type == "selection") {
                                    for (var destinationId of config.destination.value) {
                                        if (destinationId.toString() == valid.destinationId.toString()) {
                                            isAny = true;
                                            break;
                                        }
                                    }
                                }
                                else {
                                    if (config.destination.value.toString() == valid.destinationId.toString())
                                        isAny = true;
                                }
                                if (!isAny)
                                    errors["destinationId"] = "destinationId is not valid";
                            }
                        }
                    }
                    var getItem = [];
                    if (valid.items && valid.items.length > 0) {
                        for (var item of valid.items) {
                            getItem.push(this.inventoryManager.getByStorageIdAndArticleVarianIdOrDefault(valid.sourceId, item.articleVariantId))
                        }
                    }
                    else {
                        errors["items"] = "items is required";
                    }

                    Promise.all(getItem)
                        .then(results => {
                            var index = 0;
                            var itemErrors = [];
                            var itemError = {};

                            if (results.length > 0) {
                                for (var item of valid.items) {
                                    if (results[index] == null) {
                                        var inventoryQuantity = 0;
                                    } else {
                                        var inventoryQuantity = results[index].quantity;
                                    }
                                    index++;
                                    if (item.quantity > inventoryQuantity) {
                                        itemError["quantity"] = "Tidak bisa simpan jika Quantity Pengiriman > Quantity Stock";
                                    }
                                    itemErrors.push(itemError);
                                }
                            }
                            for (var itemError of itemErrors) {
                                for (var prop in itemError) {
                                    errors.items = itemErrors;
                                    break;
                                }
                                if (errors.items)
                                    break;
                            }
                            for (var prop in errors) {
                                var ValidationError = require('../../validation-error');
                                reject(new ValidationError('data does not pass validation', errors));
                            }
                            resolve(valid);
                        }).catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });
        });
    }
};

<commit_msg>change pst-3 in efr-kb-rtt-manajer<commit_after>'use strict';

// external deps
var ObjectId = require('mongodb').ObjectId;

// internal deps
require('mongodb-toolkit');
var BateeqModels = require('bateeq-models');
var generateCode = require('../../utils/code-generator');
var map = BateeqModels.map;

var TransferOutDoc = BateeqModels.inventory.TransferOutDoc;
var TransferOutItem = BateeqModels.inventory.TransferOutItem;

const moduleId = "EFR-KB/RTT";
const modulePackingList = "EFR-KB/PBR";
module.exports = class TokoTransferStokManager {
    constructor(db, user) {
        this.db = db;
        this.user = user;
        this.transferOutDocCollection = this.db.use(map.inventory.TransferOutDoc);
        var StorageManager = require('./storage-manager');
        this.storageManager = new StorageManager(db, user);

        var ArticleVariantManager = require('../core/article/article-variant-manager');
        this.articleVariantManager = new ArticleVariantManager(db, user);

        var InventoryManager = require('./inventory-manager');
        this.inventoryManager = new InventoryManager(db, user);

        var TrasferOutManager = require('./transfer-out-doc-manager');
        this.transferOutDocManager = new TrasferOutManager(db, user);

        var ModuleManager = require('../core/module-manager');
        this.moduleManager = new ModuleManager(db, user);

        var PusatReturTokoTerimaBarangReturManager = require('./efr-tb-brt-manager');
        this.pusatReturTokoTerimaBarangReturManager = new PusatReturTokoTerimaBarangReturManager(db, user);

        var SPKBarangJadiReturManager = require('../merchandiser/efr-pk-pbr-manager');
        this.spkBarangJadiReturManager = new SPKBarangJadiReturManager(db, user);

        var PusatBarangBaruKirimBarangJadiAksesorisManager = require('./efr-kb-exb-manager');
        this.pusatBarangBaruKirimBarangJadiAksesorisManager = new PusatBarangBaruKirimBarangJadiAksesorisManager(db, user);

    }

    read(paging) {
        var _paging = Object.assign({
            page: 1,
            size: 20,
            order: '_id',
            asc: true
        }, paging);

        return new Promise((resolve, reject) => {
            var regexModuleId = new RegExp(moduleId, "i");
            var filter = {
                _deleted: false,
                'code': {
                    '$regex': regexModuleId
                }
            };
            var query = _paging.keyword ? {
                '$and': [filter]
            } : filter;

            if (_paging.keyword) {
                var regex = new RegExp(_paging.keyword, "i");
                var filterCode = {
                    'code': {
                        '$regex': regex
                    }
                };
                var $or = {
                    '$or': [filterCode]
                };

                query['$and'].push($or);
            }

            this.transferOutDocCollection
                .where(query)
                .page(_paging.page, _paging.size)
                .orderBy(_paging.order, _paging.asc)
                .execute()
                .then(transferOutDocs => {
                    resolve(transferOutDocs);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getById(id) {
        return new Promise((resolve, reject) => {
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(transferOutDoc => {
                    resolve(transferOutDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getByIdOrDefault(id) {
        return new Promise((resolve, reject) => {
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleOrDefaultByQuery(query)
                .then(transferOutDoc => {
                    resolve(transferOutDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getSingleByQuery(query) {
        return new Promise((resolve, reject) => {
            this.transferOutDocCollection
                .single(query)
                .then(transferOutDoc => {
                    resolve(transferOutDoc);
                })
                .catch(e => {
                    reject(e);
                });
        })
    }

    getSingleOrDefaultByQuery(query) {
        return new Promise((resolve, reject) => {
            this.transferOutDocCollection
                .singleOrDefault(query)
                .then(transferOutDoc => {
                    resolve(transferOutDoc);
                })
                .catch(e => {
                    reject(e);
                });
        })
    }

    create(transferOutDoc) {
        return new Promise((resolve, reject) => {
            this._validate(transferOutDoc)
                .then(validTransferOutDoc => {
                    validTransferOutDoc.code = generateCode(moduleId);
                    this.storageManager.getByCode("PST-3")
                        .then(storage => {
                            var transferinDoc = {};
                            transferinDoc.source = validTransferOutDoc.source;
                            transferinDoc.sourceId = validTransferOutDoc.sourceId;
                            transferinDoc.destination = storage;
                            transferinDoc.destinationId = storage._id;
                            transferinDoc.items = validTransferOutDoc.items;
                            transferinDoc.reference = validTransferOutDoc.code;

                            var spkDoc = {};
                            spkDoc.source = storage;
                            spkDoc.sourceId = storage._id;
                            spkDoc.destination = validTransferOutDoc.destination;
                            spkDoc.destinationId = validTransferOutDoc.destinationId;
                            spkDoc.items = validTransferOutDoc.items;
                            spkDoc.packingList = generateCode(modulePackingList);
                            spkDoc.isDraft = false;
                            spkDoc.isReceived = false;
                            spkDoc.reference = validTransferOutDoc.code;

                            var ekspedisiDoc = {};
                            ekspedisiDoc.destination = validTransferOutDoc.destination;
                            ekspedisiDoc.destinationId = validTransferOutDoc.destinationId;
                            ekspedisiDoc.items = validTransferOutDoc.items;
                            ekspedisiDoc.expedition = "Dikirim Sendiri";
                            ekspedisiDoc.weight = 0;

                            this.transferOutDocManager.create(validTransferOutDoc)
                                .then(id => {
                                    this.pusatReturTokoTerimaBarangReturManager.create(transferinDoc);
                                    this.spkBarangJadiReturManager.create(spkDoc);
                                    this.pusatBarangBaruKirimBarangJadiAksesorisManager.create(ekspedisiDoc);
                                    resolve(id);
                                })
                                .catch(e => {
                                    reject(e);
                                })
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        })

    }

    update(transferOutDoc) {
        return new Promise((resolve, reject) => {
            this._validate(transferOutDoc)
                .then(validTransferOutDoc => {
                    this.transferOutDocManager.update(validTransferOutDoc)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(ex => {
                            reject(ex);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    delete(transferOutDoc) {
        return new Promise((resolve, reject) => {
            this._validate(transferOutDoc)
                .then(validTransferOutDoc => {
                    validTransferOutDoc._deleted = true;
                    this.transferOutDocManager.update(validTransferOutDoc)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    _validate(transferOutDoc) {
        var errors={};
        return new Promise((resolve, reject) => {
            var valid = transferOutDoc;
            this.moduleManager.getByCode(moduleId)
                .then(module => {
                    var config = module.config;
                    if (!valid.sourceId || valid.sourceId == '')
                        errors["sourceId"] = "sourceId is required";
                    else {
                        if (config) {
                            if (config.source) {
                                var isAny = false;
                                if (config.source.type == "selection") {
                                    for (var sourceId of config.source.value) {
                                        if (sourceId.toString() == valid.sourceId.toString()) {
                                            isAny = true;
                                            break;
                                        }
                                    }
                                }
                                else {
                                    if (config.source.value.toString() == valid.sourceId.toString())
                                        isAny = true;
                                }
                                if (!isAny)
                                    errors["sourceId"] = "sourceId is not valid";
                            }
                        }
                    }

                    if (!valid.destinationId || valid.destinationId == '')
                        errors["destinationId"] = "destinationId is required";
                    else {
                        if (config) {
                            if (config.destination) {
                                var isAny = false;
                                if (config.destination.type == "selection") {
                                    for (var destinationId of config.destination.value) {
                                        if (destinationId.toString() == valid.destinationId.toString()) {
                                            isAny = true;
                                            break;
                                        }
                                    }
                                }
                                else {
                                    if (config.destination.value.toString() == valid.destinationId.toString())
                                        isAny = true;
                                }
                                if (!isAny)
                                    errors["destinationId"] = "destinationId is not valid";
                            }
                        }
                    }
                    var getItem = [];
                    if (valid.items && valid.items.length > 0) {
                        for (var item of valid.items) {
                            getItem.push(this.inventoryManager.getByStorageIdAndArticleVarianIdOrDefault(valid.sourceId, item.articleVariantId))
                        }
                    }
                    else {
                        errors["items"] = "items is required";
                    }

                    Promise.all(getItem)
                        .then(results => {
                            var index = 0;
                            var itemErrors = [];
                            var itemError = {};

                            if (results.length > 0) {
                                for (var item of valid.items) {
                                    if (results[index] == null) {
                                        var inventoryQuantity = 0;
                                    } else {
                                        var inventoryQuantity = results[index].quantity;
                                    }
                                    index++;
                                    if (item.quantity > inventoryQuantity) {
                                        itemError["quantity"] = "Tidak bisa simpan jika Quantity Pengiriman > Quantity Stock";
                                    }
                                    itemErrors.push(itemError);
                                }
                            }
                            for (var itemError of itemErrors) {
                                for (var prop in itemError) {
                                    errors.items = itemErrors;
                                    break;
                                }
                                if (errors.items)
                                    break;
                            }
                            for (var prop in errors) {
                                var ValidationError = require('../../validation-error');
                                reject(new ValidationError('data does not pass validation', errors));
                            }
                            resolve(valid);
                        }).catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });
        });
    }
};

<|endoftext|>


<commit_before>/*!
 * jQuery GrewForm Plugin v0.0.3
 *
 * Copyright 2011, Artem Suschev
 * Grandcapital Ltd.
 *
 * Licensed under the MIT license (license.txt)
 */
(function() {
    jQuery.fn.grewform = function(options) {

        //this will allow selectors like 'input[value=foo]' to work with all jQuery versions
        jQuery('input,textarea').live('keyup change', function(e) {
            var ignore_codes = [33,34,36,35,45,38,40,37,39];//arrows and others
            if (e.keyCode && jQuery.inArray(e.keyCode, ignore_codes) < 0)//ignore this keyUps to let this keys work as expected
            {
                jQuery(this).attr('value', this.value);
            }
        });

        var form = this;

        for (var rule_key in options) {
            var rule = new Rule(rule_key, form, options[rule_key]);
        }

        //wait 300ms after keyup
        form.find('*').keyup(function() {
            var wait = setInterval(function() {
                    clearInterval(wait)
                    run_rules()
                },
                300)
        });

        //run on DOM loaded
        jQuery(document).ready(function() {
            run_rules()
        });

        //run after every change
        return form.find('*').change(function() {
            run_rules()
        });
    };

    //reset all rules
    jQuery.fn.grewformReset = function() {
        Rule.id = undefined;
        Rule.all = [];
    };

    function debug(str) {
        //console.log('jQuery.brForms >>> '+str)
    }

    function run_rules() {
        //debug(checking rules')

        //first run all unmatch actions
        jQuery.each(Rule.all, function(i, rule) {
            (function(rule) {
                var wait = setInterval(
                    function() {
                        try {
                            if (!Rule.form.find('*').is(":animated")) {
                                clearInterval(wait);
                                if (rule.unmatches()) {
                                    rule.run_unmatch_actions()
                                }
                            }
                        }
                        catch(e) {
                            clearInterval(wait);
                        }
                    },
                    200);
            }(rule));
        })

        //then run all math actions
        jQuery.each(Rule.all, function(i, rule) {
            (function(rule) {
                var wait = setInterval(
                    function() {
                        try {
                            if (!Rule.form.find('*').is(":animated")) {
                                clearInterval(wait);
                                if (rule.matches()) {
                                    rule.run_match_actions()
                                }
                            }
                        }
                        catch(e) {
                            clearInterval(wait);
                        }
                    },
                    200);
            }(rule));
        })
    }

//constructor for rules
    function Rule(selector, form, raw_rule) {
        if (typeof Rule.id == 'undefined') {
            //unique id for rules
            Rule.id = 0
            //special blip to mark DOM elements witch invoke rule actions
            Rule.blip_ptr = 'hgo_grewform_rule'
            //function for cascade unmatch
            Rule.unmtach_by_blip = function(blip) {
                jQuery.each(Rule.all, function(i, rule) {
                    if (rule.blip === blip) {
                        //debug('unmtach_by_blip '+blip)
                        rule.run_unmatch_actions()
                    }
                })
            }

            //All rules (hello Django:])
            Rule.all = [];
            Rule.form = form;
        }

        this.id = Rule.id
        Rule.id = Rule.id + 1
        this.blip = Rule.blip_ptr + this.id
        this.selectors = arrayfy(('' + selector).split('AND')) //selectors of the rule
        jQuery.each(this.selectors, function(selectors) {
            return function(k, v) {
                selectors[k] = jQuery.trim('' + v)
            }
        }(this.selectors))//trim each selector
        this.selector = arr_to_selector(this.selectors)//selector of the rule
        this.trigged = false//indicates is rule trigged or not
        this.match_actions = []
        this.unmatch_actions = []
        this.raw = raw_rule
        this.raw_selector = selector

        //extract actions
        for (var action_key in raw_rule) {
            generate_actions(action_key, form, this);
        }

        //debug('created rule: '+this.selector +'['+ this.match_actions.length +'|'+this.unmatch_actions.length+']')

        this.matches = function() {
            for (var i = 0; i < this.selectors.length; i++) {
                var selector = this.selectors[i]
                if ((!this.trigged)) {
                    //('option:visible') always return nothing
                    if (Rule.form.find(selector).filter('option:first').length > 0) {
                        if (Rule.form.find(selector).parent('select:visible:first').length === 0) {
                            return false;
                        }
                    }
                    else if (Rule.form.find(selector).filter(':visible:first').length === 0) {
                        return false;
                    }

                }
                else {
                    return false
                }
            }
            return true
        }

        this.unmatches = function() {
            if (!this.trigged) {
                return false;
            }

            for (var i = 0; i < this.selectors.length; i++) {
                var selector = this.selectors[i]
                if (Rule.form.find(selector + ':first').length === 0) {
                    return true;
                }
            }

            return false
        }

        this.run_match_actions = function() {
            debug('match: ' + this.raw_selector)

            this.trigged = true
            //mark elements that rule trigged, it's need for cascade actions
            Rule.form.find(this.selector).addClass(this.blip)
            for (var i = 0; i < this.match_actions.length; i++) {
                var action = this.match_actions[i]
                action.call(this)
            }
        }
        this.run_match_actions.first_run = true

        this.run_unmatch_actions = function() {
            debug('unmatch: ' + this.raw_selector)

            this.trigged = false
            jQuery('.' + this.blip).removeClass(this.blip)
            for (var i = 0; i < this.unmatch_actions.length; i++) {
                var action = this.unmatch_actions[i]
                action.call(this)
            }
        }

        Rule.all.push(this)
    }

    function generate_actions(key, form, rule) {
        //genereting different actions
        switch (key) {
            case 'show':
                rule.match_actions.push(
                    function(elems) {
                        return function() {
                            //debug('show action');
                            if (elems.is('option')) {
                                elems.show();
                            }
                            else {
                                elems.slideDown();
                            }
                        }
                    }(form.find(rule.raw[key])))

                rule.unmatch_actions.push(
                    function(elems) {
                        return function() {
                            //debug('show action rollback');
                            cascade_unmatch(elems);
                            if (elems.is('option')) {
                                elems.hide();
                            }
                            else {
                                elems.slideUp();
                            }
                        }
                    }(form.find(rule.raw[key])))
                break
            case 'hide':
                rule.match_actions.push(
                    function(elems) {
                        return function() {
                            //debug('hide action');
                            if (elems.is('option')) {
                                elems.hide();
                            }
                            else {
                                elems.slideUp();
                            }
                        }
                    }(form.find(rule.raw[key])))

                rule.unmatch_actions.push(
                    function(elems) {
                        return function() {
                            //debug('hide action rollback');
                            cascade_unmatch(elems);
                            if (elems.is('option')) {
                                elems.show();
                            }
                            else {
                                elems.slideDown();
                            }
                        }
                    }(form.find(rule.raw[key])))
                break
            case 'set_value':
                rule.match_actions.push(
                    function(values) {
                        return function() {
                            //debug('value action');

                            var rule = this
                            jQuery.each(values, function(selector, value) {
                                jQuery.each(Rule.form.find(selector), function() {
                                    var tagName = jQuery(this).tagName

                                    if (tagName == 'select') {
                                        elems.find('option').removeAttr('selected')
                                        elems.find('option [value=' + value + ']').attr('selected', 'selected')
                                    }
                                    else {
                                        jQuery(this).val(value);
                                    }
                                })
                            })
                        }
                    }(rule.raw[key]))
                break
            case 'add_options':
                for (var selector in rule.raw[key]) {
                    var options = rule.raw[key][selector]

                    if (typeof options == 'function') {
                        rule.match_actions.push(
                            function(e, selector, fn) {
                                return function() {
                                    var options = fn()
                                    for (var v in options) {
                                        //debug('add_options action')
                                        var selects = e.find(selector)
                                        jQuery('<option></option>').html(options[v]).val(v).appendTo(selects);
                                    }

                                    //small trick with callable options:
                                    //we should determine what to remove from DOM right after we add it!
                                    if (this.run_match_actions.first_run) {
                                        for (var v in options) {
                                            this.unmatch_actions.push(
                                                function(e, selector, v) {
                                                    return function() {
                                                        //debug('add_options action rollback');
                                                        cascade_unmatch(e.children(selector).children('option[value=' + v + ']'))
                                                        e.find(selector).children().remove('option[value=' + v + ']')
                                                    }
                                                }(form, selector, v))
                                        }
                                        //for adding unmatch actions only once!
                                        this.run_match_actions.first_run = false
                                    }
                                }
                            }(form, selector, options))
                    }
                    else {
                        for (var v in options) {
                            rule.match_actions.push(
                                function(e, selector, v, h) {
                                    return function() {
                                        //debug('add_options action')
                                        var selects = e.find(selector)
                                        jQuery('<option></option>').html(h).val(v).appendTo(selects);
                                    }
                                }(form, selector, v, options[v]))
                            rule.unmatch_actions.push(
                                function(e, selector, v) {
                                    return function() {
                                        //debug('add_options action rollback');
                                        cascade_unmatch(e.children(selector).children('option[value=' + v + ']'))
                                        e.find(selector).children().remove('option[value=' + v + ']')
                                    }
                                }(form, selector, v))
                        }
                    }
                }
                break
            case 'disable':
                rule.match_actions.push(
                    function(elems) {
                        return function() {
                            //debug('disable action');
                            elems.attr('disabled', 'disabled');
                        }
                    }(form.find(rule.raw[key])))

                rule.unmatch_actions.push(
                    function(elems) {
                        return function() {
                            //debug('disable action rollback');
                            cascade_unmatch(elems);
                            elems.removeAttr('disabled');
                        }
                    }(form.find(rule.raw[key])))
                break
            case 'enable':
                rule.match_actions.push(
                    function(elems) {
                        return function() {
                            //debug('enable action');
                            elems.removeAttr('disabled');
                        }
                    }(form.find(rule.raw[key])))

                rule.unmatch_actions.push(
                    function(elems) {
                        return function() {
                            //debug('enable action rollback');
                            cascade_unmatch(elems);
                            elems.attr('disabled', 'disabled');
                        }
                    }(form.find(rule.raw[key])))
                break
            case 'check':
                rule.match_actions.push(
                    function(elems) {
                        return function() {
                            //debug('check action');
                            elems.attr('checked', 'checked');
                        }
                    }(form.find(rule.raw[key])))

                rule.unmatch_actions.push(
                    function(elems) {
                        return function() {
                            //debug('check action rollback');
                            cascade_unmatch(elems);
                            elems.removeAttr('checked');
                        }
                    }(form.find(rule.raw[key])))
                break
            case 'uncheck':
                rule.match_actions.push(
                    function(elems) {
                        return function() {
                            //debug('uncheck action');
                            elems.removeAttr('checked');
                        }
                    }(form.find(rule.raw[key])))

                rule.unmatch_actions.push(
                    function(elems) {
                        return function() {
                            //debug('uncheck action rollback');
                            cascade_unmatch(elems);
                            elems.attr('checked', 'checked');
                        }
                    }(form.find(rule.raw[key])))
                break
            case 'custom':
                rule.match_actions.push(
                    function(fn, context) {
                        return function() {
                            fn.call(context)
                        }
                    }(rule.raw[key]['match'], jQuery(rule.selector)))

                rule.unmatch_actions.push(
                    function(fn, context) {
                        return function() {
                            fn.call(context)
                        }
                    }(rule.raw[key]['unmatch'], jQuery(rule.selector)))
                break
            default:
                return;
        }
    }

    function cascade_unmatch(elements) {
        jQuery.each(elements, function(k, v) {
            if (jQuery(this).attr('class') !== undefined) {
                var classes = jQuery(this).attr('class').split(' ');
            }
            else {
                return;
            }

            jQuery.each(classes, function(k, v) {
                Rule.unmtach_by_blip(v);
            })
            cascade_unmatch(elements.children())
        })
    }

    function arrayfy(obj) {
        if (obj.constructor !== Array) {
            return [obj];
        }

        return obj;
    }

    function arr_to_selector(arr) {
        res = ''
        for (var i = 0; i < arr.length; i++) {
            res += jQuery.trim('' + arr[i]) + ',';
        }

        return res
    }
})();
<commit_msg>Added jQuery.fn.grewform.runRules to enable manual run of rules. Changed jQuery.fn.grewformReset to jQuery.fn.grewform.reset which feels like a better name for the function<commit_after>/*!
 * jQuery GrewForm Plugin v0.0.3
 *
 * Copyright 2011, Artem Suschev
 * Grandcapital Ltd.
 *
 * Licensed under the MIT license (license.txt)
 */
(function() {
    jQuery.fn.grewform = function(options) {

        //this will allow selectors like 'input[value=foo]' to work with all jQuery versions
        jQuery('input,textarea').live('keyup change', function(e) {
            var ignore_codes = [33,34,36,35,45,38,40,37,39];//arrows and others
            if (e.keyCode && jQuery.inArray(e.keyCode, ignore_codes) < 0)//ignore this keyUps to let this keys work as expected
            {
                jQuery(this).attr('value', this.value);
            }
        });

        var form = this;

        for (var rule_key in options) {
            var rule = new Rule(rule_key, form, options[rule_key]);
        }

        //wait 300ms after keyup
        form.find('*').keyup(function() {
            var wait = setInterval(function() {
                    clearInterval(wait)
                    run_rules()
                },
                300)
        });

        //run on DOM loaded
        jQuery(document).ready(function() {
            run_rules()
        });

        //run after every change
        return form.find('*').change(function() {
            run_rules()
        });
    };

    //reset all rules
    jQuery.fn.grewform.reset = function() {
        Rule.id = undefined;
        Rule.all = [];
    };

    jQuery.fn.grewform.runRules = function() {
        run_rules();
    };

    function debug(str) {
        //console.log('jQuery.brForms >>> '+str)
    }

    function run_rules() {
        //debug(checking rules')

        //first run all unmatch actions
        jQuery.each(Rule.all, function(i, rule) {
            (function(rule) {
                var wait = setInterval(
                    function() {
                        try {
                            if (!Rule.form.find('*').is(":animated")) {
                                clearInterval(wait);
                                if (rule.unmatches()) {
                                    rule.run_unmatch_actions()
                                }
                            }
                        }
                        catch(e) {
                            clearInterval(wait);
                        }
                    },
                    200);
            }(rule));
        })

        //then run all math actions
        jQuery.each(Rule.all, function(i, rule) {
            (function(rule) {
                var wait = setInterval(
                    function() {
                        try {
                            if (!Rule.form.find('*').is(":animated")) {
                                clearInterval(wait);
                                if (rule.matches()) {
                                    rule.run_match_actions()
                                }
                            }
                        }
                        catch(e) {
                            clearInterval(wait);
                        }
                    },
                    200);
            }(rule));
        })
    }

//constructor for rules
    function Rule(selector, form, raw_rule) {
        if (typeof Rule.id == 'undefined') {
            //unique id for rules
            Rule.id = 0
            //special blip to mark DOM elements witch invoke rule actions
            Rule.blip_ptr = 'hgo_grewform_rule'
            //function for cascade unmatch
            Rule.unmtach_by_blip = function(blip) {
                jQuery.each(Rule.all, function(i, rule) {
                    if (rule.blip === blip) {
                        //debug('unmtach_by_blip '+blip)
                        rule.run_unmatch_actions()
                    }
                })
            }

            //All rules (hello Django:])
            Rule.all = [];
            Rule.form = form;
        }

        this.id = Rule.id
        Rule.id = Rule.id + 1
        this.blip = Rule.blip_ptr + this.id
        this.selectors = arrayfy(('' + selector).split('AND')) //selectors of the rule
        jQuery.each(this.selectors, function(selectors) {
            return function(k, v) {
                selectors[k] = jQuery.trim('' + v)
            }
        }(this.selectors))//trim each selector
        this.selector = arr_to_selector(this.selectors)//selector of the rule
        this.trigged = false//indicates is rule trigged or not
        this.match_actions = []
        this.unmatch_actions = []
        this.raw = raw_rule
        this.raw_selector = selector

        //extract actions
        for (var action_key in raw_rule) {
            generate_actions(action_key, form, this);
        }

        //debug('created rule: '+this.selector +'['+ this.match_actions.length +'|'+this.unmatch_actions.length+']')

        this.matches = function() {
            for (var i = 0; i < this.selectors.length; i++) {
                var selector = this.selectors[i]
                if ((!this.trigged)) {
                    //('option:visible') always return nothing
                    if (Rule.form.find(selector).filter('option:first').length > 0) {
                        if (Rule.form.find(selector).parent('select:visible:first').length === 0) {
                            return false;
                        }
                    }
                    else if (Rule.form.find(selector).filter(':visible:first').length === 0) {
                        return false;
                    }

                }
                else {
                    return false
                }
            }
            return true
        }

        this.unmatches = function() {
            if (!this.trigged) {
                return false;
            }

            for (var i = 0; i < this.selectors.length; i++) {
                var selector = this.selectors[i]
                if (Rule.form.find(selector + ':first').length === 0) {
                    return true;
                }
            }

            return false
        }

        this.run_match_actions = function() {
            debug('match: ' + this.raw_selector)

            this.trigged = true
            //mark elements that rule trigged, it's need for cascade actions
            Rule.form.find(this.selector).addClass(this.blip)
            for (var i = 0; i < this.match_actions.length; i++) {
                var action = this.match_actions[i]
                action.call(this)
            }
        }
        this.run_match_actions.first_run = true

        this.run_unmatch_actions = function() {
            debug('unmatch: ' + this.raw_selector)

            this.trigged = false
            jQuery('.' + this.blip).removeClass(this.blip)
            for (var i = 0; i < this.unmatch_actions.length; i++) {
                var action = this.unmatch_actions[i]
                action.call(this)
            }
        }

        Rule.all.push(this)
    }

    function generate_actions(key, form, rule) {
        //genereting different actions
        switch (key) {
            case 'show':
                rule.match_actions.push(
                    function(elems) {
                        return function() {
                            //debug('show action');
                            if (elems.is('option')) {
                                elems.show();
                            }
                            else {
                                elems.slideDown();
                            }
                        }
                    }(form.find(rule.raw[key])))

                rule.unmatch_actions.push(
                    function(elems) {
                        return function() {
                            //debug('show action rollback');
                            cascade_unmatch(elems);
                            if (elems.is('option')) {
                                elems.hide();
                            }
                            else {
                                elems.slideUp();
                            }
                        }
                    }(form.find(rule.raw[key])))
                break
            case 'hide':
                rule.match_actions.push(
                    function(elems) {
                        return function() {
                            //debug('hide action');
                            if (elems.is('option')) {
                                elems.hide();
                            }
                            else {
                                elems.slideUp();
                            }
                        }
                    }(form.find(rule.raw[key])))

                rule.unmatch_actions.push(
                    function(elems) {
                        return function() {
                            //debug('hide action rollback');
                            cascade_unmatch(elems);
                            if (elems.is('option')) {
                                elems.show();
                            }
                            else {
                                elems.slideDown();
                            }
                        }
                    }(form.find(rule.raw[key])))
                break
            case 'set_value':
                rule.match_actions.push(
                    function(values) {
                        return function() {
                            //debug('value action');

                            var rule = this
                            jQuery.each(values, function(selector, value) {
                                jQuery.each(Rule.form.find(selector), function() {
                                    var tagName = jQuery(this).tagName

                                    if (tagName == 'select') {
                                        elems.find('option').removeAttr('selected')
                                        elems.find('option [value=' + value + ']').attr('selected', 'selected')
                                    }
                                    else {
                                        jQuery(this).val(value);
                                    }
                                })
                            })
                        }
                    }(rule.raw[key]))
                break
            case 'add_options':
                for (var selector in rule.raw[key]) {
                    var options = rule.raw[key][selector]

                    if (typeof options == 'function') {
                        rule.match_actions.push(
                            function(e, selector, fn) {
                                return function() {
                                    var options = fn()
                                    for (var v in options) {
                                        //debug('add_options action')
                                        var selects = e.find(selector)
                                        jQuery('<option></option>').html(options[v]).val(v).appendTo(selects);
                                    }

                                    //small trick with callable options:
                                    //we should determine what to remove from DOM right after we add it!
                                    if (this.run_match_actions.first_run) {
                                        for (var v in options) {
                                            this.unmatch_actions.push(
                                                function(e, selector, v) {
                                                    return function() {
                                                        //debug('add_options action rollback');
                                                        cascade_unmatch(e.children(selector).children('option[value=' + v + ']'))
                                                        e.find(selector).children().remove('option[value=' + v + ']')
                                                    }
                                                }(form, selector, v))
                                        }
                                        //for adding unmatch actions only once!
                                        this.run_match_actions.first_run = false
                                    }
                                }
                            }(form, selector, options))
                    }
                    else {
                        for (var v in options) {
                            rule.match_actions.push(
                                function(e, selector, v, h) {
                                    return function() {
                                        //debug('add_options action')
                                        var selects = e.find(selector)
                                        jQuery('<option></option>').html(h).val(v).appendTo(selects);
                                    }
                                }(form, selector, v, options[v]))
                            rule.unmatch_actions.push(
                                function(e, selector, v) {
                                    return function() {
                                        //debug('add_options action rollback');
                                        cascade_unmatch(e.children(selector).children('option[value=' + v + ']'))
                                        e.find(selector).children().remove('option[value=' + v + ']')
                                    }
                                }(form, selector, v))
                        }
                    }
                }
                break
            case 'disable':
                rule.match_actions.push(
                    function(elems) {
                        return function() {
                            //debug('disable action');
                            elems.attr('disabled', 'disabled');
                        }
                    }(form.find(rule.raw[key])))

                rule.unmatch_actions.push(
                    function(elems) {
                        return function() {
                            //debug('disable action rollback');
                            cascade_unmatch(elems);
                            elems.removeAttr('disabled');
                        }
                    }(form.find(rule.raw[key])))
                break
            case 'enable':
                rule.match_actions.push(
                    function(elems) {
                        return function() {
                            //debug('enable action');
                            elems.removeAttr('disabled');
                        }
                    }(form.find(rule.raw[key])))

                rule.unmatch_actions.push(
                    function(elems) {
                        return function() {
                            //debug('enable action rollback');
                            cascade_unmatch(elems);
                            elems.attr('disabled', 'disabled');
                        }
                    }(form.find(rule.raw[key])))
                break
            case 'check':
                rule.match_actions.push(
                    function(elems) {
                        return function() {
                            //debug('check action');
                            elems.attr('checked', 'checked');
                        }
                    }(form.find(rule.raw[key])))

                rule.unmatch_actions.push(
                    function(elems) {
                        return function() {
                            //debug('check action rollback');
                            cascade_unmatch(elems);
                            elems.removeAttr('checked');
                        }
                    }(form.find(rule.raw[key])))
                break
            case 'uncheck':
                rule.match_actions.push(
                    function(elems) {
                        return function() {
                            //debug('uncheck action');
                            elems.removeAttr('checked');
                        }
                    }(form.find(rule.raw[key])))

                rule.unmatch_actions.push(
                    function(elems) {
                        return function() {
                            //debug('uncheck action rollback');
                            cascade_unmatch(elems);
                            elems.attr('checked', 'checked');
                        }
                    }(form.find(rule.raw[key])))
                break
            case 'custom':
                rule.match_actions.push(
                    function(fn, context) {
                        return function() {
                            fn.call(context)
                        }
                    }(rule.raw[key]['match'], jQuery(rule.selector)))

                rule.unmatch_actions.push(
                    function(fn, context) {
                        return function() {
                            fn.call(context)
                        }
                    }(rule.raw[key]['unmatch'], jQuery(rule.selector)))
                break
            default:
                return;
        }
    }

    function cascade_unmatch(elements) {
        jQuery.each(elements, function(k, v) {
            if (jQuery(this).attr('class') !== undefined) {
                var classes = jQuery(this).attr('class').split(' ');
            }
            else {
                return;
            }

            jQuery.each(classes, function(k, v) {
                Rule.unmtach_by_blip(v);
            })
            cascade_unmatch(elements.children())
        })
    }

    function arrayfy(obj) {
        if (obj.constructor !== Array) {
            return [obj];
        }

        return obj;
    }

    function arr_to_selector(arr) {
        res = ''
        for (var i = 0; i < arr.length; i++) {
            res += jQuery.trim('' + arr[i]) + ',';
        }

        return res
    }
})();
<|endoftext|>


<commit_before>/*****************************************************************************************************************
 *    VGridMarkupGenerator
 *    This generates all htmlstring needed for row/headers templates when needed
 *    Created by vegar ringdal
 *
 ****************************************************************************************************************/
export class VGridMarkupGenerator {

  constructor(vGrid) {
    this.vGrid = vGrid;
  }

  generate() {
    let columnsToUse = [];
    let type = null;

    if (this.vGrid.vGridColumns && this.vGrid.vGridColumns.length > 0) {
      columnsToUse = this.vGrid.vGridColumns;
      type = 'typeArray'
    }

    if (this.vGrid.vGridConfig.colConfig && this.vGrid.vGridConfig.colConfig.length > 0) {
      columnsToUse = this.colConfig;
      type = 'typeHtml'
    }

    if (!type) {
      throw new Error('column setup missing');
    }

    if (type === 'typeArray') {
      this.vGrid.vGridConfig.colConfig = this.vGrid.vGridColumns;
      this.vGrid.vGridConfig.columnLength = this.vGrid.vGridColumns.length;
    }
    this.processColumns(this.vGrid.vGridConfig.colConfig);

  }

  processColumns(array) {

    array.forEach((col, index)=> {

      //we need attribute or rowtemplate, else throm error
      if (!col.colField && !col.colRowTemplate) {
        throw new Error('colField is not set on column', index);
      }

      //set default, some can be missing
      col.colType = col.colType || "text";
      col.colFilterTop = col.colFilterTop || false;
      col.colHeaderName = col.colHeaderName || this.getAttribute(col.colField, true);
      col.colWidth = col.colWidth || 100;
      col.colCss = col.colCss || '';
      col.colField = this.checkAttribute(col.colField);

      //if selection type
      if (col.colType === "selection") {
        //override to manual selection
        this.vGrid.vGridConfig.attManualSelection = true;
        //set template
        col.colHeaderTemplate = `<input class="vgrid-row-checkbox-100" v-selection="header" type="checkbox">`;
        col.colRowTemplate = `<input class="vgrid-row-checkbox-100"  v-selection="row" type="checkbox" >`;

      } else {

        //does a rowTemplate exist, if not we create one, else we skip it
        if (!col.colRowTemplate) {
          if (col.colType === "image") {
            this.createImageRowMarkup(col);
          } else {
            this.createInputRowMarkup(col);
          }
        }

        if (!col.colHeaderTemplate) {
          if (col.colType === "image") {
            var inputHeader = "";
            var labelHeader = this.createLabelMarkup(col);
          } else {
            var inputHeader = this.createInputHeaderMarkup(col);
            var labelHeader = this.createLabelMarkup(col);
          }
          if (col.colFilterTop) {
            col.colHeaderTemplate = inputHeader + labelHeader;
          } else {
            col.colHeaderTemplate = labelHeader + inputHeader;
          }
        }
      }

    });
  }

  //simple way to get get attribute, this can prb be done better...
  getAttribute = function (value, capitalize) {
    if (value) {
      value = value.replace('rowRef.', '');
      value = value.replace('tempRef.', '');
      let newValue = "";
      let done = false;
      for (var x = 0; x < value.length; x++) {
        let letter = value.charAt(x);
        if (!done && letter !== " " && letter !== "&" && letter !== "|" && letter !== ":") {
          newValue = newValue + letter;
        } else {
          done = true;
        }
      }
      if (capitalize) {
        return newValue.charAt(0).toUpperCase() + newValue.slice(1);
      } else {
        return newValue;
      }

    } else {
      return "missing!";
    }
  };

  checkAttribute(attribute){
    //not the best way... temp fix so they dont haveto write rowRef...
    if(attribute){
      if(attribute.indexOf("rowRef") === -1 && attribute.indexOf("tempRef") === -1){
          return "rowRef."+attribute;
      } else {
        return attribute;
      }
    } else {
      return attribute;
    }

  }

  createImageRowMarkup(col) {
    //get the values/settings
    let classNames = 'class="vgrid-image-round"';
    let attributeRow = col.colAddRowAttributes ? col.colAddRowAttributes : '';
    let css = col.colCss ? `css="${col.colCss}"` : '';

    //insert the markup
    col.colRowTemplate = `<image ${css} ${classNames} v-image-fix ${attributeRow} src.bind="${col.colField}">`;

  }

  createInputRowMarkup(col) {
    //get the values/settings
    let classNames = `class="${col.colType === "checkbox" ? 'vgrid-row-checkbox-100' : 'vgrid-row-input'}"`;

    //type
    let type = `type="${col.colType}"`;

    //get attributes row
    let colAddRowAttributes = col.colAddRowAttributes ? col.colAddRowAttributes : '';

    //get css
    let css = col.colCss ? `css="${col.colCss}"` : '';

    //is it a checkbox?
    //todo: adding the update part without choice, maybe param for that?
    if (col.colType === "checkbox") {
      col.colRowTemplate = `<input v-observe-field="${this.getAttribute(col.colField)}" ${css} ${classNames} ${type} ${colAddRowAttributes}  checked.bind="${col.colField}">`;
    } else {
      col.colRowTemplate = `<input v-observe-field=${this.getAttribute(col.colField)} ${css} ${classNames} ${type} ${colAddRowAttributes}  value.bind="${col.colField}">`;
    }

  }

  createInputHeaderMarkup(col) {

    //is it filter ?
    let markup;
    if (col.colFilter) {

      //type
      let type = `type="${col.colType}"`;

      //filter
      let filter = col.colFilter ? `v-filter="${col.colFilter}"` : '';

      //get attributes label
      let colAddFilterAttributes = col.colAddFilterAttributes ? col.colAddFilterAttributes : '';

      //is it a checkbox ?
      let classNames = '';
      if (col.colType === "checkbox") {
        classNames = `class="${col.colFilterTop ? 'vgrid-row-checkbox-50' : 'vgrid-row-checkbox-50'}"`;
      } else {
        classNames = `class="${col.colFilterTop ? 'vgrid-header-input-top' : 'vgrid-header-input-bottom'}"`;
      }

      //apply magic
      markup = `<input  ${classNames} ${colAddFilterAttributes} ${type} ${filter}">`;
    } else {
      markup = '';
    }
    //return the markup
    return markup;

  }

  createLabelMarkup(col) {
    //get the values/settings
    let filterClass = col.colFilter ? `${col.colFilterTop ? 'vgrid-label-bottom' : 'vgrid-label-top'}` : 'vgrid-label-full';

    let dragDropClass = this.vGrid.vGridConfig.attSortableHeader ? 'vGrid-vGridDragHandle' : '';

    let classname = `class="${dragDropClass} ${filterClass}"`;

    let colAddLabelAttributes = col.colAddLabelAttributes ? col.colAddLabelAttributes : '';

    let sort = col.colSort ? `v-sort="${col.colSort}"` : '';

    //apply magic
    //todo, atm Im adding resize columns and dragdrop columns, should this be a choice?
    let markup = `<p v-drag-drop-col v-resize-col ${classname} ${sort} ${colAddLabelAttributes}>${col.colHeaderName}</p>`;
    //return the markup
    return markup;
  }

}
<commit_msg>fix (markup-generator): quick fix for arrow/tabbing on selection column<commit_after>/*****************************************************************************************************************
 *    VGridMarkupGenerator
 *    This generates all htmlstring needed for row/headers templates when needed
 *    Created by vegar ringdal
 *
 ****************************************************************************************************************/
export class VGridMarkupGenerator {

  constructor(vGrid) {
    this.vGrid = vGrid;
  }

  generate() {
    let columnsToUse = [];
    let type = null;

    if (this.vGrid.vGridColumns && this.vGrid.vGridColumns.length > 0) {
      columnsToUse = this.vGrid.vGridColumns;
      type = 'typeArray'
    }

    if (this.vGrid.vGridConfig.colConfig && this.vGrid.vGridConfig.colConfig.length > 0) {
      columnsToUse = this.colConfig;
      type = 'typeHtml'
    }

    if (!type) {
      throw new Error('column setup missing');
    }

    if (type === 'typeArray') {
      this.vGrid.vGridConfig.colConfig = this.vGrid.vGridColumns;
      this.vGrid.vGridConfig.columnLength = this.vGrid.vGridColumns.length;
    }
    this.processColumns(this.vGrid.vGridConfig.colConfig);

  }

  processColumns(array) {

    array.forEach((col, index)=> {

      //we need attribute or rowtemplate, else throm error
      if (!col.colField && !col.colRowTemplate) {
        throw new Error('colField is not set on column', index);
      }

      //set default, some can be missing
      col.colType = col.colType || "text";
      col.colFilterTop = col.colFilterTop || false;
      col.colHeaderName = col.colHeaderName || this.getAttribute(col.colField, true);
      col.colWidth = col.colWidth || 100;
      col.colCss = col.colCss || '';
      col.colField = this.checkAttribute(col.colField);

      //if selection type
      if (col.colType === "selection") {
        //override to manual selection
        this.vGrid.vGridConfig.attManualSelection = true;
        //set template
        col.colHeaderTemplate = `<input class="vgrid-row-checkbox-100" v-selection="header" type="checkbox">`;
        col.colRowTemplate = `<input v-key-move class="vgrid-row-checkbox-100"  v-selection="row" type="checkbox" >`;

      } else {

        //does a rowTemplate exist, if not we create one, else we skip it
        if (!col.colRowTemplate) {
          if (col.colType === "image") {
            this.createImageRowMarkup(col);
          } else {
            this.createInputRowMarkup(col);
          }
        }

        if (!col.colHeaderTemplate) {
          if (col.colType === "image") {
            var inputHeader = '

';
            if(!col.colFilterTop){
              col.colFilter = "x"
            }
            var labelHeader = this.createLabelMarkup(col);
          } else {
            var inputHeader = this.createInputHeaderMarkup(col);
            var labelHeader = this.createLabelMarkup(col);
          }
          if (col.colFilterTop) {
            col.colHeaderTemplate = inputHeader + labelHeader;
          } else {
            col.colHeaderTemplate = labelHeader + inputHeader;
          }
        }
      }

    });
  }

  //simple way to get get attribute, this can prb be done better...
  getAttribute = function (value, capitalize) {
    if (value) {
      value = value.replace('rowRef.', '');
      value = value.replace('tempRef.', '');
      let newValue = "";
      let done = false;
      for (var x = 0; x < value.length; x++) {
        let letter = value.charAt(x);
        if (!done && letter !== " " && letter !== "&" && letter !== "|" && letter !== ":") {
          newValue = newValue + letter;
        } else {
          done = true;
        }
      }
      if (capitalize) {
        return newValue.charAt(0).toUpperCase() + newValue.slice(1);
      } else {
        return newValue;
      }

    } else {
      return "missing!";
    }
  };

  checkAttribute(attribute){
    //not the best way... temp fix so they dont haveto write rowRef...
    if(attribute){
      if(attribute.indexOf("rowRef") === -1 && attribute.indexOf("tempRef") === -1){
          return "rowRef."+attribute;
      } else {
        return attribute;
      }
    } else {
      return attribute;
    }

  }

  createImageRowMarkup(col) {
    //get the values/settings
    let classNames = 'class="vgrid-image-round"';
    let attributeRow = col.colAddRowAttributes ? col.colAddRowAttributes : '';
    let css = col.colCss ? `css="${col.colCss}"` : '';

    //insert the markup
    col.colRowTemplate = `<image ${css} ${classNames} v-image-fix ${attributeRow} src.bind="${col.colField}">`;

  }

  createInputRowMarkup(col) {
    //get the values/settings
    let classNames = `class="${col.colType === "checkbox" ? 'vgrid-row-checkbox-100' : 'vgrid-row-input'}"`;

    //type
    let type = `type="${col.colType}"`;

    //get attributes row
    let colAddRowAttributes = col.colAddRowAttributes ? col.colAddRowAttributes : '';

    //get css
    let css = col.colCss ? `css="${col.colCss}"` : '';

    //is it a checkbox?
    //todo: adding the update part without choice, maybe param for that?
    if (col.colType === "checkbox") {
      col.colRowTemplate = `<input v-observe-field="${this.getAttribute(col.colField)}" ${css} ${classNames} ${type} ${colAddRowAttributes}  checked.bind="${col.colField}">`;
    } else {
      col.colRowTemplate = `<input v-observe-field=${this.getAttribute(col.colField)} ${css} ${classNames} ${type} ${colAddRowAttributes}  value.bind="${col.colField}">`;
    }

  }

  createInputHeaderMarkup(col) {

    //is it filter ?
    let markup;
    if (col.colFilter) {

      //type
      let type = `type="${col.colType}"`;

      //filter
      let filter = col.colFilter ? `v-filter="${col.colFilter}"` : '';

      //get attributes label
      let colAddFilterAttributes = col.colAddFilterAttributes ? col.colAddFilterAttributes : '';

      //is it a checkbox ?
      let classNames = '';
      if (col.colType === "checkbox") {
        classNames = `class="${col.colFilterTop ? 'vgrid-row-checkbox-50' : 'vgrid-row-checkbox-50'}"`;
      } else {
        classNames = `class="${col.colFilterTop ? 'vgrid-header-input-top' : 'vgrid-header-input-bottom'}"`;
      }

      //apply magic
      markup = `<input  ${classNames} ${colAddFilterAttributes} ${type} ${filter}">`;
    } else {
      markup = '';
    }
    //return the markup
    return markup;

  }

  createLabelMarkup(col) {
    //get the values/settings
    let filterClass = col.colFilter ? `${col.colFilterTop ? 'vgrid-label-bottom' : 'vgrid-label-top'}` : 'vgrid-label-full';

    let dragDropClass = this.vGrid.vGridConfig.attSortableHeader ? 'vGrid-vGridDragHandle' : '';

    let classname = `class="${dragDropClass} ${filterClass}"`;

    let colAddLabelAttributes = col.colAddLabelAttributes ? col.colAddLabelAttributes : '';

    let sort = col.colSort ? `v-sort="${col.colSort}"` : '';

    //apply magic
    //todo, atm Im adding resize columns and dragdrop columns, should this be a choice?
    let markup = `<p v-drag-drop-col v-resize-col ${classname} ${sort} ${colAddLabelAttributes}>${col.colHeaderName}</p>`;
    //return the markup
    return markup;
  }

}
<|endoftext|>