<commit_before>'use strict'

// external deps
var ObjectId = require("mongodb").ObjectId;
var BaseManager = require('../base-manager');

// internal deps
require('mongodb-toolkit');
var DLModels = require('dl-models');
var map = DLModels.map;
var DeliveryOrder = DLModels.purchasing.DeliveryOrder;
var PurchaseOrderManager = require('./purchase-order-manager');
var PurchaseOrderExternalManager = require('./purchase-order-external-manager');

// var PurchaseOrderBaseManager = require('../po/purchase-order-base-manager');
// var DOItem = DLModels.po.DOItem;

module.exports = class DeliveryOrderManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.purchasing.collection.DeliveryOrder);
        this.purchaseOrderManager = new PurchaseOrderManager(db, user);
        this.purchaseOrderExternalManager = new PurchaseOrderExternalManager(db, user);
    }

    _getQuery(paging) {
        var deleted = {
            _deleted: false
        };
        var query = paging.keyword ? {
            '$and': [deleted]
        } : deleted;

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");
            var filteNO = {
                'no': {
                    '$regex': regex
                }
            };
            var filterNRefNo = {
                'refNo': {
                    '$regex': regex
                }
            };
            var filterSupplierName = {
                'supplier.name': {
                    '$regex': regex
                }
            };
            var filterItem = {
                items: {
                    $elemMatch: {
                        'purchaseOrderExternal.no':{
                            '$regex': regex
                        }
                    }
                }
            };
            var $or = {
                '$or': [filteNO, filterNRefNo, filterSupplierName,filterItem]
            };

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

    post(deliveryOrder) {
        return new Promise((resolve, reject) => {
            this._validate(deliveryOrder)
                .then(validDeliveryOrder => {
                    validDeliveryOrder.isPosted = true;
                    this.collection.update(validDeliveryOrder)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    _validate(deliveryOrder) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = deliveryOrder;
            var now = new Date();

            var getDeliveryderPromise = this.collection.singleOrDefault({
                "$and": [{
                    _id: {
                        '$ne': new ObjectId(valid._id)
                    }
                }, {
                        "no": valid.no
                    }]
            });
            Promise.all([getDeliveryderPromise])
                .then(results => {
                    var _module = results[0];
                    if (!valid.no || valid.no == '')
                        errors["no"] = "Nomor surat jalan tidak boleh kosong";
                    else if (_module)
                        errors["no"] = "Nomor surat jalan sudah terdaftar";

                    if (!valid.date || valid.date == '')
                        errors["date"] = "Tanggal surat jalan tidak boleh kosong";
                    else if (valid.date > now)
                        errors["SJDate"] = "Tanggal surat jalan tidak boleh lebih besar dari tanggal hari ini";

                    if (!valid.supplierId || valid.supplierId.toString() == '')
                        errors["supplier"] = "Nama supplier tidak boleh kosong";

                    if (valid.items && valid.items.length < 1) {
                        errors["items"] = "Harus ada minimal 1 nomor po eksternal";
                    } else {
                        var deliveryOrderItemErrors = [];
                        var deliveryOrderItemHasError = false;
                        for (var doItem of valid.items || []) {
                            var purchaseOrderExternalItemErrors = [];
                            var purchaseOrderExternalItemHasErrors = false;
                            var purchaseOrderExternalError = {};

                            if (!doItem.purchaseOrderExternal) {
                                purchaseOrderExternalItemHasErrors = true;
                                purchaseOrderExternalError["purchaseOrderExternal"] = "Purchase order external tidak boleh kosong";
                            }

                            for (var doFulfillment of doItem.fulfillments || []) {
                                var fulfillmentError = {};
                                if (!doFulfillment.deliveredQuantity || doFulfillment.deliveredQuantity == 0) {
                                    purchaseOrderExternalItemHasErrors = true;
                                    fulfillmentError["deliveredQuantity"] = "Jumlah barang diterima tidak boleh kosong";
                                }
                                else if (doFulfillment.deliveredQuantity > doFulfillment.purchaseOrderQuantity) {
                                    purchaseOrderExternalItemHasErrors = true;
                                    fulfillmentError["deliveredQuantity"] = "Jumlah barang diterima tidak boleh lebih besar dari jumlah barang di po eksternal";
                                }
                                purchaseOrderExternalItemErrors.push(fulfillmentError);
                            }
                            if (purchaseOrderExternalItemHasErrors) {
                                deliveryOrderItemHasError = true;
                                purchaseOrderExternalError["fulfillments"] = purchaseOrderExternalItemErrors;
                            }
                            deliveryOrderItemErrors.push(purchaseOrderExternalError);
                        }
                        if (purchaseOrderExternalItemHasErrors)
                            errors["items"] = deliveryOrderItemErrors;
                    }

                    // 2c. begin: check if data has any error, reject if it has.
                    for (var prop in errors) {
                        var ValidationError = require('../../validation-error');
                        reject(new ValidationError('data does not pass validation', errors));
                    }

                    if (!valid.stamp)
                        valid = new DeliveryOrder(valid);

                    valid.stamp(this.user.username, 'manager');
                    resolve(valid);
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    create(deliveryOrder) {
        return new Promise((resolve, reject) => {
            var tasks = [];
            var tasksPoExternal = [];
            var getPurchaseOrderById=[];
            this._validate(deliveryOrder)
                .then(validDeliveryOrder => {
                    this.collection.insert(validDeliveryOrder)
                        .then(id => {
                            //update PO Internal
                            for (var validDeliveryOrderItem of validDeliveryOrder.items) {
                                for (var fulfillmentItem of validDeliveryOrderItem.fulfillments) {
                                    getPurchaseOrderById.push(this.purchaseOrderManager.getSingleById(fulfillmentItem.purchaseOrder._id));
                                }
                                    Promise.all(getPurchaseOrderById)
                                        .then(results => {
                                            for (var result of results) {
                                                var purchaseOrder = result;
                                                for (var poItem of purchaseOrder.items) {
                                                    var doItems = validDeliveryOrderItem.fulfillments;
                                                    for (var doItem of doItems) {
                                                        if (purchaseOrder._id == doItem.purchaseOrder._id && poItem.product._id == doItem.product._id) {

                                                            var fulfillmentObj = {
                                                                no: validDeliveryOrder.no,
                                                                deliveredQuantity: doItem.deliveredQuantity,
                                                                date:validDeliveryOrder.date
                                                            };
                                                            poItem.fulfillments.push(fulfillmentObj);

                                                            var totalRealize = 0;
                                                            for (var poItemFulfillment of poItem.fulfillments) {
                                                                totalRealize += poItemFulfillment.deliveredQuantity;
                                                            }
                                                            poItem.realizationQuantity = totalRealize;
                                                            break;
                                                        }
                                                    }
                                                }
                                                tasks.push(this.purchaseOrderManager.update(purchaseOrder));
                                            }

                                            Promise.all(tasks)
                                                .then(results => {
                                                    //update PO Eksternal
                                                    for (var validDeliveryOrderItem of validDeliveryOrder.items) {
                                                        var purchaseOrderExternal = validDeliveryOrderItem.purchaseOrderExternal;
                                                        var getPurchaseOrderById = [];
                                                        for (var purchaseOrderExternalItem of purchaseOrderExternal.items) {
                                                            // var indexPO = purchaseOrderExternal.items.indexOf(purchaseOrderExternalItem);
                                                            getPurchaseOrderById.push(this.purchaseOrderManager.getSingleById(purchaseOrderExternalItem._id));
                                                        }
                                                        Promise.all(getPurchaseOrderById)
                                                            .then(results => {
                                                                purchaseOrderExternal.items = results;
                                                                tasksPoExternal.push(this.purchaseOrderExternalManager.update(purchaseOrderExternal));
                                                            })
                                                            .catch(e => {
                                                                reject(e);
                                                            });

                                                    }

                                                    Promise.all(tasksPoExternal)
                                                        .then(results => {
                                                            resolve(id);
                                                        })
                                                        .catch(e => {
                                                            reject(e);
                                                        })
                                                })
                                                .catch(e => {
                                                    reject(e);
                                                })

                                        })
                                        .catch(e => {
                                            reject(e);
                                        });
                            }

                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    getDataDeliveryOrder(no, supplierId, dateFrom, dateTo) {
        return new Promise((resolve, reject) => {
            var query;
            if (no != "undefined" && no != "" && supplierId != "undefined" && supplierId != "" && dateFrom != "undefined" && dateFrom != "" && dateTo != "undefined" && dateTo != "") {
                query = {
                    no: no,
                    supplierId: supplierId,
                    date:
                    {
                        $gte: dateFrom,
                        $lte: dateTo
                    },
                    _deleted: false
                };
            } else if (no != "undefined" && no != "" && supplierId != "undefined" && supplierId != "") {
                query = {
                    no: no,
                    supplierId: supplierId,
                    _deleted: false
                };
            } else if (supplierId != "undefined" && supplierId != "") {
                query = {
                    supplierId: supplierId,
                    _deleted: false
                };
            } else if (no != "undefined" && no != "") {
                query = {
                    no: no,
                    _deleted: false
                };
            } else if (dateFrom != "undefined" && dateFrom != "" && dateTo != "undefined" && dateTo != "") {
                query = {
                    date:
                    {
                        $gte: dateFrom,
                        $lte: dateTo
                    },
                    _deleted: false
                };
            }

            this.collection
                .where(query)
                .execute()
                .then(PurchaseOrder => {
                    resolve(PurchaseOrder);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }
}<commit_msg>add validation for supplierDOdate<commit_after>'use strict'

// external deps
var ObjectId = require("mongodb").ObjectId;
var BaseManager = require('../base-manager');

// internal deps
require('mongodb-toolkit');
var DLModels = require('dl-models');
var map = DLModels.map;
var DeliveryOrder = DLModels.purchasing.DeliveryOrder;
var PurchaseOrderManager = require('./purchase-order-manager');
var PurchaseOrderExternalManager = require('./purchase-order-external-manager');

// var PurchaseOrderBaseManager = require('../po/purchase-order-base-manager');
// var DOItem = DLModels.po.DOItem;

module.exports = class DeliveryOrderManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.purchasing.collection.DeliveryOrder);
        this.purchaseOrderManager = new PurchaseOrderManager(db, user);
        this.purchaseOrderExternalManager = new PurchaseOrderExternalManager(db, user);
    }

    _getQuery(paging) {
        var deleted = {
            _deleted: false
        };
        var query = paging.keyword ? {
            '$and': [deleted]
        } : deleted;

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");
            var filteNO = {
                'no': {
                    '$regex': regex
                }
            };
            var filterNRefNo = {
                'refNo': {
                    '$regex': regex
                }
            };
            var filterSupplierName = {
                'supplier.name': {
                    '$regex': regex
                }
            };
            var filterItem = {
                items: {
                    $elemMatch: {
                        'purchaseOrderExternal.no':{
                            '$regex': regex
                        }
                    }
                }
            };
            var $or = {
                '$or': [filteNO, filterNRefNo, filterSupplierName,filterItem]
            };

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

    post(deliveryOrder) {
        return new Promise((resolve, reject) => {
            this._validate(deliveryOrder)
                .then(validDeliveryOrder => {
                    validDeliveryOrder.isPosted = true;
                    this.collection.update(validDeliveryOrder)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    _validate(deliveryOrder) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = deliveryOrder;
            var now = new Date();

            var getDeliveryderPromise = this.collection.singleOrDefault({
                "$and": [{
                    _id: {
                        '$ne': new ObjectId(valid._id)
                    }
                }, {
                        "no": valid.no
                    }]
            });
            Promise.all([getDeliveryderPromise])
                .then(results => {
                    var _module = results[0];
                    if (!valid.no || valid.no == '')
                        errors["no"] = "Nomor surat jalan tidak boleh kosong";
                    else if (_module)
                        errors["no"] = "Nomor surat jalan sudah terdaftar";

                    if (!valid.date || valid.date == '')
                        errors["date"] = "Tanggal surat jalan tidak boleh kosong";
                    else if (valid.date > now)
                        errors["date"] = "Tanggal surat jalan tidak boleh lebih besar dari tanggal hari ini";
                    if (!valid.supplierDOdate || valid.supplierDOdate == '')
                        errors["supplierDOdate"] = "Tanggal surat jalan supplier tidak boleh kosong";

                    if (!valid.supplierId || valid.supplierId.toString() == '')
                        errors["supplier"] = "Nama supplier tidak boleh kosong";

                    if (valid.items && valid.items.length < 1) {
                        errors["items"] = "Harus ada minimal 1 nomor po eksternal";
                    } else {
                        var deliveryOrderItemErrors = [];
                        var deliveryOrderItemHasError = false;
                        for (var doItem of valid.items || []) {
                            var purchaseOrderExternalItemErrors = [];
                            var purchaseOrderExternalItemHasErrors = false;
                            var purchaseOrderExternalError = {};

                            if (!doItem.purchaseOrderExternal) {
                                purchaseOrderExternalItemHasErrors = true;
                                purchaseOrderExternalError["purchaseOrderExternal"] = "Purchase order external tidak boleh kosong";
                            }

                            for (var doFulfillment of doItem.fulfillments || []) {
                                var fulfillmentError = {};
                                if (!doFulfillment.deliveredQuantity || doFulfillment.deliveredQuantity == 0) {
                                    purchaseOrderExternalItemHasErrors = true;
                                    fulfillmentError["deliveredQuantity"] = "Jumlah barang diterima tidak boleh kosong";
                                }
                                else if (doFulfillment.deliveredQuantity > doFulfillment.purchaseOrderQuantity) {
                                    purchaseOrderExternalItemHasErrors = true;
                                    fulfillmentError["deliveredQuantity"] = "Jumlah barang diterima tidak boleh lebih besar dari jumlah barang di po eksternal";
                                }
                                purchaseOrderExternalItemErrors.push(fulfillmentError);
                            }
                            if (purchaseOrderExternalItemHasErrors) {
                                deliveryOrderItemHasError = true;
                                purchaseOrderExternalError["fulfillments"] = purchaseOrderExternalItemErrors;
                            }
                            deliveryOrderItemErrors.push(purchaseOrderExternalError);
                        }
                        if (purchaseOrderExternalItemHasErrors)
                            errors["items"] = deliveryOrderItemErrors;
                    }

                    // 2c. begin: check if data has any error, reject if it has.
                    for (var prop in errors) {
                        var ValidationError = require('../../validation-error');
                        reject(new ValidationError('data does not pass validation', errors));
                    }

                    if (!valid.stamp)
                        valid = new DeliveryOrder(valid);

                    valid.stamp(this.user.username, 'manager');
                    resolve(valid);
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    create(deliveryOrder) {
        return new Promise((resolve, reject) => {
            var tasks = [];
            var tasksPoExternal = [];
            var getPurchaseOrderById=[];
            this._validate(deliveryOrder)
                .then(validDeliveryOrder => {
                    this.collection.insert(validDeliveryOrder)
                        .then(id => {
                            //update PO Internal
                            for (var validDeliveryOrderItem of validDeliveryOrder.items) {
                                for (var fulfillmentItem of validDeliveryOrderItem.fulfillments) {
                                    getPurchaseOrderById.push(this.purchaseOrderManager.getSingleById(fulfillmentItem.purchaseOrder._id));
                                }
                                    Promise.all(getPurchaseOrderById)
                                        .then(results => {
                                            for (var result of results) {
                                                var purchaseOrder = result;
                                                for (var poItem of purchaseOrder.items) {
                                                    var doItems = validDeliveryOrderItem.fulfillments;
                                                    for (var doItem of doItems) {
                                                        if (purchaseOrder._id == doItem.purchaseOrder._id && poItem.product._id == doItem.product._id) {

                                                            var fulfillmentObj = {
                                                                no: validDeliveryOrder.no,
                                                                deliveredQuantity: doItem.deliveredQuantity,
                                                                date:validDeliveryOrder.date
                                                            };
                                                            poItem.fulfillments.push(fulfillmentObj);

                                                            var totalRealize = 0;
                                                            for (var poItemFulfillment of poItem.fulfillments) {
                                                                totalRealize += poItemFulfillment.deliveredQuantity;
                                                            }
                                                            poItem.realizationQuantity = totalRealize;
                                                            break;
                                                        }
                                                    }
                                                }
                                                tasks.push(this.purchaseOrderManager.update(purchaseOrder));
                                            }

                                            Promise.all(tasks)
                                                .then(results => {
                                                    //update PO Eksternal
                                                    for (var validDeliveryOrderItem of validDeliveryOrder.items) {
                                                        var purchaseOrderExternal = validDeliveryOrderItem.purchaseOrderExternal;
                                                        var getPurchaseOrderById = [];
                                                        for (var purchaseOrderExternalItem of purchaseOrderExternal.items) {
                                                            // var indexPO = purchaseOrderExternal.items.indexOf(purchaseOrderExternalItem);
                                                            getPurchaseOrderById.push(this.purchaseOrderManager.getSingleById(purchaseOrderExternalItem._id));
                                                        }
                                                        Promise.all(getPurchaseOrderById)
                                                            .then(results => {
                                                                purchaseOrderExternal.items = results;
                                                                tasksPoExternal.push(this.purchaseOrderExternalManager.update(purchaseOrderExternal));
                                                            })
                                                            .catch(e => {
                                                                reject(e);
                                                            });

                                                    }

                                                    Promise.all(tasksPoExternal)
                                                        .then(results => {
                                                            resolve(id);
                                                        })
                                                        .catch(e => {
                                                            reject(e);
                                                        })
                                                })
                                                .catch(e => {
                                                    reject(e);
                                                })

                                        })
                                        .catch(e => {
                                            reject(e);
                                        });
                            }

                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    getDataDeliveryOrder(no, supplierId, dateFrom, dateTo) {
        return new Promise((resolve, reject) => {
            var query;
            if (no != "undefined" && no != "" && supplierId != "undefined" && supplierId != "" && dateFrom != "undefined" && dateFrom != "" && dateTo != "undefined" && dateTo != "") {
                query = {
                    no: no,
                    supplierId: supplierId,
                    date:
                    {
                        $gte: dateFrom,
                        $lte: dateTo
                    },
                    _deleted: false
                };
            } else if (no != "undefined" && no != "" && supplierId != "undefined" && supplierId != "") {
                query = {
                    no: no,
                    supplierId: supplierId,
                    _deleted: false
                };
            } else if (supplierId != "undefined" && supplierId != "") {
                query = {
                    supplierId: supplierId,
                    _deleted: false
                };
            } else if (no != "undefined" && no != "") {
                query = {
                    no: no,
                    _deleted: false
                };
            } else if (dateFrom != "undefined" && dateFrom != "" && dateTo != "undefined" && dateTo != "") {
                query = {
                    date:
                    {
                        $gte: dateFrom,
                        $lte: dateTo
                    },
                    _deleted: false
                };
            }

            this.collection
                .where(query)
                .execute()
                .then(PurchaseOrder => {
                    resolve(PurchaseOrder);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }
}<|endoftext|>


<commit_before>//TODO: add delay before opening more details
/*
 var timer;
 var details;
 ;
 */

var opened = false, currentPage = 1, infiniteScroll = null;

$(function() {

	$(document).on('click', '#assets-container .asset-add-btn', function(event) {
		var parent = $(this).parent().parent().parent();
		asset.process(parent.data('type'), parent.data('id'), location.href);
		event.stopPropagation();
	});

	$(document).on('click', '.asset > .asset-details', function(event) {
		var link = $(this).find('.asset-name > a').attr('href');
		location.href = link;
	});

	mouseStop();

	History.Adapter.bind(window, 'statechange', function() {
		var state = History.getState();
		if (state.data.id === 'assets') {
			renderAssets(state.data.context);
		}
	});

	var loadAssets = function(url) {
		caramel.data({
			title : null,
			header : ['header'],
			body : ['assets', 'sort-assets']
		}, {
			url : url,
			success : function(data, status, xhr) {
				//TODO: Integrate a new History.js library to fix this
				if ($.browser.msie == true && $.browser.version < 10) {
					renderAssets(data);
				} else {
					History.pushState({
						id : 'assets',
						context : data
					}, document.title, url);
				}

			},
			error : function(xhr, status, error) {
				theme.loaded($('#assets-container').parent(), '
Error while retrieving data.
');
			}
		});
		theme.loading($('.store-left'));
	};

	var loadAssetsScroll = function(url) {
		caramel.data({
			title : null,
			body : ['assets']
		}, {
			url : url,
			success : function(data, status, xhr) {
                infiniteScroll = data.body.assets.context.assets.length >= 12;
                currentPag = 1;
				renderAssetsScroll(data);
				$('.loading-inf-scroll').hide();
			},
			error : function(xhr, status, error) {
                infiniteScroll = false;
			}
		});
		$('.loading-inf-scroll').show();
	};

	$(document).on('click', '#ul-sort-assets li a', function(e) {
		currentPage = 1;
		$('#ul-sort-assets li a').removeClass('selected-type');
		var thiz = $(this);
		thiz.addClass('selected-type');
		loadAssets(thiz.attr('href'));
		mouseStop();
		e.preventDefault();
	});

	$(document).on('click', '.pagination a', function(e) {
		e.preventDefault();
		var url = $(this).attr('href');
		if (url === '#') {
			return;
		}
		loadAssets(url);
	});

	var scroll = function() {

		if(infiniteScroll || (store.asset.paging.size >= 12 && infiniteScroll == null)) {
			if($(window).scrollTop() + $(window).height() >= $(document).height() * .8) {
				var url = caramel.url(store.asset.paging.url + (++currentPage));
				loadAssetsScroll(url);
				$(window).unbind('scroll', scroll);
				setTimeout(function() {
					$(window).bind('scroll', scroll);
				}, 500);
			}
		} else {
			$('.loading-inf-scroll').hide();
		}
	}

	$(window).bind('scroll', scroll);

	$("a[data-toggle='tooltip']").tooltip();

	$('#my-assets').hide();
	$('.my-assets-link').click(function(){

		if($(this).find('.pull-right').hasClass('icon-angle-down')){
			$(this).find('.pull-right').removeClass('icon-angle-down').addClass('icon-angle-up');
		}else{
			$(this).find('.pull-right').removeClass('icon-angle-up').addClass('icon-angle-down');
		}
		$('#my-assets').slideToggle("fast");
	});

	caramel.loaded('js', 'assets');
	caramel.loaded('js', 'sort-assets');
});
<commit_msg>(Fixing STORE-358) repeating asserts for tags is fixed<commit_after>//TODO: add delay before opening more details
/*
 var timer;
 var details;
 ;
 */

var opened = false, currentPage = 1, infiniteScroll = null;

$(function() {

	$(document).on('click', '#assets-container .asset-add-btn', function(event) {
		var parent = $(this).parent().parent().parent();
		asset.process(parent.data('type'), parent.data('id'), location.href);
		event.stopPropagation();
	});

	$(document).on('click', '.asset > .asset-details', function(event) {
		var link = $(this).find('.asset-name > a').attr('href');
		location.href = link;
	});

	mouseStop();

	History.Adapter.bind(window, 'statechange', function() {
		var state = History.getState();
		if (state.data.id === 'assets') {
			renderAssets(state.data.context);
		}
	});

	var loadAssets = function(url) {
		caramel.data({
			title : null,
			header : ['header'],
			body : ['assets', 'sort-assets']
		}, {
			url : url,
			success : function(data, status, xhr) {
				//TODO: Integrate a new History.js library to fix this
				if ($.browser.msie == true && $.browser.version < 10) {
					renderAssets(data);
				} else {
					History.pushState({
						id : 'assets',
						context : data
					}, document.title, url);
				}

			},
			error : function(xhr, status, error) {
				theme.loaded($('#assets-container').parent(), '
Error while retrieving data.
');
			}
		});
		theme.loading($('.store-left'));
	};

	var loadAssetsScroll = function(url) {
		//TO-DO
		/* As tags are not Indexing so far
		*  Assert pagination and is not supporteed and There for infiniteScroll is disable to 'Tag'
		* */
		if(url.indexOf('tag')== -1){
		caramel.data({
			title : null,
			body : ['assets']
		}, {
			url : url,
			success : function(data, status, xhr) {
                infiniteScroll = data.body.assets.context.assets.length >= 12;
                currentPag = 1;
				renderAssetsScroll(data);
				$('.loading-inf-scroll').hide();
			},
			error : function(xhr, status, error) {
                infiniteScroll = false;
			}
		});
		$('.loading-inf-scroll').show();
		}
	};

	$(document).on('click', '#ul-sort-assets li a', function(e) {
		currentPage = 1;
		$('#ul-sort-assets li a').removeClass('selected-type');
		var thiz = $(this);
		thiz.addClass('selected-type');
		loadAssets(thiz.attr('href'));
		mouseStop();
		e.preventDefault();
	});

	$(document).on('click', '.pagination a', function(e) {
		e.preventDefault();
		var url = $(this).attr('href');
		if (url === '#') {
			return;
		}
		loadAssets(url);
	});

	var scroll = function() {

		if(infiniteScroll || (store.asset.paging.size >= 12 && infiniteScroll == null)) {
			if($(window).scrollTop() + $(window).height() >= $(document).height() * .8) {
				var url = caramel.url(store.asset.paging.url + (++currentPage));
				loadAssetsScroll(url);
				$(window).unbind('scroll', scroll);
				setTimeout(function() {
					$(window).bind('scroll', scroll);
				}, 500);
			}
		} else {
			$('.loading-inf-scroll').hide();
		}
	}

	$(window).bind('scroll', scroll);

	$("a[data-toggle='tooltip']").tooltip();

	$('#my-assets').hide();
	$('.my-assets-link').click(function(){

		if($(this).find('.pull-right').hasClass('icon-angle-down')){
			$(this).find('.pull-right').removeClass('icon-angle-down').addClass('icon-angle-up');
		}else{
			$(this).find('.pull-right').removeClass('icon-angle-up').addClass('icon-angle-down');
		}
		$('#my-assets').slideToggle("fast");
	});

	caramel.loaded('js', 'assets');
	caramel.loaded('js', 'sort-assets');
});
<|endoftext|>


<commit_before>define('app/controllers/machines', [
    'app/models/machine'],
	/**
	 * Machines controller
	 *
	 * @returns Class
	 */
	function(Machine) {
		return Ember.ArrayController.extend({
			backend: null,

			content: null,

			init: function() {
				this._super();
				this.set('content', []),
				this.refresh();
			},

			refresh: function(){

				if(this.backend.state == "offline"){
					this.clear();
					return;
				}

				var that = this;

				this.backend.set('state', 'wait');

				$.getJSON('/backends/' + this.backend.index + '/machines', function(data) {
					data.forEach(function(item){

						var found = false;

						console.log("item id: " + item.id);

						that.content.forEach(function(machine){

							if(machine.id == item.id){
								found = true;
								machine.set(item); //FIXME this does not change anything;

								machine.set('state', item.state);
								machine.set('can_stop', item.can_stop);
								machine.set('can_start', item.can_start);
								machine.set('can_destroy', item.can_destroy);
								machine.set('can_reboot', item.can_reboot);
								machine.set('tags', item.tags);
								return false;
							}
						});

						if(!found){
							item.backend = that.backend;
							var machine = Machine.create(item);
							that.contentWillChange(that.content.length - 1, 0, 1);
							that.content.push(machine);
							that.contentDidChange(that.content.length - 1, 0, 1);
							var idx = Mist.backendsController.content.indexOf(that.backend);
							Mist.backendsController.contentWillChange(idx, 0, 0);
							Mist.backendsController.contentDidChange(idx, 0, 0);
						}

					});

					that.content.forEach(function(item){

						var found = false;

						data.forEach(function(machine){
							console.log("machine id: " + machine.id);

							if(machine.id == item.id){
								found = true;
								return false;
							}
						});

						if(!found){
							console.log("not found, deleting");
							that.contentWillChange();
							that.removeObject(item);
							that.contentDidChange();
							var idx = Mist.backendsController.content.indexOf(that.backend);
							Mist.backendsController.contentWillChange(idx, 0, 0);
							Mist.backendsController.contentDidChange(idx, 0, 0);
						}
					});

					// TODO handle deletion from server

					that.backend.set('state', 'online');

					Ember.run.later(that, function(){
						this.refresh();
				    }, that.backend.poll_interval);
				}).error(function(e) {
					Mist.notificationController.notify("Error loading machines for backend: " + that.backend.title);
					that.backend.set('state', 'offline');
					console.log("Error loading machines for backend: " + that.backend.title);
					console.log(e.state + " " + e.stateText);
				});

			},

			newMachine: function(name, image, size) {
                console.log('Creating machine', this.name, 'to backend', this.backend.title);

				var payload = {
	                    'name': name,
                        // TODO: this should get a location and not the backend id
	                    'location' : this.backend.id,
	                    'image': image.id,
	                    'size': size.id,
                        // this is needed for Linode only
                        'disk': size.disk
	            };

                var that = this;
				$.ajax({
                    url: 'backends/' + this.backend.index + '/machines',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(payload),
                    dataType: 'json',
                    success: function(data) {
                        console.info('Successfully sent create machine', name, 'to backend',
                                    that.backend.title);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error while sending create machine' +
                                name + ' to backend ' + that.backend.title);
                        console.error(textstate, errorThrown, 'while checking key of machine', that.name);
                    }
                });
			}

		});
	}
);
<commit_msg>Pass location id upon machine creation<commit_after>define('app/controllers/machines', [
    'app/models/machine'],
	/**
	 * Machines controller
	 *
	 * @returns Class
	 */
	function(Machine) {
		return Ember.ArrayController.extend({
			backend: null,

			content: null,

			init: function() {
				this._super();
				this.set('content', []),
				this.refresh();
			},

			refresh: function(){

				if(this.backend.state == "offline"){
					this.clear();
					return;
				}

				var that = this;

				this.backend.set('state', 'wait');

				$.getJSON('/backends/' + this.backend.index + '/machines', function(data) {
					data.forEach(function(item){

						var found = false;

						console.log("item id: " + item.id);

						that.content.forEach(function(machine){

							if(machine.id == item.id){
								found = true;
								machine.set(item); //FIXME this does not change anything;

								machine.set('state', item.state);
								machine.set('can_stop', item.can_stop);
								machine.set('can_start', item.can_start);
								machine.set('can_destroy', item.can_destroy);
								machine.set('can_reboot', item.can_reboot);
								machine.set('tags', item.tags);
								return false;
							}
						});

						if(!found){
							item.backend = that.backend;
							var machine = Machine.create(item);
							that.contentWillChange(that.content.length - 1, 0, 1);
							that.content.push(machine);
							that.contentDidChange(that.content.length - 1, 0, 1);
							var idx = Mist.backendsController.content.indexOf(that.backend);
							Mist.backendsController.contentWillChange(idx, 0, 0);
							Mist.backendsController.contentDidChange(idx, 0, 0);
						}

					});

					that.content.forEach(function(item){

						var found = false;

						data.forEach(function(machine){
							console.log("machine id: " + machine.id);

							if(machine.id == item.id){
								found = true;
								return false;
							}
						});

						if(!found){
							console.log("not found, deleting");
							that.contentWillChange();
							that.removeObject(item);
							that.contentDidChange();
							var idx = Mist.backendsController.content.indexOf(that.backend);
							Mist.backendsController.contentWillChange(idx, 0, 0);
							Mist.backendsController.contentDidChange(idx, 0, 0);
						}
					});

					// TODO handle deletion from server

					that.backend.set('state', 'online');

					Ember.run.later(that, function(){
						this.refresh();
				    }, that.backend.poll_interval);
				}).error(function(e) {
					Mist.notificationController.notify("Error loading machines for backend: " + that.backend.title);
					that.backend.set('state', 'offline');
					console.log("Error loading machines for backend: " + that.backend.title);
					console.log(e.state + " " + e.stateText);
				});

			},

			newMachine: function(name, image, size, location) {
                console.log('Creating machine', this.name, 'to backend', this.backend.title);

				var payload = {
	                    'name': name,
	                    'location' : location.id,
	                    'image': image.id,
	                    'size': size.id,
                        // this is needed for Linode only
                        'disk': size.disk
	            };

                var that = this;
				$.ajax({
                    url: 'backends/' + this.backend.index + '/machines',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(payload),
                    dataType: 'json',
                    success: function(data) {
                        console.info('Successfully sent create machine', name, 'to backend',
                                    that.backend.title);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.notify('Error while sending create machine' +
                                name + ' to backend ' + that.backend.title);
                        console.error(textstate, errorThrown, 'while checking key of machine', that.name);
                    }
                });
			}

		});
	}
);
<|endoftext|>


<commit_before>define('app/controllers/machines', ['app/models/machine'],
    /**
     *  Machines Controller
     *
     *  @returns Class
     */
    function(Machine) {
        return Ember.ArrayController.extend(Ember.Evented, {

            /**
             *  Properties
             */

            content: [],
            loading: null,
            backend: null,

            /**
             *
             *  Initialization
             *
             */

            load: function() {

                if (!this.backend.enabled) return;

                var that = this;
                this.set('loading', true);
                Mist.ajaxGET('/backends/' + this.backend.id + '/machines', {
                }).success(function(machines) {
                    if (!that.backend.enabled) return;
                    that._setContent(machines);
                }).error(function() {
                    if (!that.backend.enabled) return;
                    Mist.notificationController.notify('Failed to load machines for ' + that.backend.title);
                    that.backend.set('enabled', false);
                }).complete(function(success) {
                    if (!that.backend.enabled) return;
                    that.set('loading', false);
                    that.trigger('onLoad');
                });
            },

            newMachine: function(name, image, size, location, key, script) {
                log('Creating machine', this.name, 'to backend', this.backend.title);

                this.backend.set('create_pending', true);

                if (this.backend.provider.search('rackspace_first_gen') > -1) {
                    // Rackspace (first gen) does not support spaces in names
                    name = name.replace(/ /g,'');
                }

                var payload = {
                        'name': name,
                        'image': image.id,
                        'size': size.id,
                        // these are only useful for Linode
                        'image_extra': image.extra,
                        'disk': size.disk,
                        'location': location.id,
                        'key': key.name,
                        'script': script,
                };

                var item = {};
                item.state = 'pending';
                item.can_stop = false;
                item.can_start = false;
                item.can_destroy = false;
                item.can_reboot = false;
                item.can_tag = false;
                item.backend = this.backend;
                item.name = name;
                item.image = image;
                item.id = -1;
                item.pendingCreation = true;

                var machine = Machine.create(item);

                this.addObject(machine);
                Ember.run.next(function(){
                    $('#machines-list input.ember-checkbox').checkboxradio();
                });
                var that = this;
                $.ajax({
                    url: 'backends/' + this.backend.id + '/machines',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(payload),
                    headers: { "cache-control": "no-cache" },
                    success: function(data) {
                        info('Successfully sent create machine', name, 'to backend',
                                    that.backend.title);
                        if (that.backend.error) {
                            that.backend.set('error', false);
                        }

                        machine.set("id", data.id);
                        machine.set("name", data.name);
                        machine.set("public_ips", data.public_ips);
                        machine.set("private_ips", data.private_ips);
                        machine.set("extra", data.extra);
                        machine.set('pendingCreation', false);
                        that.backend.set('create_pending', false);

                        var key_machines = new Array();
                        key.machines.forEach(function(machine) {
                            key_machines.push(machine);
                        });
                        key_machines.push([machine.backend.id, machine.id, Date.now()]);
                        Mist.keysController.updateKeyMachinesList(key.name, key_machines);

                        machine.set('keysCount', 1);
                        Ember.run.next(function() {
                            $('#mist-manage-keys').parent().trigger('create');
                        });
                        machine.probe(key.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.timeNotify(jqXHR.responseText, 15000);
                        error(textstate, errorThrown, 'while creating machine', that.name);
                        machine.set('pendingCreation', false);
                        that.removeObject(machine);
                        that.backend.set('error', textstate);
                        that.backend.set('create_pending', false);
                    }
                });
            },

            /**
             *
             *  Methods
             *
             */

            clear: function() {
                Ember.run(this, function() {
                    this.set('content', []);
                    this.set('loading', false);
                    this.trigger('onMachineListChange');
                });
            },

            getMachine: function(machineId) {
                return this.content.findBy('id', machineId);
            },

            /**
             *
             *  Pseudo-Private Methods
             *
             */

            _setContent: function(machines) {
                var that = this;
                Ember.run(function() {
                    that.set('content', []);
                    machines.forEach(function(machine) {
                        that.content.pushObject(Machine.create(machine));
                    });
                    that.trigger('onMachineListChange');
                });
            }
        });
    }
);
<commit_msg>Bring back machine poll interval<commit_after>define('app/controllers/machines', ['app/models/machine'],
    /**
     *  Machines Controller
     *
     *  @returns Class
     */
    function(Machine) {
        return Ember.ArrayController.extend(Ember.Evented, {

            /**
             *  Properties
             */

            content: [],
            loading: null,
            backend: null,

            /**
             *
             *  Initialization
             *
             */

            load: function() {

                if (!this.backend.enabled) return;

                var that = this;
                this.set('loading', true);
                Mist.ajaxGET('/backends/' + this.backend.id + '/machines', {
                }).success(function(machines) {
                    if (!that.backend.enabled) return;
                    that._setContent(machines);
                    that._reload();
                }).error(function() {
                    if (!that.backend.enabled) return;
                    Mist.notificationController.notify('Failed to load machines for ' + that.backend.title);
                    that.backend.set('enabled', false);
                }).complete(function(success) {
                    if (!that.backend.enabled) return;
                    that.set('loading', false);
                    that.trigger('onLoad');
                });
            },

            newMachine: function(name, image, size, location, key, script) {

                this.backend.set('create_pending', true);

                if (this.backend.provider.search('rackspace_first_gen') > -1) {
                    // Rackspace (first gen) does not support spaces in names
                    name = name.replace(/ /g,'');
                }

                var payload = {
                        'name': name,
                        'image': image.id,
                        'size': size.id,
                        // these are only useful for Linode
                        'image_extra': image.extra,
                        'disk': size.disk,
                        'location': location.id,
                        'key': key.name,
                        'script': script,
                };

                var item = {};
                item.state = 'pending';
                item.can_stop = false;
                item.can_start = false;
                item.can_destroy = false;
                item.can_reboot = false;
                item.can_tag = false;
                item.backend = this.backend;
                item.name = name;
                item.image = image;
                item.id = -1;
                item.pendingCreation = true;

                var machine = Machine.create(item);

                this.addObject(machine);
                Ember.run.next(function(){
                    $('#machines-list input.ember-checkbox').checkboxradio();
                });
                var that = this;
                $.ajax({
                    url: 'backends/' + this.backend.id + '/machines',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(payload),
                    headers: { "cache-control": "no-cache" },
                    success: function(data) {
                        info('Successfully sent create machine', name, 'to backend',
                                    that.backend.title);
                        if (that.backend.error) {
                            that.backend.set('error', false);
                        }

                        machine.set("id", data.id);
                        machine.set("name", data.name);
                        machine.set("public_ips", data.public_ips);
                        machine.set("private_ips", data.private_ips);
                        machine.set("extra", data.extra);
                        machine.set('pendingCreation', false);
                        that.backend.set('create_pending', false);

                        var key_machines = new Array();
                        key.machines.forEach(function(machine) {
                            key_machines.push(machine);
                        });
                        key_machines.push([machine.backend.id, machine.id, Date.now()]);
                        Mist.keysController.updateKeyMachinesList(key.name, key_machines);

                        machine.set('keysCount', 1);
                        Ember.run.next(function() {
                            $('#mist-manage-keys').parent().trigger('create');
                        });
                        machine.probe(key.name);
                    },
                    error: function(jqXHR, textstate, errorThrown) {
                        Mist.notificationController.timeNotify(jqXHR.responseText, 15000);
                        error(textstate, errorThrown, 'while creating machine', that.name);
                        machine.set('pendingCreation', false);
                        that.removeObject(machine);
                        that.backend.set('error', textstate);
                        that.backend.set('create_pending', false);
                    }
                });
            },

            /**
             *
             *  Methods
             *
             */

            clear: function() {
                Ember.run(this, function() {
                    this.set('content', []);
                    this.set('loading', false);
                    this.trigger('onMachineListChange');
                });
            },

            getMachine: function(machineId) {
                return this.content.findBy('id', machineId);
            },

            /**
             *
             *  Pseudo-Private Methods
             *
             */

            _reload: function() {
                Ember.run.later(this, function() {
                    this.load();
                }, this.backend.poll_interval);
            },

            _setContent: function(machines) {
                var that = this;
                Ember.run(function() {
                    that.set('content', []);
                    machines.forEach(function(machine) {
                        that.content.pushObject(Machine.create(machine));
                    });
                    that.trigger('onMachineListChange');
                });
            }
        });
    }
);
<|endoftext|>


<commit_before>import sinon from "sinon";
import Draft, { EditorState, SelectionState } from "draft-js";
import handleNewCodeBlock from "../handleNewCodeBlock";

describe("handleNewCodeBlock", () => {
  describe("in unstyled block with three backquotes", () => {
    const testNewCodeBlock = (text, data) => () => {
      const beforeRawContentState = {
        entityMap: {},
        blocks: [
          {
            key: "item1",
            text,
            type: "unstyled",
            depth: 0,
            inlineStyleRanges: [],
            entityRanges: [],
            data: {},
          },
        ],
      };
      const afterRawContentState = {
        entityMap: {},
        blocks: [
          {
            key: "item1",
            text: "",
            type: "code-block",
            depth: 0,
            inlineStyleRanges: [],
            entityRanges: [],
            data,
          },
        ],
      };
      const contentState = Draft.convertFromRaw(beforeRawContentState);
      const selection = new SelectionState({
        anchorKey: "item1",
        anchorOffset: text.length,
        focusKey: "item1",
        focusOffset: text.length,
        isBackward: false,
        hasFocus: true,
      });
      const editorState = EditorState.forceSelection(
        EditorState.createWithContent(contentState),
        selection
      );
      it("creates new code block", () => {
        const newEditorState = handleNewCodeBlock(editorState);
        expect(newEditorState).not.toEqual(editorState);
        expect(Draft.convertToRaw(newEditorState.getCurrentContent())).toEqual(
          afterRawContentState
        );
      });
    };

    describe("without langugate", testNewCodeBlock("```", {}));
    describe("with langugate", testNewCodeBlock("```js", { language: "js" }));
  });

  describe("in code block", () => {
    beforeAll(() => {
      sinon.stub(Draft, "genKey").returns("item2");
    });
    afterAll(() => {
      Draft.genKey.restore();
    });
    const beforeRawContentState = {
      entityMap: {},
      blocks: [
        {
          key: "item1",
          text: 'console.info("hello")',
          type: "code-block",
          depth: 0,
          inlineStyleRanges: [],
          entityRanges: [],
          data: { language: "js" },
        },
      ],
    };
    const afterRawContentState = {
      entityMap: {},
      blocks: [
        {
          key: "item1",
          text: 'console.info("hello")',
          type: "code-block",
          depth: 0,
          inlineStyleRanges: [],
          entityRanges: [],
          data: { language: "js" },
        },
        {
          key: "item2",
          text: "",
          type: "code-block",
          depth: 0,
          inlineStyleRanges: [],
          entityRanges: [],
          data: { language: "js" },
        },
      ],
    };
    const contentState = Draft.convertFromRaw(beforeRawContentState);
    it("adds new line inside code block", () => {
      const selection = new SelectionState({
        anchorKey: "item1",
        anchorOffset: 21,
        focusKey: "item1",
        focusOffset: 21,
        isBackward: false,
        hasFocus: true,
      });
      const editorState = EditorState.forceSelection(
        EditorState.createWithContent(contentState),
        selection
      );
      const newEditorState = handleNewCodeBlock(editorState);
      expect(newEditorState).not.toEqual(editorState);
      expect(Draft.convertToRaw(newEditorState.getCurrentContent())).toEqual(
        afterRawContentState
      );
    });
    it("does not add new line even inside code block", () => {
      const selection = new SelectionState({
        anchorKey: "item1",
        anchorOffset: 10,
        focusKey: "item1",
        focusOffset: 10,
        isBackward: false,
        hasFocus: true,
      });
      const editorState = EditorState.forceSelection(
        EditorState.createWithContent(contentState),
        selection
      );
      const newEditorState = handleNewCodeBlock(editorState);
      expect(newEditorState).toEqual(editorState);
      expect(Draft.convertToRaw(newEditorState.getCurrentContent())).toEqual(
        beforeRawContentState
      );
    });
  });

  describe("in unstyled block without three backquotes", () => {
    const rawContentState = {
      entityMap: {},
      blocks: [
        {
          key: "item1",
          text: "``",
          type: "unstyled",
          depth: 0,
          inlineStyleRanges: [],
          entityRanges: [],
          data: {},
        },
      ],
    };
    const contentState = Draft.convertFromRaw(rawContentState);
    const selection = new SelectionState({
      anchorKey: "item1",
      anchorOffset: 2,
      focusKey: "item1",
      focusOffset: 2,
      isBackward: false,
      hasFocus: true,
    });
    const editorState = EditorState.forceSelection(
      EditorState.createWithContent(contentState),
      selection
    );
    it("noop", () => {
      const newEditorState = handleNewCodeBlock(editorState);
      expect(newEditorState).toEqual(editorState);
      expect(Draft.convertToRaw(newEditorState.getCurrentContent())).toEqual(
        rawContentState
      );
    });
  });
});
<commit_msg>Fix tests<commit_after>import sinon from "sinon";
import Draft, { EditorState, SelectionState } from "draft-js";
import handleNewCodeBlock from "../handleNewCodeBlock";

const removeBlockKeys = rawContentState => {
  return {
    ...rawContentState,
    blocks: rawContentState.blocks.map(block => {
      delete block.key;
      return block;
    }),
  };
};

describe("handleNewCodeBlock", () => {
  describe("in unstyled block with three backquotes", () => {
    const testNewCodeBlock = (text, data) => () => {
      const beforeRawContentState = {
        entityMap: {},
        blocks: [
          {
            key: "item1",
            text,
            type: "unstyled",
            depth: 0,
            inlineStyleRanges: [],
            entityRanges: [],
            data: {},
          },
        ],
      };
      const afterRawContentState = {
        entityMap: {},
        blocks: [
          {
            text: "",
            type: "code-block",
            depth: 0,
            inlineStyleRanges: [],
            entityRanges: [],
            data,
          },
          {
            text: "",
            type: "unstyled",
            inlineStyleRanges: [],
            entityRanges: [],
            data: {},
            depth: 0,
          },
        ],
      };
      const contentState = Draft.convertFromRaw(beforeRawContentState);
      const selection = new SelectionState({
        anchorKey: "item1",
        anchorOffset: text.length,
        focusKey: "item1",
        focusOffset: text.length,
        isBackward: false,
        hasFocus: true,
      });
      const editorState = EditorState.forceSelection(
        EditorState.createWithContent(contentState),
        selection
      );
      it("creates new code block", () => {
        const newEditorState = handleNewCodeBlock(editorState);
        expect(newEditorState).not.toEqual(editorState);
        expect(
          removeBlockKeys(
            Draft.convertToRaw(newEditorState.getCurrentContent())
          )
        ).toEqual(removeBlockKeys(afterRawContentState));
      });
    };

    describe("without langugate", testNewCodeBlock("```", {}));
    describe("with langugate", testNewCodeBlock("```js", { language: "js" }));
  });

  describe("in code block", () => {
    beforeAll(() => {
      sinon.stub(Draft, "genKey").returns("item2");
    });
    afterAll(() => {
      Draft.genKey.restore();
    });
    const beforeRawContentState = {
      entityMap: {},
      blocks: [
        {
          key: "item1",
          text: 'console.info("hello")',
          type: "code-block",
          depth: 0,
          inlineStyleRanges: [],
          entityRanges: [],
          data: { language: "js" },
        },
      ],
    };
    const afterRawContentState = {
      entityMap: {},
      blocks: [
        {
          key: "item1",
          text: 'console.info("hello")',
          type: "code-block",
          depth: 0,
          inlineStyleRanges: [],
          entityRanges: [],
          data: { language: "js" },
        },
        {
          key: "item2",
          text: "",
          type: "code-block",
          depth: 0,
          inlineStyleRanges: [],
          entityRanges: [],
          data: { language: "js" },
        },
      ],
    };
    const contentState = Draft.convertFromRaw(beforeRawContentState);
    it("adds new line inside code block", () => {
      const selection = new SelectionState({
        anchorKey: "item1",
        anchorOffset: 21,
        focusKey: "item1",
        focusOffset: 21,
        isBackward: false,
        hasFocus: true,
      });
      const editorState = EditorState.forceSelection(
        EditorState.createWithContent(contentState),
        selection
      );
      const newEditorState = handleNewCodeBlock(editorState);
      expect(newEditorState).not.toEqual(editorState);
      expect(Draft.convertToRaw(newEditorState.getCurrentContent())).toEqual(
        afterRawContentState
      );
    });
    it("does not add new line even inside code block", () => {
      const selection = new SelectionState({
        anchorKey: "item1",
        anchorOffset: 10,
        focusKey: "item1",
        focusOffset: 10,
        isBackward: false,
        hasFocus: true,
      });
      const editorState = EditorState.forceSelection(
        EditorState.createWithContent(contentState),
        selection
      );
      const newEditorState = handleNewCodeBlock(editorState);
      expect(newEditorState).toEqual(editorState);
      expect(Draft.convertToRaw(newEditorState.getCurrentContent())).toEqual(
        beforeRawContentState
      );
    });
  });

  describe("in unstyled block without three backquotes", () => {
    const rawContentState = {
      entityMap: {},
      blocks: [
        {
          key: "item1",
          text: "``",
          type: "unstyled",
          depth: 0,
          inlineStyleRanges: [],
          entityRanges: [],
          data: {},
        },
      ],
    };
    const contentState = Draft.convertFromRaw(rawContentState);
    const selection = new SelectionState({
      anchorKey: "item1",
      anchorOffset: 2,
      focusKey: "item1",
      focusOffset: 2,
      isBackward: false,
      hasFocus: true,
    });
    const editorState = EditorState.forceSelection(
      EditorState.createWithContent(contentState),
      selection
    );
    it("noop", () => {
      const newEditorState = handleNewCodeBlock(editorState);
      expect(newEditorState).toEqual(editorState);
      expect(Draft.convertToRaw(newEditorState.getCurrentContent())).toEqual(
        rawContentState
      );
    });
  });
});
<|endoftext|>


<commit_before>angular.module('log', ['entriesService', 'entriesCounterService', 'utilService', 'authService', 'bootstrapFilters', 'ngSanitize'])

    .config(function($routeProvider) {

        $routeProvider.
            when('/', {controller:EntriesController, templateUrl:'partials/main.html'}).
            when("/entry/:entryId", {controller: EntryEditController, templateUrl: "partials/entry.html"}).
            when("/login", {controller: LoginController, templateUrl: "partials/login.html"}).
            otherwise({redirectTo:'/'})
    })

    .config(['$httpProvider', function($httpProvider) {

        var interceptor = ['$rootScope', '$q', function($rootScope, $q) {
            function success(response) {
                return response;
            }

            function error(response) {
                // user is not logged in, remove user data from rootScope
                if (response.status === 401) {
                    if($rootScope.loggedUser != null) {
                        showInfoMessage("Your session timed out. Please login again.");
                        $rootScope.loggedUser = null;
                    }
                }
                else if(response.status === 403) {
                    console.log("403");
                    // do nothing, user is trying to modify data without privileges
                }
                else {
                    showErrorMessage("Service not responding. Please try again later.");
                }
                return $q.reject(response);
            }

            return function(promise) {
                return promise.then(success, error);
            }

        }];
        $httpProvider.responseInterceptors.push(interceptor);
    }])

    .run(function($rootScope, AuthService) {
        AuthService.validate();
    });

angular.module('bootstrapFilters', []).
    filter('newlines', function () {
        return function (text) {
            return text.replace(/\n/g, '
');
        };
    });<commit_msg>When session times out, redirect user to login page<commit_after>angular.module('log', ['entriesService', 'entriesCounterService', 'utilService', 'authService', 'bootstrapFilters', 'ngSanitize'])

    .config(function($routeProvider) {

        $routeProvider.
            when('/', {controller:EntriesController, templateUrl:'partials/main.html'}).
            when("/entry/:entryId", {controller: EntryEditController, templateUrl: "partials/entry.html"}).
            when("/login", {controller: LoginController, templateUrl: "partials/login.html"}).
            otherwise({redirectTo:'/'})
    })

    .config(['$httpProvider', function($httpProvider) {

        var interceptor = ['$rootScope', '$q', '$location', function($rootScope, $q, $location) {
            function success(response) {
                return response;
            }

            function error(response) {
                // user is not logged in, remove user data from rootScope
                if (response.status === 401) {
                    if($rootScope.loggedUser != null) {
                        $location.path("/login");
                        showInfoMessage("Your session timed out. Please login again.");
                        $rootScope.loggedUser = null;
                    }
                }
                else if(response.status === 403) {
                    console.log("403");
                    // do nothing, user is trying to modify data without privileges
                }
                else {
                    showErrorMessage("Service not responding. Please try again later.");
                }
                return $q.reject(response);
            }

            return function(promise) {
                return promise.then(success, error);
            }

        }];
        $httpProvider.responseInterceptors.push(interceptor);
    }])

    .run(function($rootScope, AuthService) {
        AuthService.validate();
    });

angular.module('bootstrapFilters', []).
    filter('newlines', function () {
        return function (text) {
            return text.replace(/\n/g, '
');
        };
    });<|endoftext|>


<commit_before>(function(angular) {
	'use strict';

	var app = angular.module('bugminerApp', ['ngResource', 'ngRoute', 'ui.bootstrap']);

	app.config(['$routeProvider', function($routeProvider) {
		$routeProvider
			.when('/', {
				templateUrl: 'partials/projects/index.html',
				controller: 'ProjectsCtrl'
			})
			.when('/projects/:name/:tab?', {
				templateUrl: 'partials/projects/view.html',
				controller: 'ProjectCtrl',
				reloadOnSearch: false
			});
	}]);

	app.factory('Project', function($resource) {
		  return $resource('/api/projects/:name');
	});

	app.factory('BugPage', function($resource, $routeParams) {
		  return $resource('/api/projects/:name/bugs', {name: $routeParams.name, sort: 'reportTime', size: 10});
	});

	app.factory('LineChange', function($resource, $routeParams) {
		return $resource('/api/projects/:name/bugs/:tracker/:key/diff', {name: $routeParams.name});
	});

	app.controller('ProjectsCtrl', function($scope, Project) {
		Project.query(function(data) {
			$scope.projects = data;
			console.log(data);
		});
	});

	app.controller('ProjectCtrl', function($scope, $routeParams, $location) {
		$scope.tab = $routeParams.tab;

		// set dashboard to default
		if ($scope.tab == null) {
			$scope.tab = 'dashboard';
		}

		$scope.navigateTo = function(tab) {
			$location.path('/projects/' + $routeParams.name + '/' + tab);
			$location.search({});
		};
	});

	app.controller('ProjectBugsCtrl', function($scope, $routeParams, $location, BugPage, LineChange) {
		$scope.currentPage = $routeParams.page ? $routeParams.page : 1;
		$scope.currentBug = null;
		$scope.changedFiles = [];

		$scope.$watch('currentPage', function() {
			$location.search({page: $scope.currentPage});

			// reset when navigating, as bug will not be in the list anymore
			$scope.currentBug = null;

			BugPage.get({page: $scope.currentPage - 1}, function(data) {
				$scope.bugs = data.content;
				$scope.totalItems = data.totalElements;
				$scope.itemsPerPage = data.size;
			});
		});

		$scope.setCurrentBug = function(bug) {
			$scope.currentBug = bug;

			// fetch line changes
			LineChange.query({tracker: bug.issueTracker.name, key: bug.key}, function(data) {
				var changedFiles = [];
				var lineChanges = data;
				var currentFileName = '';
				var currentFile = null;
				var currentEdit = {
					additions: [],
					deletions: [],
					lastLineNumber: 0
				};

				for (var i = 0; i < lineChanges.length; i++) {
					if (currentFileName !== lineChanges[i].fileName) {
						currentFileName = lineChanges[i].fileName;

						currentFile = {
							name: currentFileName,
							edits: [currentEdit]
						};

						$scope.changedFiles.push(currentFile);
					}

					if (lineChanges[i].oldLineNumber > currentEdit.lastLineNumber + 1) {
						currentEdit = {
							additions: [],
							deletions: [],
							lastLineNumber: 0
						};

						currentFile.edits.push(currentEdit);
					}

					if (lineChanges[i].kind === 'ADDITION') {
						currentEdit.additions.push(lineChanges[i]);
						currentEdit.lastLineNumber = lineChanges[i].oldLineNumber;
					} else {
						currentEdit.deletions.push(lineChanges[i]);
						currentEdit.lastLineNumber = lineChanges[i].oldLineNumber;
					}
				}

				console.log($scope.changedFiles);
			});
		};
	});

})(angular);
<commit_msg>Fix: reset scopes changed files not local var<commit_after>(function(angular) {
	'use strict';

	var app = angular.module('bugminerApp', ['ngResource', 'ngRoute', 'ui.bootstrap']);

	app.config(['$routeProvider', function($routeProvider) {
		$routeProvider
			.when('/', {
				templateUrl: 'partials/projects/index.html',
				controller: 'ProjectsCtrl'
			})
			.when('/projects/:name/:tab?', {
				templateUrl: 'partials/projects/view.html',
				controller: 'ProjectCtrl',
				reloadOnSearch: false
			});
	}]);

	app.factory('Project', function($resource) {
		  return $resource('/api/projects/:name');
	});

	app.factory('BugPage', function($resource, $routeParams) {
		  return $resource('/api/projects/:name/bugs', {name: $routeParams.name, sort: 'reportTime', size: 10});
	});

	app.factory('LineChange', function($resource, $routeParams) {
		return $resource('/api/projects/:name/bugs/:tracker/:key/diff', {name: $routeParams.name});
	});

	app.controller('ProjectsCtrl', function($scope, Project) {
		Project.query(function(data) {
			$scope.projects = data;
			console.log(data);
		});
	});

	app.controller('ProjectCtrl', function($scope, $routeParams, $location) {
		$scope.tab = $routeParams.tab;

		// set dashboard to default
		if ($scope.tab == null) {
			$scope.tab = 'dashboard';
		}

		$scope.navigateTo = function(tab) {
			$location.path('/projects/' + $routeParams.name + '/' + tab);
			$location.search({});
		};
	});

	app.controller('ProjectBugsCtrl', function($scope, $routeParams, $location, BugPage, LineChange) {
		$scope.currentPage = $routeParams.page ? $routeParams.page : 1;
		$scope.currentBug = null;
		$scope.changedFiles = [];

		$scope.$watch('currentPage', function() {
			$location.search({page: $scope.currentPage});

			// reset when navigating, as bug will not be in the list anymore
			$scope.currentBug = null;

			BugPage.get({page: $scope.currentPage - 1}, function(data) {
				$scope.bugs = data.content;
				$scope.totalItems = data.totalElements;
				$scope.itemsPerPage = data.size;
			});
		});

		$scope.setCurrentBug = function(bug) {
			$scope.currentBug = bug;

			// fetch line changes
			LineChange.query({tracker: bug.issueTracker.name, key: bug.key}, function(data) {
				$scope.changedFiles = [];
				var lineChanges = data;
				var currentFileName = '';
				var currentFile = null;
				var currentEdit = {
					additions: [],
					deletions: [],
					lastLineNumber: 0
				};

				for (var i = 0; i < lineChanges.length; i++) {
					if (currentFileName !== lineChanges[i].fileName) {
						currentFileName = lineChanges[i].fileName;

						currentFile = {
							name: currentFileName,
							edits: [currentEdit]
						};

						$scope.changedFiles.push(currentFile);
					}

					if (lineChanges[i].oldLineNumber > currentEdit.lastLineNumber + 1) {
						currentEdit = {
							additions: [],
							deletions: [],
							lastLineNumber: 0
						};

						currentFile.edits.push(currentEdit);
					}

					if (lineChanges[i].kind === 'ADDITION') {
						currentEdit.additions.push(lineChanges[i]);
						currentEdit.lastLineNumber = lineChanges[i].oldLineNumber;
					} else {
						currentEdit.deletions.push(lineChanges[i]);
						currentEdit.lastLineNumber = lineChanges[i].oldLineNumber;
					}
				}

				console.log($scope.changedFiles);
			});
		};
	});

})(angular);
<|endoftext|>


<commit_before>/*******************************************************************************
 * @license
 * Copyright (c) 2012 VMware, Inc. All Rights Reserved.
 * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
 * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
 * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
 * You can obtain a current copy of the Eclipse Public License from
 * http://www.opensource.org/licenses/eclipse-1.0.php
 *
 * Contributors:
 *     Kris De Volder - initial API and implementation
 ******************************************************************************/

/*global require define console window */
/*jslint browser:true devel:true*/

define(['scripted/exec/param-resolver', 'scripted/exec/exec-shared'], function (mParamResolver, mExecShared) {

	var getConfig = mExecShared.getConfig;
	var makeExecFunction = mExecShared.makeExecFunction;

	var SPECIAL = ".$^()[]{}+|?"; //TODO: other things in need of escaping?

	function mustEscape(c) {
		for (var i = 0; i < SPECIAL.length; i++) {
			if (SPECIAL[i]===c) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Convert a pattern using '**' and '*' into a equivalent RegExp
	 * "**" surrounded by '/' will match any sequence of 'path segments',
	 * including a sequence of length 0. Using ** without surrounding '/'
	 * is not legal and results in an error.
	 * "*" will match any sequence of chars excluding '/'
	 */
	function pat2regexp(pat) {
		//TODO: is all this string concatenation slow?
		var re = "^";
		var absolute = '/'===pat[0];
		if (!absolute) {
			pat = window.fsroot + "/" + pat;
		}

		var i = 0;
		while (i<pat.length) {
			if ("/**/"===pat.substring(i,i+4)) {
				re += "/(.*/)?";
				i+=4;
			} else if ("**"===pat.substring(i,i+2)) {
				throw "Bad pattern in exec afterSave block: "+pat+"\n '**' only allowed as follows '.../**/...'";
			} else {
				var c = pat[i++];
				if (c==='*') {
					re += "[^/]*"; //Sequence of chars not including a '/'
				} else if (mustEscape(c)) {
					re += "\\"+c;
				} else {
					re += c;
				}
			}
		}
		re += "$";
		return new RegExp(re);
	}

	function installOn(editor) {

		var replaceParams = mParamResolver.forEditor(editor);

		var afterSaves = [];

		function defineAfterSaveBinding(pathPattern, cmdSpec) {
			afterSaves.push({
				re: pat2regexp(pathPattern),
				exec: makeExecFunction(cmdSpec)
			});
		}

		//BEGIN installOn function body
		var afterSaveConf = getConfig("afterSave");
		if (afterSaveConf) {
			var empty = true;
			for (var filePat in afterSaveConf) {
				if (afterSaveConf.hasOwnProperty(filePat)) {
					try {
						defineAfterSaveBinding(filePat, afterSaveConf[filePat]);
						empty = false;
					} catch (e) {
						//Log and ignore broken/unparseable entries
						console.error(e);
					}
				}
			}

			if (!empty) {//install event listener only if there is at least one afterSave exec.
				editor.addEventListener("afterSave", function (evt) {
					var file = evt.file;
					for (var i = 0; i < afterSaves.length; i++) {
						var re = afterSaves[i].re;
						if (re.test(file)) {
							afterSaves[i].exec(replaceParams);
							return; //abort after the first match
						}
					}
				});
			}
		}
		//END installOn function
	}

	return {
		installOn: installOn
	};

});
<commit_msg>Code cleanup: trailing spaces<commit_after>/*******************************************************************************
 * @license
 * Copyright (c) 2012 VMware, Inc. All Rights Reserved.
 * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
 * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
 * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
 * You can obtain a current copy of the Eclipse Public License from
 * http://www.opensource.org/licenses/eclipse-1.0.php
 *
 * Contributors:
 *     Kris De Volder - initial API and implementation
 ******************************************************************************/

/*global require define console window */
/*jslint browser:true devel:true*/

define(['scripted/exec/param-resolver', 'scripted/exec/exec-shared'], function (mParamResolver, mExecShared) {

	var getConfig = mExecShared.getConfig;
	var makeExecFunction = mExecShared.makeExecFunction;

	var SPECIAL = ".$^()[]{}+|?"; //TODO: other things in need of escaping?

	function mustEscape(c) {
		for (var i = 0; i < SPECIAL.length; i++) {
			if (SPECIAL[i]===c) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Convert a pattern using '**' and '*' into a equivalent RegExp
	 * "**" surrounded by '/' will match any sequence of 'path segments',
	 * including a sequence of length 0. Using ** without surrounding '/'
	 * is not legal and results in an error.
	 * "*" will match any sequence of chars excluding '/'
	 */
	function pat2regexp(pat) {
		//TODO: is all this string concatenation slow?
		var re = "^";
		var absolute = '/'===pat[0];
		if (!absolute) {
			pat = window.fsroot + "/" + pat;
		}

		var i = 0;
		while (i<pat.length) {
			if ("/**/"===pat.substring(i,i+4)) {
				re += "/(.*/)?";
				i+=4;
			} else if ("**"===pat.substring(i,i+2)) {
				throw "Bad pattern in exec afterSave block: "+pat+"\n '**' only allowed as follows '.../**/...'";
			} else {
				var c = pat[i++];
				if (c==='*') {
					re += "[^/]*"; //Sequence of chars not including a '/'
				} else if (mustEscape(c)) {
					re += "\\"+c;
				} else {
					re += c;
				}
			}
		}
		re += "$";
		return new RegExp(re);
	}

	function installOn(editor) {

		var replaceParams = mParamResolver.forEditor(editor);

		var afterSaves = [];

		function defineAfterSaveBinding(pathPattern, cmdSpec) {
			afterSaves.push({
				re: pat2regexp(pathPattern),
				exec: makeExecFunction(cmdSpec)
			});
		}

		//BEGIN installOn function body
		var afterSaveConf = getConfig("afterSave");
		if (afterSaveConf) {
			var empty = true;
			for (var filePat in afterSaveConf) {
				if (afterSaveConf.hasOwnProperty(filePat)) {
					try {
						defineAfterSaveBinding(filePat, afterSaveConf[filePat]);
						empty = false;
					} catch (e) {
						//Log and ignore broken/unparseable entries
						console.error(e);
					}
				}
			}

			if (!empty) {//install event listener only if there is at least one afterSave exec.
				editor.addEventListener("afterSave", function (evt) {
					var file = evt.file;
					for (var i = 0; i < afterSaves.length; i++) {
						var re = afterSaves[i].re;
						if (re.test(file)) {
							afterSaves[i].exec(replaceParams);
							return; //abort after the first match
						}
					}
				});
			}
		}
		//END installOn function
	}

	return {
		installOn: installOn
	};

});
<|endoftext|>


<commit_before>import { transform } from 'babel-standalone';

export default
target => {
  target.prototype._renderChildren = function() { // eslint-disable-line no-param-reassign
    let transpiledCode;
    try {
      transpiledCode = transform(
        `{<div>${this.props._childrenCode}</div>}`,
        { presets: ['es2015', 'react', 'stage-0'] }
      ).code;
    } catch (err) {
      console.log('Showroom scope decorator - transpiling code error:', err);
    }

    /* Use '_scope' keyword in DOCUMENTATION file when want get access to SCOPE component.
       For example - '<ModalContainer showModal={ _scope.state.showModal } />'
       For code 'this.state.a' After transpiling finish, result code is 'undefined.state.a'.
       Because 'undefined' is an frequently occurring word, we use '_scope' */
    transpiledCode = transpiledCode.replace(/_scope/g, 'this');
    let compiledCode = eval(transpiledCode); // eslint-disable-line no-eval
    console.log('compiled', compiledCode)
    return compiledCode;
  }
};
<commit_msg>Removed odd console.log.<commit_after>import { transform } from 'babel-standalone';

export default
target => {
  target.prototype._renderChildren = function() { // eslint-disable-line no-param-reassign
    let transpiledCode;
    try {
      transpiledCode = transform(
        `{<div>${this.props._childrenCode}</div>}`,
        { presets: ['es2015', 'react', 'stage-0'] }
      ).code;
    } catch (err) {
      console.log('Showroom scope decorator - transpiling code error:', err);
    }

    /* Use '_scope' keyword in DOCUMENTATION file when want get access to SCOPE component.
       For example - '<ModalContainer showModal={ _scope.state.showModal } />'
       For code 'this.state.a' After transpiling finish, result code is 'undefined.state.a'.
       Because 'undefined' is an frequently occurring word, we use '_scope' */
    transpiledCode = transpiledCode.replace(/_scope/g, 'this');
    let compiledCode = eval(transpiledCode); // eslint-disable-line no-eval
    return compiledCode;
  }
};
<|endoftext|>


<commit_before>
Session.setDefault('TextState','short');

/*****************************************************************************/
/* ReportView: Event Handlers and Helpers */
/*****************************************************************************/
Template.ReportView.events({
  /*
   * Example:
   *  'click .selector': function (e, tmpl) {
   *
   *  }
   */
  'click #text-view-short': function(event, tmpl) {
    Session.set('TextState', 'short');
  },
  'click #text-view-long': function(event, tmpl) {
    Session.set('TextState', 'long');
  },
  'click .edit-btn': function(event, tmpl) {
    Router.go('/reports/' + this._id + '/edit');
  }
});

Template.ReportView.helpers({
    textState: function () {
      return Session.get('TextState');
  }

});

Template.ShortTextReport.helpers({
   getMainImageUrl: function() {
    if(this.images && this.images[0]) {
      var original = Images.findOne({_id:this.images[0].fileId});

      if (original) {
        return original.url();
      }
      else
        return false;
    }
    return false;
   },

});

Template.LongTextReport.helpers({
     notEscapeHTML: function(text) {
      if(text)
        return Spacebars.SafeString(text);
   }
});

Template.ProjectReferences.helpers({

  getFileURL: function(fileId) {
    var file = Files.findOne({_id:fileId});
    if (file) {
      return file.url();
    }
    else
      return false;

  }

  });

/*****************************************************************************/
/* ReportView: Lifecycle Hooks */
/*****************************************************************************/
Template.ReportView.created = function () {
};

Template.ShortTextReport.rendered = function () {

  Deps.autorun(function () {
    var report = Router.getData();

    if (report) {

      var values = _.pluck(report.evaluation, 'value');

      var data = {
        labels : ["Produktivitet", "Måloppnåelse", "Virkninger", "Relevans", "Levedyktighet", "Samf.øk. lønnsomhet"],
        datasets : [
          {
            fillColor : "rgba(0, 140, 186, 0.3)",
            strokeColor : "rgba(0, 140, 186, 0.9)",
            pointColor : "rgba(0, 140, 186, 0.9)",
            pointStrokeColor : "rgba(0, 140, 186, 1)",
            data : values
          }
        ]
      }

      var el = $("#spiderEvaluation");

      if (el.get(0)) {
        var ctx = el.get(0).getContext("2d");
        var chart = new Chart(ctx).Radar(data, options);
      }
    }
  });
};

Template.ReportView.destroyed = function () {

};

var options = {

    //Boolean - Whether to show labels on the scale
  scaleShowLabels : true,
    //Number - Scale label font size in pixels
  scaleFontSize : 18,
    //Boolean - If we show the scale above the chart data
  //scaleOverlay : true,

  //Boolean - If we want to override with a hard coded scale
  scaleOverride : true,

  //** Required if scaleOverride is true **
  //Number - The number of steps in a hard coded scale
  scaleSteps : 6,
  //Number - The value jump in the hard coded scale
  scaleStepWidth : 1,
  //Number - The centre starting value
  scaleStartValue : 0,

    //Number - Point label font size in pixels
  pointLabelFontSize : 20,
    //String - Point label font colour
  pointLabelFontColor : "rgba(0,0,0,0.8)",
    //String - Colour of the scale line
  scaleLineColor : "rgba(0,0,0,.4)",

    //String - Scale label font colour
  scaleFontColor : "rgba(0,0,0,0.5)",

    //String - Point label font weight
  pointLabelFontStyle : "normal",
}
<commit_msg>Increased font size of spider diagram. Was too small for mobile devices<commit_after>
Session.setDefault('TextState','short');

/*****************************************************************************/
/* ReportView: Event Handlers and Helpers */
/*****************************************************************************/
Template.ReportView.events({
  /*
   * Example:
   *  'click .selector': function (e, tmpl) {
   *
   *  }
   */
  'click #text-view-short': function(event, tmpl) {
    Session.set('TextState', 'short');
  },
  'click #text-view-long': function(event, tmpl) {
    Session.set('TextState', 'long');
  },
  'click .edit-btn': function(event, tmpl) {
    Router.go('/reports/' + this._id + '/edit');
  }
});

Template.ReportView.helpers({
    textState: function () {
      return Session.get('TextState');
  }

});

Template.ShortTextReport.helpers({
   getMainImageUrl: function() {
    if(this.images && this.images[0]) {
      var original = Images.findOne({_id:this.images[0].fileId});

      if (original) {
        return original.url();
      }
      else
        return false;
    }
    return false;
   },

});

Template.LongTextReport.helpers({
     notEscapeHTML: function(text) {
      if(text)
        return Spacebars.SafeString(text);
   }
});

Template.ProjectReferences.helpers({

  getFileURL: function(fileId) {
    var file = Files.findOne({_id:fileId});
    if (file) {
      return file.url();
    }
    else
      return false;

  }

  });

/*****************************************************************************/
/* ReportView: Lifecycle Hooks */
/*****************************************************************************/
Template.ReportView.created = function () {
};

Template.ShortTextReport.rendered = function () {

  Deps.autorun(function () {
    var report = Router.getData();

    if (report) {

      var values = _.pluck(report.evaluation, 'value');

      var data = {
        labels : ["Produktivitet", "Måloppnåelse", "Virkninger", "Relevans", "Levedyktighet", "Samf.øk. lønnsomhet"],
        datasets : [
          {
            fillColor : "rgba(0, 140, 186, 0.3)",
            strokeColor : "rgba(0, 140, 186, 0.9)",
            pointColor : "rgba(0, 140, 186, 0.9)",
            pointStrokeColor : "rgba(0, 140, 186, 1)",
            data : values
          }
        ]
      }

      var el = $("#spiderEvaluation");

      if (el.get(0)) {
        var ctx = el.get(0).getContext("2d");
        var chart = new Chart(ctx).Radar(data, options);
      }
    }
  });
};

Template.ReportView.destroyed = function () {

};

var options = {

    //Boolean - Whether to show labels on the scale
  scaleShowLabels : true,
    //Number - Scale label font size in pixels
  scaleFontSize : 20,
    //Boolean - If we show the scale above the chart data
  //scaleOverlay : true,

  //Boolean - If we want to override with a hard coded scale
  scaleOverride : true,

  //** Required if scaleOverride is true **
  //Number - The number of steps in a hard coded scale
  scaleSteps : 6,
  //Number - The value jump in the hard coded scale
  scaleStepWidth : 1,
  //Number - The centre starting value
  scaleStartValue : 0,

    //Number - Point label font size in pixels
  pointLabelFontSize : 22,
    //String - Point label font colour
  pointLabelFontColor : "rgba(0,0,0,0.8)",
    //String - Colour of the scale line
  scaleLineColor : "rgba(0,0,0,.4)",

    //String - Scale label font colour
  scaleFontColor : "rgba(0,0,0,0.5)",

    //String - Point label font weight
  pointLabelFontStyle : "normal",
}
<|endoftext|>


<commit_before>
var editorService;

Dependency.autorun(function() {
  editorService = Dependency.get('editorService');
});

Template.geMain.helpers({
  'node': function() {
    return editorService.context.selected.group();
  },
  'skills': function() {
    if (editorService.context.root()) {
      return Nodes.find({
        _id : {
          $in : Nodes.getSkills(editorService.context.graph(), editorService.context.selected.group()._id)
        }
      });
    }
  }
});

Template.geMain.events({
  'click .ce-main .skill': function() {
    editorService.context.select(this);
  }
});
<commit_msg>Select context node fix<commit_after>
var editorService;

Dependency.autorun(function() {
  editorService = Dependency.get('editorService');
});

Template.geMain.helpers({
  'node': function() {
    return editorService.context.selected.group();
  },
  'skills': function() {
    if (editorService.context.root()) {
      return Nodes.find({
        _id : {
          $in : Nodes.getSkills(editorService.context.graph(), editorService.context.selected.group()._id)
        }
      });
    }
  }
});

Template.geMain.events({
  'click .ce-main .skill': function() {
    editorService.select(this);
  }
});
<|endoftext|>


<commit_before>import Die from "appkit/models/die";

export default Ember.ObjectController.extend({
  dice: [Die.create(), Die.create(), Die.create(), Die.create(), Die.create()],

  actions: {
    newTurn: function() {
      var game, participant, newTurn;

      game = this.get('model');
      participant = game.get('nextParticipant');

      newTurn = this.store.createRecord('turn', {
        game: game,
        participation: participant
      });
      newTurn.save();
      game.get('turns').addObject(newTurn);
    }
  }
});<commit_msg>Reset dice on each new turn<commit_after>import Die from "appkit/models/die";

export default Ember.ObjectController.extend({
  dice: [Die.create(), Die.create(), Die.create(), Die.create(), Die.create()],

  actions: {
    newTurn: function() {
      var game, participant, newTurn;

      game = this.get('model');
      participant = game.get('nextParticipant');

      newTurn = this.store.createRecord('turn', {
        game: game,
        participation: participant
      });
      newTurn.save();
      game.get('turns').addObject(newTurn);
      this.set('dice', [Die.create(), Die.create(), Die.create(), Die.create(), Die.create()]);
    }
  }
});<|endoftext|>


<commit_before>var express = require('express'),
  router = express.Router(),
  mongoose = require('mongoose'),
  Article = mongoose.model('Article');

module.exports = function (app) {
  app.use('/', router);
};

router.get('/', function (req, res, next) {

  Article.find(function (err, articles) {
    if (err) return next(err);
    res.render('index', {
      title: 'Generator-Express MVC',
      articles: articles
    });
  });
});
<commit_msg>Removing mongoose model from yeoman generator<commit_after>var express = require('express'),
  router = express.Router();

module.exports = function (app) {
  app.use('/', router);
};

router.get('/', function (req, res, next) {

  res.render('index', {
    title: 'Generator-Express MVC',
  });
});<|endoftext|>