<commit_before>'use strict'

var ObjectId = require("mongodb").ObjectId;
require("mongodb-toolkit");

var DLModels = require('dl-models');
var map = DLModels.map;
var WeavingSalesContract = DLModels.sales.WeavingSalesContract;
var BuyerManager = require('../master/buyer-manager');
var UomManager = require('../master/uom-manager');
var ProductManager = require('../master/product-manager');
var TermOfPaymentManager = require('../master/term-of-payment-manager');
var MaterialConstructionManager = require('../master/material-construction-manager');
var YarnMaterialManager = require('../master/yarn-material-manager');
var AccountBankManager = require('../master/account-bank-manager');
var ComodityManager = require('../master/comodity-manager');
var QualityManager = require('../master/quality-manager');
var BaseManager = require('module-toolkit').BaseManager;
var i18n = require('dl-i18n');
var generateCode = require("../../utils/code-generator");
var assert = require('assert');

module.exports = class WeavingSalesContractManager extends BaseManager {
    constructor(db, user) {
        super(db, user);

        this.collection = this.db.collection(map.sales.collection.WeavingSalesContract);
        this.buyerManager = new BuyerManager(db, user);
        this.UomManager = new UomManager(db, user);
        this.ProductManager = new ProductManager(db, user);
        this.TermOfPaymentManager = new TermOfPaymentManager(db, user);
        this.YarnMaterialManager = new YarnMaterialManager(db, user);
        this.MaterialConstructionManager = new MaterialConstructionManager(db, user);
        this.ComodityManager = new ComodityManager(db, user);
        this.QualityManager = new QualityManager(db, user);
        this.AccountBankManager = new AccountBankManager(db, user);
    }

    _getQuery(paging) {
        var deletedFilter = {
            _deleted: false
        }, keywordFilter = {};

        var query = {};
        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");

            var filterSalesContract = {
                'salesContractNo': {
                    '$regex': regex
                }
            };

            var filterBuyerName = {
                'buyer.name': {
                    '$regex': regex
                }
            };

            var filterBuyerType = {
                'buyer.type': {
                    '$regex': regex
                }
            };

            keywordFilter = {
                '$or': [filterSalesContract, filterBuyerName, filterBuyerType]
            };
        }
        query = { '$and': [deletedFilter, paging.filter, keywordFilter] }
        return query;
    }

    _beforeInsert(salesContract) {
        salesContract.salesContractNo = salesContract.salesContractNo === "" ? generateCode() : salesContract.salesContractNo;
        salesContract._createdDate = new Date();
        return Promise.resolve(salesContract);
    }

    _validate(salesContract) {
        var errors = {};
        var valid = salesContract;

        var getSalesContractPromise = this.collection.singleOrDefault({
            _id: {
                '$ne': new ObjectId(valid._id)
            },
            salesContractNo: valid.salesContractNo
        });

        //get Object from ...
        var getBuyer = valid.buyer && ObjectId.isValid(valid.buyer._id) ? this.buyerManager.getSingleByIdOrDefault(valid.buyer._id) : Promise.resolve(null);
        var getUom = valid.uom && ObjectId.isValid(valid.uom._id) ? this.UomManager.getSingleByIdOrDefault(valid.uom._id) : Promise.resolve(null);
        var getProduct = valid.material && ObjectId.isValid(valid.material._id) ? this.ProductManager.getSingleByIdOrDefault(valid.material._id) : Promise.resolve(null);
        var getYarnMaterial = valid.yarnMaterial && ObjectId.isValid(valid.yarnMaterial._id) ? this.YarnMaterialManager.getSingleByIdOrDefault(valid.yarnMaterial._id) : Promise.resolve(null);
        var getMaterialConstruction = valid.materialConstruction && ObjectId.isValid(valid.materialConstruction._id) ? this.MaterialConstructionManager.getSingleByIdOrDefault(valid.materialConstruction._id) : Promise.resolve(null);
        var getComodity = valid.comodity && ObjectId.isValid(valid.comodity._id) ? this.ComodityManager.getSingleByIdOrDefault(valid.comodity._id) : Promise.resolve(null);
        var getQuality = valid.quality && ObjectId.isValid(valid.quality._id) ? this.QualityManager.getSingleByIdOrDefault(valid.quality._id) : Promise.resolve(null);
        var getBankAccount = valid.accountBank && ObjectId.isValid(valid.accountBank._id) ? this.AccountBankManager.getSingleByIdOrDefault(valid.accountBank._id) : Promise.resolve(null);
        var getTermOfPayment = valid.termOfPayment && ObjectId.isValid(valid.termOfPayment._id) ? this.TermOfPaymentManager.getSingleByIdOrDefault(valid.termOfPayment._id) : Promise.resolve(null);
        var getAgent = valid.agent && ObjectId.isValid(valid.agent._id) ? this.buyerManager.getSingleByIdOrDefault(valid.agent._id) : Promise.resolve(null);

        return Promise.all([getSalesContractPromise, getBuyer, getUom, getProduct, getYarnMaterial, getMaterialConstruction, getComodity, getQuality, getBankAccount, getTermOfPayment, getAgent])
            .then(results => {
                var _salesContract = results[0];
                var _buyer = results[1];
                var _uom = results[2];
                var _material = results[3];
                var _yarn = results[4];
                var _construction = results[5];
                var _comodity = results[6];
                var _quality = results[7];
                var _bank = results[8];
                var _payment = results[9];
                var _agent = results[10];

                if (valid.uom) {
                    if (!valid.uom.unit || valid.uom.unit == '')
                        errors["uom"] = i18n.__("WeavingSalesContract.uom.isRequired:%s is required", i18n.__("WeavingSalesContract.uom._:Uom")); //"Satuan tidak boleh kosong";
                }
                else
                    errors["uom"] = i18n.__("WeavingSalesContract.uom.isRequired:%s is required", i18n.__("WeavingSalesContract.uom._:Uom")); //"Satuan tidak boleh kosong";

                if (_salesContract) {
                    errors["salesContractNo"] = i18n.__("WeavingSalesContract.salesContractNo.isExist:%s is Exist", i18n.__("WeavingSalesContract.salesContractNo._:SalesContractNo")); //"no Sales Contract tidak boleh kosong";
                }

                if (!_construction) {
                    errors["materialConstruction"] = i18n.__("WeavingSalesContract.materialConstruction.isRequired:%s is not exsist", i18n.__("WeavingSalesContract.materialConstruction._:MaterialConstruction")); //"materialConstruction tidak boleh kosong";
                }

                if (!_payment) {
                    errors["termOfPayment"] = i18n.__("FinishingPrintingSalesContract.termOfPayment.isRequired:%s is not exsist", i18n.__("FinishingPrintingSalesContract.termOfPayment._:TermOfPayment")); //"termOfPayment tidak boleh kosong";
                }

                if (!_yarn) {
                    errors["yarnMaterial"] = i18n.__("WeavingSalesContract.yarnMaterial.isRequired:%s is not exsist", i18n.__("WeavingSalesContract.yarnMaterial._:YarnMaterial")); //"yarnMaterial tidak boleh kosong";
                }

                if (!_quality) {
                    errors["quality"] = i18n.__("WeavingSalesContract.quality.isRequired:%s is not exsist", i18n.__("WeavingSalesContract.quality._:Quality")); //"quality tidak boleh kosong";
                }

                if (!_material)
                    errors["material"] = i18n.__("WeavingSalesContract.material.isRequired:%s is not exists", i18n.__("WeavingSalesContract.material._:Material")); //"material tidak boleh kosong";

                if (!valid.materialWidth || valid.materialWidth === '') {
                    errors["materialWidth"] = i18n.__("WeavingSalesContract.materialWidth.isRequired:%s is required", i18n.__("WeavingSalesContract.materialWidth._:MaterialWidth")); //"lebar material tidak boleh kosong";
                }

                if (!_comodity)
                    errors["comodity"] = i18n.__("WeavingSalesContract.comodity.isRequired:%s is not exists", i18n.__("WeavingSalesContract.comodity._:Comodity")); //"comodity tidak boleh kosong";

                // if (!valid.condition || valid.condition === '') {
                //     errors["condition"] = i18n.__("WeavingSalesContract.condition.isRequired:%s is required", i18n.__("WeavingSalesContract.condition._:Condition")); //"condition tidak boleh kosong";
                // }

                // if (!valid.packing || valid.packing === '') {
                //     errors["packing"] = i18n.__("WeavingSalesContract.packing.isRequired:%s is required", i18n.__("WeavingSalesContract.packing._:Packing")); //"packing tidak boleh kosong";
                // }

                if (!_buyer)
                    errors["buyer"] = i18n.__("WeavingSalesContract.buyer.isRequired:%s is not exists", i18n.__("WeavingSalesContract.buyer._:Buyer")); //"Buyer tidak boleh kosong";

                if (!_bank)
                    errors["accountBank"] = i18n.__("WeavingSalesContract.accountBank.isRequired:%s is not exists", i18n.__("WeavingSalesContract.accountBank._:accountBank")); //"accountBank tidak boleh kosong";

                if (!valid.shippingQuantityTolerance || valid.shippingQuantityTolerance === 0)
                    errors["shippingQuantityTolerance"] = i18n.__("WeavingSalesContract.shippingQuantityTolerance.isRequired:%s is required", i18n.__("WeavingSalesContract.shippingQuantityTolerance._:ShippingQuantityTolerance")); //"shippingQuantityTolerance tidak boleh kosong";
                if (valid.shippingQuantityTolerance > 100) {
                    errors["shippingQuantityTolerance"] = i18n.__("WeavingSalesContract.shippingQuantityTolerance.shouldNot:%s should not more than 100", i18n.__("WeavingSalesContract.shippingQuantityTolerance._:ShippingQuantityTolerance")); //"shippingQuantityTolerance tidak boleh lebih dari 100";
                }

                if (!valid.price || valid.price === 0)
                    errors["price"] = i18n.__("WeavingSalesContract.price.isRequired:%s is required", i18n.__("WeavingSalesContract.price._:Price")); //"price tidak boleh kosong";

                if (!valid.deliveredTo || valid.deliveredTo === '') {
                    errors["deliveredTo"] = i18n.__("WeavingSalesContract.deliveredTo.isRequired:%s is required", i18n.__("WeavingSalesContract.deliveredTo._:DeliveredTo")); //"deliveredTo tidak boleh kosong";
                }

                if (!valid.deliverySchedule || valid.deliverySchedule === "") {
                    errors["deliverySchedule"] = i18n.__("WeavingSalesContract.deliverySchedule.isRequired:%s is required", i18n.__("WeavingSalesContract.deliverySchedule._:deliverySchedule")); //"deliverySchedule tidak boleh kosong";
                }

                if (!valid.incomeTax || valid.incomeTax === '') {
                    errors["incomeTax"] = i18n.__("WeavingSalesContract.incomeTax.isRequired:%s is required", i18n.__("WeavingSalesContract.incomeTax._:IncomeTax")); //"incomeTax tidak boleh kosong";
                }
                else {

                    valid.deliverySchedule = new Date(valid.deliverySchedule);
                    var today = new Date();
                    today.setHours(0, 0, 0, 0);
                    if (today > valid.deliverySchedule) {
                        errors["deliverySchedule"] = i18n.__("WeavingSalesContract.deliverySchedule.shouldNot:%s should not be less than today's date", i18n.__("WeavingSalesContract.deliverySchedule._:deliverySchedule")); //"deliverySchedule tidak boleh kurang dari tanggal hari ini";
                    }

                }

                if (!valid.orderQuantity || valid.orderQuantity === '' || valid.orderQuantity === 0) {
                    errors["orderQuantity"] = i18n.__("WeavingSalesContract.orderQuantity.isRequired:%s should greater than 0", i18n.__("WeavingSalesContract.orderQuantity._:orderQuantity")); //"orderQuantity tidak boleh kosong";
                }

                if (_agent) {
                    valid.agentId = new ObjectId(_agent._id);
                    valid.agent = _agent;
                }

                if (_buyer) {
                    valid.buyerId = new ObjectId(_buyer._id);
                    valid.buyer = _buyer;
                    if (valid.buyer.type.trim().toLowerCase() == "ekspor") {
                        if (!valid.termOfShipment || valid.termOfShipment == "") {
                            errors["termOfShipment"] = i18n.__("WeavingSalesContract.termOfShipment.isRequired:%s is required", i18n.__("WeavingSalesContract.termOfShipment._:termOfShipment")); //"termOfShipment tidak boleh kosong jika buyer type ekspor";
                        }

                        // valid.agentId = new ObjectId(_agent._id);
                        // valid.agent = _agent;
                        // if (!valid.agent) {
                        //     errors["agent"] = i18n.__("WeavingSalesContract.agent.isRequired:%s is required", i18n.__("WeavingSalesContract.agent._:agent")); //"agent tidak boleh kosong jika type buyer ekspor";
                        // }

                        if (valid.agent) {
                            if (!valid.comission) {
                                errors["comission"] = i18n.__("WeavingSalesContract.comission.isRequired:%s is required", i18n.__("WeavingSalesContract.comission._:comission")); //"comission tidak boleh kosong jika agent valid";
                            }
                        }

                    }
                }

                if (_quality) {
                    valid.qualityId = new ObjectId(_quality._id);
                    valid.quality = _quality;
                }
                if (_uom) {
                    valid.uomId = new ObjectId(_uom._id);
                    valid.uom = _uom;
                }

                if (_material) {
                    valid.material = _material;
                    valid.materialId = new ObjectId(_material._id);
                }
                if (_comodity) {
                    valid.comodityId = new ObjectId(_comodity._id);
                    valid.comodity = _comodity;
                }
                if (_yarn) {
                    valid.yarnMaterialId = new ObjectId(_yarn._id);
                    valid.yarnMaterial = _yarn;
                }
                if (_bank) {
                    valid.accountBankId = new ObjectId(_bank._id);
                    valid.accountBank = _bank;
                }
                if (_construction) {
                    valid.materialConstructionId = new ObjectId(_construction._id);
                    valid.materialConstruction = _construction;
                }

                valid.deliverySchedule = new Date(valid.deliverySchedule);

                if (Object.getOwnPropertyNames(errors).length > 0) {
                    var ValidationError = require('module-toolkit').ValidationError;
                    return Promise.reject(new ValidationError('data does not pass validation', errors));
                }

                if (!valid.stamp) {
                    valid = new WeavingSalesContract(valid);
                }

                valid.stamp(this.user.username, "manager");

                return Promise.resolve(valid);
            });
    }

    _createIndexes() {
        var dateIndex = {
            name: `ix_${map.sales.collection.WeavingSalesContract}__updatedDate`,
            key: {
                _updatedDate: -1
            }
        }

        var noIndex = {
            name: `ix_${map.sales.collection.WeavingSalesContract}_salesContractNo`,
            key: {
                salesContractNo: 1
            },
            unique: true
        }

        return this.collection.createIndexes([dateIndex, noIndex]);
    }

    pdf(id) {
        return new Promise((resolve, reject) => {

            this.getSingleById(id)
                .then(salesContract => {

                    var getDefinition = require("../../pdf/definitions/weaving-sales-contract");
                    var definition = getDefinition(salesContract);

                    var generatePdf = require("../../pdf/pdf-generator");
                    generatePdf(definition)
                        .then(binary => {
                            resolve(binary);
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });
        });
    }
}<commit_msg>update weaving sales contract<commit_after>'use strict'

var ObjectId = require("mongodb").ObjectId;
require("mongodb-toolkit");

var DLModels = require('dl-models');
var map = DLModels.map;
var WeavingSalesContract = DLModels.sales.WeavingSalesContract;
var BuyerManager = require('../master/buyer-manager');
var UomManager = require('../master/uom-manager');
var ProductManager = require('../master/product-manager');
var TermOfPaymentManager = require('../master/term-of-payment-manager');
var MaterialConstructionManager = require('../master/material-construction-manager');
var YarnMaterialManager = require('../master/yarn-material-manager');
var AccountBankManager = require('../master/account-bank-manager');
var ComodityManager = require('../master/comodity-manager');
var QualityManager = require('../master/quality-manager');
var BaseManager = require('module-toolkit').BaseManager;
var i18n = require('dl-i18n');
var generateCode = require("../../utils/code-generator");
var assert = require('assert');

module.exports = class WeavingSalesContractManager extends BaseManager {
    constructor(db, user) {
        super(db, user);

        this.collection = this.db.collection(map.sales.collection.WeavingSalesContract);
        this.buyerManager = new BuyerManager(db, user);
        this.UomManager = new UomManager(db, user);
        this.ProductManager = new ProductManager(db, user);
        this.TermOfPaymentManager = new TermOfPaymentManager(db, user);
        this.YarnMaterialManager = new YarnMaterialManager(db, user);
        this.MaterialConstructionManager = new MaterialConstructionManager(db, user);
        this.ComodityManager = new ComodityManager(db, user);
        this.QualityManager = new QualityManager(db, user);
        this.AccountBankManager = new AccountBankManager(db, user);
    }

    _getQuery(paging) {
        var deletedFilter = {
            _deleted: false
        }, keywordFilter = {};

        var query = {};
        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");

            var filterSalesContract = {
                'salesContractNo': {
                    '$regex': regex
                }
            };

            var filterBuyerName = {
                'buyer.name': {
                    '$regex': regex
                }
            };

            var filterBuyerType = {
                'buyer.type': {
                    '$regex': regex
                }
            };

            keywordFilter = {
                '$or': [filterSalesContract, filterBuyerName, filterBuyerType]
            };
        }
        query = { '$and': [deletedFilter, paging.filter, keywordFilter] }
        return query;
    }

    _beforeInsert(salesContract) {
        salesContract.salesContractNo = salesContract.salesContractNo === "" ? generateCode() : salesContract.salesContractNo;
        salesContract._createdDate = new Date();
        return Promise.resolve(salesContract);
    }

    _validate(salesContract) {
        var errors = {};
        var valid = salesContract;

        var getSalesContractPromise = this.collection.singleOrDefault({
            _id: {
                '$ne': new ObjectId(valid._id)
            },
            salesContractNo: valid.salesContractNo
        });

        //get Object from ...
        var getBuyer = valid.buyer && ObjectId.isValid(valid.buyer._id) ? this.buyerManager.getSingleByIdOrDefault(valid.buyer._id) : Promise.resolve(null);
        var getUom = valid.uom && ObjectId.isValid(valid.uom._id) ? this.UomManager.getSingleByIdOrDefault(valid.uom._id) : Promise.resolve(null);
        var getProduct = valid.material && ObjectId.isValid(valid.material._id) ? this.ProductManager.getSingleByIdOrDefault(valid.material._id) : Promise.resolve(null);
        var getYarnMaterial = valid.yarnMaterial && ObjectId.isValid(valid.yarnMaterial._id) ? this.YarnMaterialManager.getSingleByIdOrDefault(valid.yarnMaterial._id) : Promise.resolve(null);
        var getMaterialConstruction = valid.materialConstruction && ObjectId.isValid(valid.materialConstruction._id) ? this.MaterialConstructionManager.getSingleByIdOrDefault(valid.materialConstruction._id) : Promise.resolve(null);
        var getComodity = valid.comodity && ObjectId.isValid(valid.comodity._id) ? this.ComodityManager.getSingleByIdOrDefault(valid.comodity._id) : Promise.resolve(null);
        var getQuality = valid.quality && ObjectId.isValid(valid.quality._id) ? this.QualityManager.getSingleByIdOrDefault(valid.quality._id) : Promise.resolve(null);
        var getBankAccount = valid.accountBank && ObjectId.isValid(valid.accountBank._id) ? this.AccountBankManager.getSingleByIdOrDefault(valid.accountBank._id) : Promise.resolve(null);
        var getTermOfPayment = valid.termOfPayment && ObjectId.isValid(valid.termOfPayment._id) ? this.TermOfPaymentManager.getSingleByIdOrDefault(valid.termOfPayment._id) : Promise.resolve(null);
        var getAgent = valid.agent && ObjectId.isValid(valid.agent._id) ? this.buyerManager.getSingleByIdOrDefault(valid.agent._id) : Promise.resolve(null);

        return Promise.all([getSalesContractPromise, getBuyer, getUom, getProduct, getYarnMaterial, getMaterialConstruction, getComodity, getQuality, getBankAccount, getTermOfPayment, getAgent])
            .then(results => {
                var _salesContract = results[0];
                var _buyer = results[1];
                var _uom = results[2];
                var _material = results[3];
                var _yarn = results[4];
                var _construction = results[5];
                var _comodity = results[6];
                var _quality = results[7];
                var _bank = results[8];
                var _payment = results[9];
                var _agent = results[10];

                if (valid.uom) {
                    if (!valid.uom.unit || valid.uom.unit == '')
                        errors["uom"] = i18n.__("WeavingSalesContract.uom.isRequired:%s is required", i18n.__("WeavingSalesContract.uom._:Uom")); //"Satuan tidak boleh kosong";
                }
                else
                    errors["uom"] = i18n.__("WeavingSalesContract.uom.isRequired:%s is required", i18n.__("WeavingSalesContract.uom._:Uom")); //"Satuan tidak boleh kosong";

                if (_salesContract) {
                    errors["salesContractNo"] = i18n.__("WeavingSalesContract.salesContractNo.isExist:%s is Exist", i18n.__("WeavingSalesContract.salesContractNo._:SalesContractNo")); //"no Sales Contract tidak boleh kosong";
                }

                if (!_construction) {
                    errors["materialConstruction"] = i18n.__("WeavingSalesContract.materialConstruction.isRequired:%s is not exsist", i18n.__("WeavingSalesContract.materialConstruction._:MaterialConstruction")); //"materialConstruction tidak boleh kosong";
                }

                if (!_payment) {
                    errors["termOfPayment"] = i18n.__("FinishingPrintingSalesContract.termOfPayment.isRequired:%s is not exsist", i18n.__("FinishingPrintingSalesContract.termOfPayment._:TermOfPayment")); //"termOfPayment tidak boleh kosong";
                }

                if (!_yarn) {
                    errors["yarnMaterial"] = i18n.__("WeavingSalesContract.yarnMaterial.isRequired:%s is not exsist", i18n.__("WeavingSalesContract.yarnMaterial._:YarnMaterial")); //"yarnMaterial tidak boleh kosong";
                }

                if (!_quality) {
                    errors["quality"] = i18n.__("WeavingSalesContract.quality.isRequired:%s is not exsist", i18n.__("WeavingSalesContract.quality._:Quality")); //"quality tidak boleh kosong";
                }

                if (!_material)
                    errors["material"] = i18n.__("WeavingSalesContract.material.isRequired:%s is not exists", i18n.__("WeavingSalesContract.material._:Material")); //"material tidak boleh kosong";

                if (!valid.materialWidth || valid.materialWidth === '') {
                    errors["materialWidth"] = i18n.__("WeavingSalesContract.materialWidth.isRequired:%s is required", i18n.__("WeavingSalesContract.materialWidth._:MaterialWidth")); //"lebar material tidak boleh kosong";
                }

                if (!_comodity)
                    errors["comodity"] = i18n.__("WeavingSalesContract.comodity.isRequired:%s is not exists", i18n.__("WeavingSalesContract.comodity._:Comodity")); //"comodity tidak boleh kosong";

                // if (!valid.condition || valid.condition === '') {
                //     errors["condition"] = i18n.__("WeavingSalesContract.condition.isRequired:%s is required", i18n.__("WeavingSalesContract.condition._:Condition")); //"condition tidak boleh kosong";
                // }

                // if (!valid.packing || valid.packing === '') {
                //     errors["packing"] = i18n.__("WeavingSalesContract.packing.isRequired:%s is required", i18n.__("WeavingSalesContract.packing._:Packing")); //"packing tidak boleh kosong";
                // }

                if (!_buyer)
                    errors["buyer"] = i18n.__("WeavingSalesContract.buyer.isRequired:%s is not exists", i18n.__("WeavingSalesContract.buyer._:Buyer")); //"Buyer tidak boleh kosong";

                if (!_bank)
                    errors["accountBank"] = i18n.__("WeavingSalesContract.accountBank.isRequired:%s is not exists", i18n.__("WeavingSalesContract.accountBank._:accountBank")); //"accountBank tidak boleh kosong";

                if (!valid.shippingQuantityTolerance || valid.shippingQuantityTolerance === 0)
                    errors["shippingQuantityTolerance"] = i18n.__("WeavingSalesContract.shippingQuantityTolerance.isRequired:%s is required", i18n.__("WeavingSalesContract.shippingQuantityTolerance._:ShippingQuantityTolerance")); //"shippingQuantityTolerance tidak boleh kosong";
                if (valid.shippingQuantityTolerance > 100) {
                    errors["shippingQuantityTolerance"] = i18n.__("WeavingSalesContract.shippingQuantityTolerance.shouldNot:%s should not more than 100", i18n.__("WeavingSalesContract.shippingQuantityTolerance._:ShippingQuantityTolerance")); //"shippingQuantityTolerance tidak boleh lebih dari 100";
                }

                if (!valid.price || valid.price === 0)
                    errors["price"] = i18n.__("WeavingSalesContract.price.isRequired:%s is required", i18n.__("WeavingSalesContract.price._:Price")); //"price tidak boleh kosong";

                if (!valid.deliveredTo || valid.deliveredTo === '') {
                    errors["deliveredTo"] = i18n.__("WeavingSalesContract.deliveredTo.isRequired:%s is required", i18n.__("WeavingSalesContract.deliveredTo._:DeliveredTo")); //"deliveredTo tidak boleh kosong";
                }

                if (!valid.deliverySchedule || valid.deliverySchedule === "") {
                    errors["deliverySchedule"] = i18n.__("WeavingSalesContract.deliverySchedule.isRequired:%s is required", i18n.__("WeavingSalesContract.deliverySchedule._:deliverySchedule")); //"deliverySchedule tidak boleh kosong";
                }

                if (!valid.incomeTax || valid.incomeTax === '') {
                    errors["incomeTax"] = i18n.__("WeavingSalesContract.incomeTax.isRequired:%s is required", i18n.__("WeavingSalesContract.incomeTax._:IncomeTax")); //"incomeTax tidak boleh kosong";
                }
                else {

                    valid.deliverySchedule = new Date(valid.deliverySchedule);
                    var today = new Date();
                    today.setHours(0, 0, 0, 0);
                    if (today > valid.deliverySchedule) {
                        errors["deliverySchedule"] = i18n.__("WeavingSalesContract.deliverySchedule.shouldNot:%s should not be less than today's date", i18n.__("WeavingSalesContract.deliverySchedule._:deliverySchedule")); //"deliverySchedule tidak boleh kurang dari tanggal hari ini";
                    }

                }

                if (!valid.orderQuantity || valid.orderQuantity === '' || valid.orderQuantity === 0) {
                    errors["orderQuantity"] = i18n.__("WeavingSalesContract.orderQuantity.isRequired:%s should greater than 0", i18n.__("WeavingSalesContract.orderQuantity._:orderQuantity")); //"orderQuantity tidak boleh kosong";
                }

                if (_agent) {
                    valid.agentId = new ObjectId(_agent._id);
                    valid.agent = _agent;
                }

                if (_buyer) {
                    valid.buyerId = new ObjectId(_buyer._id);
                    valid.buyer = _buyer;
                    if (valid.buyer.type.trim().toLowerCase() == "ekspor") {
                        if (!valid.termOfShipment || valid.termOfShipment == "") {
                            errors["termOfShipment"] = i18n.__("WeavingSalesContract.termOfShipment.isRequired:%s is required", i18n.__("WeavingSalesContract.termOfShipment._:termOfShipment")); //"termOfShipment tidak boleh kosong jika buyer type ekspor";
                        }

                        // valid.agentId = new ObjectId(_agent._id);
                        // valid.agent = _agent;
                        // if (!valid.agent) {
                        //     errors["agent"] = i18n.__("WeavingSalesContract.agent.isRequired:%s is required", i18n.__("WeavingSalesContract.agent._:agent")); //"agent tidak boleh kosong jika type buyer ekspor";
                        // }

                        if (valid.agent) {
                            if (!valid.comission) {
                                errors["comission"] = i18n.__("WeavingSalesContract.comission.isRequired:%s is required", i18n.__("WeavingSalesContract.comission._:comission")); //"comission tidak boleh kosong jika agent valid";
                            }
                        }

                    }
                }

                if (_quality) {
                    valid.qualityId = new ObjectId(_quality._id);
                    valid.quality = _quality;
                }
                if (_uom) {
                    valid.uomId = new ObjectId(_uom._id);
                    valid.uom = _uom;
                }

                if (_material) {
                    valid.material = _material;
                    valid.materialId = new ObjectId(_material._id);
                }
                if (_comodity) {
                    valid.comodityId = new ObjectId(_comodity._id);
                    valid.comodity = _comodity;
                }
                if (_yarn) {
                    valid.yarnMaterialId = new ObjectId(_yarn._id);
                    valid.yarnMaterial = _yarn;
                }
                if (_bank) {
                    valid.accountBankId = new ObjectId(_bank._id);
                    valid.accountBank = _bank;
                }
                if (_construction) {
                    valid.materialConstructionId = new ObjectId(_construction._id);
                    valid.materialConstruction = _construction;
                }

                //set GMT+7
                var date = new Date(valid.deliverySchedule);
                date.setHours(new Date(valid.deliverySchedule).getHours() + 7);
                valid.deliverySchedule = new Date(date);

                if (Object.getOwnPropertyNames(errors).length > 0) {
                    var ValidationError = require('module-toolkit').ValidationError;
                    return Promise.reject(new ValidationError('data does not pass validation', errors));
                }

                if (!valid.stamp) {
                    valid = new WeavingSalesContract(valid);
                }

                valid.stamp(this.user.username, "manager");

                return Promise.resolve(valid);
            });
    }

    _createIndexes() {
        var dateIndex = {
            name: `ix_${map.sales.collection.WeavingSalesContract}__updatedDate`,
            key: {
                _updatedDate: -1
            }
        }

        var noIndex = {
            name: `ix_${map.sales.collection.WeavingSalesContract}_salesContractNo`,
            key: {
                salesContractNo: 1
            },
            unique: true
        }

        return this.collection.createIndexes([dateIndex, noIndex]);
    }

    pdf(id) {
        return new Promise((resolve, reject) => {

            this.getSingleById(id)
                .then(salesContract => {

                    var getDefinition = require("../../pdf/definitions/weaving-sales-contract");
                    var definition = getDefinition(salesContract);

                    var generatePdf = require("../../pdf/pdf-generator");
                    generatePdf(definition)
                        .then(binary => {
                            resolve(binary);
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });
        });
    }
}<|endoftext|>


<commit_before>/*global describe, it*/
var assert = require('assert'),
  fs = require('fs'),
  execSync = require('child_process').execSync,
  path = require('path'),
  RSVP = require('rsvp'),
  unirest = require('unirest'),
  skeemas = require('skeemas'),
  debug = require('debug')('validator'),
  parallel = require('mocha.parallel'),
  colors = require('mocha/lib/reporters/base').colors;

// setup mocha color scheme
// 32 = console code for green
colors.pass = 32;

function getModifiedPaths() {
  assert.ok(process.env.TRAVIS_COMMIT_RANGE, 'VALIDATE_MODIFIED_ONLY requires TRAVIS_COMMIT_RANGE to be set to [START_COMMIT_HASH]...[END_COMMIT_HASH]');
  var stdout = execSync('git diff --name-only ' + process.env.TRAVIS_COMMIT_RANGE, {
    encoding: 'utf8'
  });
  var lines = stdout.split('\n');
  var result = {};

  for (var i = 0; i < lines.length; i += 1) {
    result[lines[i]] = lines[i];
  }

  return result;
}
// Tries to parse a json string and asserts with a friendly
// message if something is wrong
function tryParse(fileName, jsonStringData) {
  var object;

  try {
    object = JSON.parse(jsonStringData);
  } catch (e) {
    assert(false, fileName + ' is not valid JSON. Copy and paste the contents to https://jsonformatter.curiousconcept.com/ and correct the syntax errors. Error: ' + e.toString());
  }

  return object;
}

// Vaidates that the expected file paths exist
function ensureExists(templatePath) {
  assert(fs.existsSync(templatePath), 'The file ' + templatePath + ' is missing.');
}

function validateMetadata(metadataPath) {
  var metadataData = fs.readFileSync(metadataPath, {
    encoding: 'utf-8'
  });
  metadataData = metadataData.trim();
  console.log('In validate metadata');

  var metadata = tryParse(metadataPath, metadataData);

  var result = skeemas.validate(metadata, {
    properties: {
      itemDisplayName: {
        type: 'string',
        required: true,
        minLength: 10,
        maxLength: 60
      },
      description: {
        type: 'string',
        required: true,
        minLength: 10,
        maxLength: 1000
      },
      summary: {
        type: 'string',
        required: true,
        minLength: 10,
        maxLength: 200
      },
      githubUsername: {
        type: 'string',
        required: true,
        minLength: 2
      },
      dateUpdated: {
        type: 'string',
        required: true,
        minLength: 10
      },
      icon: {
        type: 'string'
      }
    },
    additionalProperties: false
  });
  var messages = '';
  result.errors.forEach(function (error) {
    messages += (metadataPath + ' - ' + error.context + ':' + error.message + '\n');
  });
  assert(result.valid, messages);

  // validate description has no html
  assert(!/<[a-z][\s\S]*>/i.test(metadata.description), metadataPath + ' - Contains possible HTML elements which are not allowed');
  // validate date
  var date = new Date(metadata.dateUpdated);
  var currentTime = new Date(Date.now());
  assert(!isNaN(date.getTime()), metadataPath + ' - dateUpdated field should be a valid date in the format YYYY-MM-DD');
  // validate date is not in future
  assert(date < currentTime, metadataPath + ' - dateUpdated field should not be in the future');
}

// azure cli apparently does not check for this
function validateTemplateParameters(templatePath, templateObject) {
  assert.ok(templateObject.parameters, 'Expected a \'.parameters\' field within the deployment template');
  for (var k in templateObject.parameters) {
    if (typeof k === 'string') {
      assert.ok(templateObject.parameters[k].metadata,
        templatePath + ' -  Parameter \"' + k + '\" is missing its \"metadata\" property');
      assert.ok(templateObject.parameters[k].metadata.description,
        templatePath + ' - Parameter \"' + k + '\" is missing its \"description\" field within the metadata property');
    }
  }
}

function validateParamtersFile(parametersPath) {
  var parametersData = fs.readFileSync(parametersPath, {
    encoding: 'utf-8'
  });
  var metadataData = parametersData.trim();
  console.log('In validate Template File');

  var parametersObject = tryParse(parametersPath, metadataData);

  assert.ok(parametersObject.parameters, parametersPath + ' - Expected a \'.parameters\' field within the parameters file');
  for (var k in parametersObject.parameters) {
    if (typeof k === 'string') {
      assert.ok(parametersObject.parameters[k].value !== null &&
        parametersObject.parameters[k].value !== undefined &&
        parametersObject.parameters[k].value !== '',
        parametersPath + ' -  Parameter \"' + k + '\" is missing its value field');
    }
  }
}

function prepTemplate(templatePath, parametersPath) {
  var templateData = fs.readFileSync(templatePath, {
      encoding: 'utf-8'
    }),
    parameterData = fs.readFileSync(parametersPath, {
      encoding: 'utf-8'
    });

  templateData = templateData.trim();
  parameterData = parameterData.trim();
  console.log('In Prep Template');

  var requestBody = {
    template: tryParse(templatePath, templateData),
    parameters: tryParse(templatePath, parameterData)
  };

  return requestBody;
}

// Calls a remote url which will validate the template and parameters
function validateTemplate(templatePath, parametersPath) {
  var requestBody = prepTemplate(templatePath, parametersPath);
  console.log('In validateTemplate');

  if (process.env.TRAVIS_PULL_REQUEST &&
    process.env.TRAVIS_PULL_REQUEST !== 'false') {
    requestBody.pull_request = process.env.TRAVIS_PULL_REQUEST;
  }

  // validate the template paramters, particularly the description field
  validateTemplateParameters(templatePath, requestBody.template);

  return new RSVP.Promise(function (resolve, reject) {
    unirest.post(process.env.VALIDATION_HOST + '/validate')
      .type('json')
      .send(JSON.stringify(requestBody))
      .end(function (response) {
        if (response.status !== 200) {
            reject(response);
          } else {
            resolve(response.body);
          }
      });
  });
}

// this is required to keep travis from timing out
// due to lack of console output
function timedOutput(onOff, intervalObject) {
  if (onOff) {
    return setInterval(function () {
      process.stdout.write('...');
    }, 60 * 1000);
  } else {
    clearTimeout(intervalObject);
  }
}

// Calls a remote url which will deploy the template
function deployTemplate(templatePath, parametersPath) {
  var requestBody = prepTemplate(templatePath, parametersPath);
  console.log('In deployTemplate');

  if (process.env.TRAVIS_PULL_REQUEST &&
    process.env.TRAVIS_PULL_REQUEST !== 'false') {
    requestBody.pull_request = process.env.TRAVIS_PULL_REQUEST;
  }

  // validate the template paramters, particularly the description field
  validateTemplateParameters(templatePath, requestBody.template);

  var intervalObj = timedOutput(true);
  debug('making deploy request');
  console.log('making deploy request');

  return new RSVP.Promise(function (resolve, reject) {
    unirest.post(process.env.VALIDATION_HOST + '/deploy')
      .type('json')
      .timeout(3600 * 1000) // template deploy can take some time
      .send(JSON.stringify(requestBody))
      .end(function (response) {
        timedOutput(false, intervalObj);
        debug(response.status);
        debug(response.body);

        // 202 is the long poll response
        // anything else is really bad
        if (response.status !== 202) {
          return reject(response.body);
        }

        if (response.body.result === 'Deployment Successful') {
          console.log('Custom log: Deployment Successful... Exiting from deployTemplate');
          return resolve(response.body);
        } else {
          return reject(response.body);
        }
      });
  });
}

function getDirectories(srcpath) {
  return fs.readdirSync(srcpath).filter(function (file) {
    return fs.statSync(path.join(srcpath, file)).isDirectory();
  });
}

// Generates the mocha tests based on directories in
// the existing repo.
function generateTests(modifiedPaths) {
  var tests = [];
  var directories = getDirectories('./');
  debug(modifiedPaths);
  var modifiedDirs = {};

  for (var k in modifiedPaths) {
    if (typeof k === 'string') {
      // don't include the top level dir
      if (path.dirname(k) === '.') {
        continue;
      }
      modifiedDirs[path.dirname(k)] = true;
    }
  }
  debug('modified dirs:');
  debug(modifiedDirs);
  directories.forEach(function (dirName) {
    // exceptions
    if (dirName === '.git' ||
      dirName === 'node_modules') {
      return;
    }

    if (fs.existsSync(path.join(dirName, '.ci_skip'))) {
      return;
    }
    var templatePath = path.join(dirName, 'azuredeploy.json'),
      paramsPath = path.join(dirName, 'azuredeploy.parameters.json'),
      metadataPath = path.join(dirName, 'metadata.json'),
      readmePath = path.join(dirName, 'README.md');

    // if we are only validating modified templates
    // only add test if this directory template has been modified
    if (modifiedPaths && !modifiedDirs[dirName]) {
      return;
    }

    tests.push({
      args: [templatePath, paramsPath, metadataPath, readmePath],
      expected: true
    });
  });

  debug('created tests:');
  debug(tests);

  return tests;
}

// Group tests in chunks defined by an environment variable
// or by the default value
function groupTests(modifiedPaths) {
  // we probably shouldn't deploy a ton of templates at once...
  var tests = generateTests(modifiedPaths),
    testGroups = [],
    groupIndex = 0,
    counter = 0,
    groupSize = process.env.PARALLEL_DEPLOYMENT_NUMBER || 2;

  tests.forEach(function (test) {
    if (!testGroups[groupIndex]) {
      testGroups[groupIndex] = [];
    }

    testGroups[groupIndex].push(test);
    counter += 1;

    if (counter % groupSize === 0) {
      groupIndex += 1;
    }
  });

  return testGroups;
}

describe('Template', function () {
  this.timeout(7100 * 1000);

  var modifiedPaths;

  if (process.env.VALIDATE_MODIFIED_ONLY) {
    var count = 0;
    // we automatically reset to the beginning of the commit range
    // so this includes all file paths that have changed for the CI run
    modifiedPaths = getModifiedPaths();
    debug(modifiedPaths);
    for (var i in modifiedPaths) {
      if (typeof i === 'string') {
        count += 1;
      }
    }

    assert(count !== 0, 'No changes were detected in your commit. Verify you added files and try again.');
  }

  var testGroups = groupTests(modifiedPaths);

  testGroups.forEach(function (tests) {
    parallel('Running ' + tests.length + ' Parallel Template Validation(s)...', function () {
      tests.forEach(function (test) {
        it(test.args[0] + ' & ' + test.args[1] + ' should be valid', function () {
          // validate template files are in correct place
          test.args.forEach(function (path) {
            ensureExists.apply(null, [path]);
          });

          validateMetadata.apply(null, [test.args[2]]);
          validateParamtersFile.apply(null, [test.args[1]]);

          return validateTemplate.apply(null, test.args)
            .then(function () {
              debug('template validation sucessful, deploying template...');
              return deployTemplate.apply(null, test.args);
            })
            .then(function () {
              // success
              return assert(true);
            })
            .catch(function (err) {
              var errorString = 'Template Validiation Failed. Try deploying your template with the commands:\n';
              errorString += 'azure group template validate --resource-group (your_group_name) ';
              errorString += ' --template-file ' + test.args[0] + ' --parameters-file ' + test.args[1] + '\n';
              errorString += 'azure group deployment create --resource-group (your_group_name) ';
              errorString += ' --template-file ' + test.args[0] + ' --parameters-file ' + test.args[1];
              assert(false, errorString + ' \n\nServer Error:' + JSON.stringify(err, null, 4));
            });
        });
      });
    });
  });
});
<commit_msg>Update tests.js<commit_after>/*global describe, it*/
var assert = require('assert'),
    fs = require('fs'),
    execSync = require('child_process').execSync,
    path = require('path'),
    RSVP = require('rsvp'),
    unirest = require('unirest'),
    skeemas = require('skeemas'),
    debug = require('debug')('validator'),
    parallel = require('mocha.parallel'),
    colors = require('mocha/lib/reporters/base').colors;

// setup mocha color scheme
// 32 = console code for green
colors.pass = 32;

function getModifiedPaths() {
    assert.ok(process.env.TRAVIS_COMMIT_RANGE, 'VALIDATE_MODIFIED_ONLY requires TRAVIS_COMMIT_RANGE to be set to [START_COMMIT_HASH]...[END_COMMIT_HASH]');
    var stdout = execSync('git diff --name-only ' + process.env.TRAVIS_COMMIT_RANGE, {
        encoding: 'utf8'
    });
    var lines = stdout.split('\n');
    var result = {};

    for (var i = 0; i < lines.length; i += 1) {
        result[lines[i]] = lines[i];
    }

    return result;
}
// Tries to parse a json string and asserts with a friendly
// message if something is wrong
function tryParse(fileName, jsonStringData) {
    var object;

    try {
        object = JSON.parse(jsonStringData);
    } catch (e) {
        assert(false, fileName + ' is not valid JSON. Copy and paste the contents to https://jsonformatter.curiousconcept.com/ and correct the syntax errors. Error: ' + e.toString());
    }

    return object;
}

// Vaidates that the expected file paths exist
function ensureExists(templatePath) {
    assert(fs.existsSync(templatePath), 'The file ' + templatePath + ' is missing.');
}

function validateMetadata(metadataPath) {
    var metadataData = fs.readFileSync(metadataPath, {
        encoding: 'utf-8'
    });
    metadataData = metadataData.trim();
    console.log('In validate metadata');

    var metadata = tryParse(metadataPath, metadataData);

    var result = skeemas.validate(metadata, {
        properties: {
            itemDisplayName: {
                type: 'string',
                required: true,
                minLength: 10,
                maxLength: 60
            },
            description: {
                type: 'string',
                required: true,
                minLength: 10,
                maxLength: 1000
            },
            summary: {
                type: 'string',
                required: true,
                minLength: 10,
                maxLength: 200
            },
            githubUsername: {
                type: 'string',
                required: true,
                minLength: 2
            },
            dateUpdated: {
                type: 'string',
                required: true,
                minLength: 10
            },
            icon: {
                type: 'string'
            }
        },
        additionalProperties: false
    });
    var messages = '';
    result.errors.forEach(function(error) {
        messages += (metadataPath + ' - ' + error.context + ':' + error.message + '\n');
    });
    assert(result.valid, messages);

    // validate description has no html
    assert(!/<[a-z][\s\S]*>/i.test(metadata.description), metadataPath + ' - Contains possible HTML elements which are not allowed');
    // validate date
    var date = new Date(metadata.dateUpdated);
    var currentTime = new Date(Date.now());
    assert(!isNaN(date.getTime()), metadataPath + ' - dateUpdated field should be a valid date in the format YYYY-MM-DD');
    // validate date is not in future
    assert(date < currentTime, metadataPath + ' - dateUpdated field should not be in the future');
}

// azure cli apparently does not check for this
function validateTemplateParameters(templatePath, templateObject) {
    assert.ok(templateObject.parameters, 'Expected a \'.parameters\' field within the deployment template');
    for (var k in templateObject.parameters) {
        if (typeof k === 'string') {
            assert.ok(templateObject.parameters[k].metadata,
                templatePath + ' -  Parameter \"' + k + '\" is missing its \"metadata\" property');
            assert.ok(templateObject.parameters[k].metadata.description,
                templatePath + ' - Parameter \"' + k + '\" is missing its \"description\" field within the metadata property');
        }
    }
}

function validateParamtersFile(parametersPath) {
    var parametersData = fs.readFileSync(parametersPath, {
        encoding: 'utf-8'
    });
    var metadataData = parametersData.trim();
    console.log('In validate Template File');

    var parametersObject = tryParse(parametersPath, metadataData);

    assert.ok(parametersObject.parameters, parametersPath + ' - Expected a \'.parameters\' field within the parameters file');
    for (var k in parametersObject.parameters) {
        if (typeof k === 'string') {
            assert.ok(parametersObject.parameters[k].value !== null &&
                parametersObject.parameters[k].value !== undefined &&
                parametersObject.parameters[k].value !== '',
                parametersPath + ' -  Parameter \"' + k + '\" is missing its value field');
        }
    }
}

function prepTemplate(templatePath, parametersPath) {
    var templateData = fs.readFileSync(templatePath, {
            encoding: 'utf-8'
        }),
        parameterData = fs.readFileSync(parametersPath, {
            encoding: 'utf-8'
        });

    templateData = templateData.trim();
    parameterData = parameterData.trim();
    console.log('In Prep Template');

    var requestBody = {
        template: tryParse(templatePath, templateData),
        parameters: tryParse(templatePath, parameterData)
    };

    return requestBody;
}

// Calls a remote url which will validate the template and parameters
function validateTemplate(templatePath, parametersPath) {
    var requestBody = prepTemplate(templatePath, parametersPath);
    console.log('In validateTemplate');

    if (process.env.TRAVIS_PULL_REQUEST &&
        process.env.TRAVIS_PULL_REQUEST !== 'false') {
        requestBody.pull_request = process.env.TRAVIS_PULL_REQUEST;
    }

    // validate the template paramters, particularly the description field
    validateTemplateParameters(templatePath, requestBody.template);

    return new RSVP.Promise(function(resolve, reject) {
        unirest.post(process.env.VALIDATION_HOST + '/validate')
            .type('json')
            .send(JSON.stringify(requestBody))
            .end(function(response) {
                if (response.status !== 200) {
                    reject(response);
                } else {
                    resolve(response.body);
                }
            });
    });
}

// this is required to keep travis from timing out
// due to lack of console output
function timedOutput(onOff, intervalObject) {
    if (onOff) {
        return setInterval(function() {
            process.stdout.write('...');
        }, 60 * 1000);
    } else {
        clearTimeout(intervalObject);
    }
}

// Calls a remote url which will deploy the template
function deployTemplate(templatePath, parametersPath) {
    var requestBody = prepTemplate(templatePath, parametersPath);
    console.log('In deployTemplate');

    if (process.env.TRAVIS_PULL_REQUEST &&
        process.env.TRAVIS_PULL_REQUEST !== 'false') {
        requestBody.pull_request = process.env.TRAVIS_PULL_REQUEST;
    }

    // validate the template paramters, particularly the description field
    validateTemplateParameters(templatePath, requestBody.template);

    var intervalObj = timedOutput(true);
    debug('making deploy request');
    console.log('making deploy request');

    return new RSVP.Promise(function(resolve, reject) {
        unirest.post(process.env.VALIDATION_HOST + '/deploy')
            .type('json')
            .timeout(3600 * 1000) // template deploy can take some time
            .send(JSON.stringify(requestBody))
            .end(function(response) {
                timedOutput(false, intervalObj);
                debug(response.status);
                debug(response.body);

                // 202 is the long poll response
                // anything else is really bad
                if (response.status !== 202) {
                    return reject(response.body);
                }

                if (response.body.result === 'Deployment Successful') {
                    console.log('Custom log: Deployment Successful... Exiting from deployTemplate');
                    return resolve(response.body);
                } else {
                    return reject(response.body);
                }
            });
    });
}

function getDirectories(srcpath) {
    return fs.readdirSync(srcpath).filter(function(file) {
        return fs.statSync(path.join(srcpath, file)).isDirectory();
    });
}

// Generates the mocha tests based on directories in
// the existing repo.
function generateTests(modifiedPaths) {
    var tests = [];
    var directories = getDirectories('./');
    debug(modifiedPaths);
    var modifiedDirs = {};

    for (var k in modifiedPaths) {
        if (typeof k === 'string') {
            // don't include the top level dir
            if (path.dirname(k) === '.') {
                continue;
            }
            modifiedDirs[path.dirname(k)] = true;
        }
    }
    debug('modified dirs:');
    debug(modifiedDirs);
    directories.forEach(function(dirName) {
        // exceptions
        if (dirName === '.git' ||
            dirName === 'node_modules') {
            return;
        }

        if (fs.existsSync(path.join(dirName, '.ci_skip'))) {
            return;
        }
        var templatePath = path.join(dirName, 'azuredeploy.json'),
            paramsPath = path.join(dirName, 'azuredeploy.parameters.json'),
            metadataPath = path.join(dirName, 'metadata.json'),
            readmePath = path.join(dirName, 'README.md');

        // if we are only validating modified templates
        // only add test if this directory template has been modified
        if (modifiedPaths && !modifiedDirs[dirName]) {
            return;
        }

        tests.push({
            args: [templatePath, paramsPath, metadataPath, readmePath],
            expected: true
        });
    });

    debug('created tests:');
    debug(tests);

    return tests;
}

// Group tests in chunks defined by an environment variable
// or by the default value
function groupTests(modifiedPaths) {
    // we probably shouldn't deploy a ton of templates at once...
    var tests = generateTests(modifiedPaths),
        testGroups = [],
        groupIndex = 0,
        counter = 0,
        groupSize = process.env.PARALLEL_DEPLOYMENT_NUMBER || 2;

    tests.forEach(function(test) {
        if (!testGroups[groupIndex]) {
            testGroups[groupIndex] = [];
        }

        testGroups[groupIndex].push(test);
        counter += 1;

        if (counter % groupSize === 0) {
            groupIndex += 1;
        }
    });

    return testGroups;
}

describe('Template', function() {
    this.timeout(7100 * 1000);

    var modifiedPaths;

    if (process.env.VALIDATE_MODIFIED_ONLY) {
        var count = 0;
        // we automatically reset to the beginning of the commit range
        // so this includes all file paths that have changed for the CI run
        modifiedPaths = getModifiedPaths();
        debug(modifiedPaths);
        for (var i in modifiedPaths) {
            if (typeof i === 'string') {
                count += 1;
            }
        }

        assert(count !== 0, 'No changes were detected in your commit. Verify you added files and try again.');
    }

    var testGroups = groupTests(modifiedPaths);

    testGroups.forEach(function(tests) {
        parallel('Running ' + tests.length + ' Parallel Template Validation(s)...', function() {
            tests.forEach(function(test) {
                it(test.args[0] + ' & ' + test.args[1] + ' should be valid', function() {
                    // validate template files are in correct place
                    test.args.forEach(function(path) {
                        ensureExists.apply(null, [path]);
                    });

                    validateMetadata.apply(null, [test.args[2]]);
                    validateParamtersFile.apply(null, [test.args[1]]);

                    return validateTemplate.apply(null, test.args)
                        .then(function() {
                            debug('template validation sucessful, deploying template...');
                            return deployTemplate.apply(null, test.args);
                        })
                        .then(function() {
                            // success
                            return assert(true);
                        })
                        .catch(function(err) {
                            var errorString = 'Template Validiation Failed. Try deploying your template with the commands:\n';
                            errorString += 'azure group template validate --resource-group (your_group_name) ';
                            errorString += ' --template-file ' + test.args[0] + ' --parameters-file ' + test.args[1] + '\n';
                            errorString += 'azure group deployment create --resource-group (your_group_name) ';
                            errorString += ' --template-file ' + test.args[0] + ' --parameters-file ' + test.args[1];
                            assert(false, errorString + ' \n\nServer Error:' + JSON.stringify(err, null, 4));
                        });
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>function cleanSelected() {
    // use jquery's API to add and remove class property
    $('#testCase-grid .selectedCase').removeClass('selectedCase');
    $('#testCase-grid .selectedSuite').removeClass('selectedSuite');
}

function setSelectedSuite(id) {
    saveOldCase();
    cleanSelected();
    $("#" + id).addClass('selectedSuite');
    clean_panel();
    // document.getElementById("records-grid").innerHTML = "";
}

function setSelectedCase(id) {
    saveOldCase();
    var suite_id = document.getElementById(id).parentNode.id;
    setSelectedSuite(suite_id);
    $("#" + id).addClass('selectedCase');
    clean_panel();
    document.getElementById("records-grid").innerHTML = escapeHTML(sideex_testCase[id].records);
}

function getSelectedSuite() {
    if (document.getElementById("testCase-grid").getElementsByClassName("selectedSuite")) {
        return document.getElementById("testCase-grid").getElementsByClassName("selectedSuite")[0];
    } else {
        return null;
    }
}

function getSelectedCase() {
    if (document.getElementById("testCase-grid").getElementsByClassName("selectedCase")) {
        return document.getElementById("testCase-grid").getElementsByClassName("selectedCase")[0];
    } else {
        return null;
    }
}

function saveOldCase() {
    var old_case = getSelectedCase();
    if (old_case) {
        sideex_testCase[old_case.id].records = document.getElementById("records-grid").innerHTML;
    }
}

function appendContextMenu(node, isCase) {
    var ul = document.createElement("ul");
    var a;

    if (isCase) {
        var add_case = document.createElement("li");
        a = document.createElement("a");
        a.setAttribute("href", "#");
        a.innerHTML = "Add New Test Case";
        add_case.appendChild(a);
        add_case.addEventListener("click", function(event) {
            event.stopPropagation();
            document.getElementById('add-testCase').click();
        }, false);
        ul.appendChild(add_case);

        var remove_case = document.createElement("li");
        a = document.createElement("a");
        a.setAttribute("href", "#");
        a.innerHTML = "Remove Test Case";
        remove_case.appendChild(a);
        remove_case.addEventListener("click", function(event) {
            event.stopPropagation();
            document.getElementById('delete-testCase').click();
        }, false);
        ul.appendChild(remove_case);

        var rename_case = document.createElement("li");
        a = document.createElement("a");
        a.setAttribute("href", "#");
        a.innerHTML = "Rename Test Case";
        rename_case.appendChild(a);
        rename_case.addEventListener("click", function(event) {
            event.stopPropagation();
            var s_case = getSelectedCase();
            var n_title = prompt("Please enter the Test Case's title", sideex_testCase[s_case.id].title);
            // get text node
            s_case.childNodes[0].textContent = n_title;
            sideex_testCase[s_case.id].title = n_title;
        }, false);
        ul.appendChild(rename_case);
    } else {
        var open_suite = document.createElement("li");
        a = document.createElement("a");
        a.setAttribute("href", "#");
        a.innerHTML = "Open Test Suites";
        open_suite.appendChild(a);
        open_suite.addEventListener("click", function(event) {
            event.stopPropagation();
            document.getElementById('load-testSuite-hidden').click();
        }, false);
        ul.appendChild(open_suite);

        var add_suite = document.createElement("li");
        a = document.createElement("a");
        a.setAttribute("href", "#");
        a.innerHTML = "Add New Test Suite";
        add_suite.appendChild(a);
        add_suite.addEventListener("click", function(event) {
            event.stopPropagation();
            document.getElementById("add-testSuite").click();
        }, false);
        ul.appendChild(add_suite);

        var save_suite = document.createElement("li");
        a = document.createElement("a");
        a.setAttribute("href", "#");
        a.innerHTML = "Save Test Suite As...";
        save_suite.appendChild(a);
        save_suite.addEventListener("click", function(event) {
            event.stopPropagation();
            document.getElementById('save-testSuite').click();
        }, false);
        ul.appendChild(save_suite);

        var close_suite = document.createElement("li");
        a = document.createElement("a");
        a.setAttribute("href", "#");
        a.innerHTML = "Close Test Suite";
        close_suite.appendChild(a);
        close_suite.addEventListener("click", function(event) {
            event.stopPropagation();
            document.getElementById('close-testSuite').click();
        }, false);
        ul.appendChild(close_suite);

        var add_case = document.createElement("li");
        a = document.createElement("a");
        a.setAttribute("href", "#");
        a.innerHTML = "Add New Test Case";
        add_case.appendChild(a);
        add_case.addEventListener("click", function(event) {
            event.stopPropagation();
            document.getElementById('add-testCase').click();
        }, false);
        ul.appendChild(add_case);

        var rename_suite = document.createElement("li");
        a = document.createElement("a");
        a.setAttribute("href", "#");
        a.innerHTML = "Rename Test Suite";
        rename_suite.appendChild(a);
        rename_suite.addEventListener("click", function(event) {
            event.stopPropagation();
            var s_suite = getSelectedSuite();
            var n_title = prompt("Please enter the Test Suite's title", sideex_testSuite[s_suite.id].title);
            // get text node
            s_suite.childNodes[0].textContent = n_title;
            sideex_testSuite[s_suite.id].title = n_title;
            $(s_suite).find("strong").addClass("modified");
            closeConfirm(true);
        }, false);
        ul.appendChild(rename_suite);
    }

    node.appendChild(ul);
}

function addTestCase(title, id) {
    if (!getSelectedSuite()) {
        var suite_id = "suite" + sideex_testSuite.count;
        sideex_testSuite.count++;
        sideex_testSuite[suite_id] = {
            file_name: "Untitled Test Suite.html",
            title: "Untitled Test Suite"
        };
        addTestSuite("Untitled Test Suite", suite_id);
    }

    var p = document.createElement("p");
    p.innerHTML = escapeHTML(title);
    p.setAttribute("id", id);
    p.setAttribute("contextmenu", "menu" + id);

    var s_case = getSelectedCase();
    if (s_case) {
        s_case.parentNode.insertBefore(p, s_case.nextSibling);
    } else {
        getSelectedSuite().appendChild(p);
    }

    cleanSelected();
    p.classList.add("selectedCase");
    p.parentNode.classList.add("selectedSuite");

    if (sideex_testCase[id]) { // load file
        clean_panel();
        document.getElementById("records-grid").innerHTML = escapeHTML(sideex_testCase[id].records);
        if (sideex_testCase[id].records) {
            reAssignId("records-1", "records-" + getRecordsNum());
            attachEvent(1, getRecordsNum());
        }
    } else { // add new testCase
        clean_panel();
        document.getElementById("records-grid").innerHTML = escapeHTML('<input id="records-count" type=hidden value=0></input>');
        sideex_testCase[id] = {
            records: "",
            title: title
        };
        p.classList.add("modified");
        p.parentNode.getElementsByTagName("strong")[0].classList.add("modified");
    }

    // attach event
    p.addEventListener("click", function(event) {
        event.stopPropagation();
        saveOldCase();
        // use jquery's API to add and remove class property
        cleanSelected();
        this.classList.add("selectedCase");
        this.parentNode.classList.add("selectedSuite");
        if (sideex_testCase[this.id].records) {
            clean_panel();
            document.getElementById("records-grid").innerHTML = escapeHTML(sideex_testCase[this.id].records);
            reAssignId("records-1", "records-" + getRecordsNum());
            attachEvent(1, getRecordsNum());
        } else {
            clean_panel();
            document.getElementById("records-grid").innerHTML = escapeHTML('<input id="records-count" type=hidden value=0></input>');
        }
        // prevent event trigger on parent from child
        event.stopPropagation();
    }, false);

    var menu = document.createElement("div");
    menu.setAttribute("class", "menu");
    menu.setAttribute("id", "menu" + id);
    appendContextMenu(menu, true);
    p.appendChild(menu);

    // right click
    p.addEventListener("contextmenu", function(event) {
        event.preventDefault();
        event.stopPropagation();
        saveOldCase();
        setSelectedCase(this.id);
        var mid = "#" + "menu" + id;
        console.log($(mid));
        $(".menu").css("left", event.pageX);
        $(".menu").css("top", event.pageY);
        $(mid).show();
    }, false);

    closeConfirm(true);
}

function addTestSuite(title, id) {
    var text = document.createElement("strong");
    text.innerHTML = escapeHTML(title);
    var div = document.createElement("div");
    div.setAttribute("id", id);
    div.setAttribute("contextmenu", "menu" + id);
    div.setAttribute("class", "message");
    div.appendChild(text);

    var s_suite = getSelectedSuite();
    if (s_suite) {
        s_suite.parentNode.insertBefore(div, s_suite.nextSibling);
    } else {
        document.getElementById("testCase-grid").appendChild(div);
    }

    cleanSelected();
    div.classList.add("selectedSuite");
    // attach event
    div.addEventListener("click", function(event) {
        if (this.getElementsByTagName("p").length != 0) {
            this.getElementsByTagName("p")[0].click();
        } else {
            event.stopPropagation();
            saveOldCase();
            cleanSelected();
            this.classList.add("selectedSuite");
            clean_panel();
            // document.getElementById("records-grid").innerHTML = "";
        }
    }, false);

    var menu = document.createElement("div");
    menu.setAttribute("class", "menu");
    menu.setAttribute("id", "menu" + id);
    appendContextMenu(menu, false);
    div.appendChild(menu);

    // right click
    div.addEventListener("contextmenu", function(event) {
        event.preventDefault();
        event.stopPropagation();
        saveOldCase();
        setSelectedSuite(this.id);
        var mid = "#" + "menu" + id;
        console.log($(mid));
        $(".menu").css("left", event.pageX);
        $(".menu").css("top", event.pageY);
        $(mid).show();
    }, false);

    makeCaseSortable(div);
}

document.getElementById("add-testSuite").addEventListener("click", function(event) {
    event.stopPropagation();
    var title = prompt("Please enter the Test Suite's title", "Untitled Test Suite");
    if (title) {
        var id = "suite" + sideex_testSuite.count;
        sideex_testSuite.count++;
        sideex_testSuite[id] = {
            file_name: title + ".html",
            title: title
        };
        addTestSuite(title, id);
    }
}, false);

document.getElementById("add-testSuite-menu").addEventListener("click", function(event) {
    event.stopPropagation();
    document.getElementById('add-testSuite').click();
}, false);

var confirmCloseSuite = function(question) {
    var defer = $.Deferred();
    $('

')
        .html(question)
        .dialog({
            title: "Save?",
            resizable: false,
            height: "auto",
            width: 400,
            modal: true,
            buttons: {
                "Yes": function() {
                    defer.resolve("true");
                    $(this).dialog("close");
                },
                "No": function() {
                    defer.resolve("false");
                    $(this).dialog("close");
                },
                Cancel: function() {
                    $(this).dialog("close");
                }
            },
            close: function() {
                $(this).remove();
            }
        });
    return defer.promise();
};

var remove_testSuite = function() {
    var s_suite = getSelectedSuite();
    sideex_testSuite[s_suite.id] = null;
    s_suite.parentNode.removeChild(s_suite);
    clean_panel();
};

document.getElementById("close-testSuite").addEventListener('click', function(event) {
    event.stopPropagation();
    var s_suite = getSelectedSuite();
    if (s_suite) {
        if ($(s_suite).find(".modified").length) {
            confirmCloseSuite("Would you like to save this test suite?").then(function(answer) {
                if (answer === "true")
                    downloadSuite(s_suite, remove_testSuite);
                else
                    remove_testSuite(s_suite);
            });
        } else {
            remove_testSuite(s_suite);
        }
        // document.getElementById("records-grid").innerHTML = "";
    }
}, false);

document.getElementById("add-testCase").addEventListener("click", function(event) {
    var title = prompt("Please enter the Test Case's title", "Untitled Test Case");
    if (title) {
        var id = "case" + sideex_testCase.count;
        sideex_testCase.count++;
        addTestCase(title, id);
    }
}, false);

var remove_testCase = function() {
    var s_case = getSelectedCase();
    sideex_testCase[s_case.id] = null;
    s_case.parentNode.removeChild(s_case);
    clean_panel();
};

document.getElementById("delete-testCase").addEventListener('click', function() {
    var s_case = getSelectedCase();
    console.log(s_case);
    if (s_case) {
        if ($(s_case).hasClass("modified")) {
            confirmCloseSuite("Would you like to save this test case?").then(function(answer) {
                if (answer === "true")
                    downloadSuite(getSelectedSuite(), remove_testCase);
                else
                    remove_testCase();
            });
        } else {
            remove_testCase();
        }
        // document.getElementById("records-grid").innerHTML = "";
    }
}, false);
<commit_msg>Fix record grid no listener after playsuite<commit_after>function cleanSelected() {
    // use jquery's API to add and remove class property
    $('#testCase-grid .selectedCase').removeClass('selectedCase');
    $('#testCase-grid .selectedSuite').removeClass('selectedSuite');
}

function setSelectedSuite(id) {
    saveOldCase();
    cleanSelected();
    $("#" + id).addClass('selectedSuite');
    clean_panel();
    // document.getElementById("records-grid").innerHTML = "";
}

function setSelectedCase(id) {
    saveOldCase();
    var suite_id = document.getElementById(id).parentNode.id;
    setSelectedSuite(suite_id);
    $("#" + id).addClass('selectedCase');
    clean_panel();
    document.getElementById("records-grid").innerHTML = escapeHTML(sideex_testCase[id].records);
    attachEvent(1,getRecordsNum());
}

function getSelectedSuite() {
    if (document.getElementById("testCase-grid").getElementsByClassName("selectedSuite")) {
        return document.getElementById("testCase-grid").getElementsByClassName("selectedSuite")[0];
    } else {
        return null;
    }
}

function getSelectedCase() {
    if (document.getElementById("testCase-grid").getElementsByClassName("selectedCase")) {
        return document.getElementById("testCase-grid").getElementsByClassName("selectedCase")[0];
    } else {
        return null;
    }
}

function saveOldCase() {
    var old_case = getSelectedCase();
    if (old_case) {
        sideex_testCase[old_case.id].records = document.getElementById("records-grid").innerHTML;
    }
}

function appendContextMenu(node, isCase) {
    var ul = document.createElement("ul");
    var a;

    if (isCase) {
        var add_case = document.createElement("li");
        a = document.createElement("a");
        a.setAttribute("href", "#");
        a.innerHTML = "Add New Test Case";
        add_case.appendChild(a);
        add_case.addEventListener("click", function(event) {
            event.stopPropagation();
            document.getElementById('add-testCase').click();
        }, false);
        ul.appendChild(add_case);

        var remove_case = document.createElement("li");
        a = document.createElement("a");
        a.setAttribute("href", "#");
        a.innerHTML = "Remove Test Case";
        remove_case.appendChild(a);
        remove_case.addEventListener("click", function(event) {
            event.stopPropagation();
            document.getElementById('delete-testCase').click();
        }, false);
        ul.appendChild(remove_case);

        var rename_case = document.createElement("li");
        a = document.createElement("a");
        a.setAttribute("href", "#");
        a.innerHTML = "Rename Test Case";
        rename_case.appendChild(a);
        rename_case.addEventListener("click", function(event) {
            event.stopPropagation();
            var s_case = getSelectedCase();
            var n_title = prompt("Please enter the Test Case's title", sideex_testCase[s_case.id].title);
            // get text node
            s_case.childNodes[0].textContent = n_title;
            sideex_testCase[s_case.id].title = n_title;
        }, false);
        ul.appendChild(rename_case);
    } else {
        var open_suite = document.createElement("li");
        a = document.createElement("a");
        a.setAttribute("href", "#");
        a.innerHTML = "Open Test Suites";
        open_suite.appendChild(a);
        open_suite.addEventListener("click", function(event) {
            event.stopPropagation();
            document.getElementById('load-testSuite-hidden').click();
        }, false);
        ul.appendChild(open_suite);

        var add_suite = document.createElement("li");
        a = document.createElement("a");
        a.setAttribute("href", "#");
        a.innerHTML = "Add New Test Suite";
        add_suite.appendChild(a);
        add_suite.addEventListener("click", function(event) {
            event.stopPropagation();
            document.getElementById("add-testSuite").click();
        }, false);
        ul.appendChild(add_suite);

        var save_suite = document.createElement("li");
        a = document.createElement("a");
        a.setAttribute("href", "#");
        a.innerHTML = "Save Test Suite As...";
        save_suite.appendChild(a);
        save_suite.addEventListener("click", function(event) {
            event.stopPropagation();
            document.getElementById('save-testSuite').click();
        }, false);
        ul.appendChild(save_suite);

        var close_suite = document.createElement("li");
        a = document.createElement("a");
        a.setAttribute("href", "#");
        a.innerHTML = "Close Test Suite";
        close_suite.appendChild(a);
        close_suite.addEventListener("click", function(event) {
            event.stopPropagation();
            document.getElementById('close-testSuite').click();
        }, false);
        ul.appendChild(close_suite);

        var add_case = document.createElement("li");
        a = document.createElement("a");
        a.setAttribute("href", "#");
        a.innerHTML = "Add New Test Case";
        add_case.appendChild(a);
        add_case.addEventListener("click", function(event) {
            event.stopPropagation();
            document.getElementById('add-testCase').click();
        }, false);
        ul.appendChild(add_case);

        var rename_suite = document.createElement("li");
        a = document.createElement("a");
        a.setAttribute("href", "#");
        a.innerHTML = "Rename Test Suite";
        rename_suite.appendChild(a);
        rename_suite.addEventListener("click", function(event) {
            event.stopPropagation();
            var s_suite = getSelectedSuite();
            var n_title = prompt("Please enter the Test Suite's title", sideex_testSuite[s_suite.id].title);
            // get text node
            s_suite.childNodes[0].textContent = n_title;
            sideex_testSuite[s_suite.id].title = n_title;
            $(s_suite).find("strong").addClass("modified");
            closeConfirm(true);
        }, false);
        ul.appendChild(rename_suite);
    }

    node.appendChild(ul);
}

function addTestCase(title, id) {
    if (!getSelectedSuite()) {
        var suite_id = "suite" + sideex_testSuite.count;
        sideex_testSuite.count++;
        sideex_testSuite[suite_id] = {
            file_name: "Untitled Test Suite.html",
            title: "Untitled Test Suite"
        };
        addTestSuite("Untitled Test Suite", suite_id);
    }

    var p = document.createElement("p");
    p.innerHTML = escapeHTML(title);
    p.setAttribute("id", id);
    p.setAttribute("contextmenu", "menu" + id);

    var s_case = getSelectedCase();
    if (s_case) {
        s_case.parentNode.insertBefore(p, s_case.nextSibling);
    } else {
        getSelectedSuite().appendChild(p);
    }

    cleanSelected();
    p.classList.add("selectedCase");
    p.parentNode.classList.add("selectedSuite");

    if (sideex_testCase[id]) { // load file
        clean_panel();
        document.getElementById("records-grid").innerHTML = escapeHTML(sideex_testCase[id].records);
        if (sideex_testCase[id].records) {
            reAssignId("records-1", "records-" + getRecordsNum());
            attachEvent(1, getRecordsNum());
        }
    } else { // add new testCase
        clean_panel();
        document.getElementById("records-grid").innerHTML = escapeHTML('<input id="records-count" type=hidden value=0></input>');
        sideex_testCase[id] = {
            records: "",
            title: title
        };
        p.classList.add("modified");
        p.parentNode.getElementsByTagName("strong")[0].classList.add("modified");
    }

    // attach event
    p.addEventListener("click", function(event) {
        event.stopPropagation();
        saveOldCase();
        // use jquery's API to add and remove class property
        cleanSelected();
        this.classList.add("selectedCase");
        this.parentNode.classList.add("selectedSuite");
        if (sideex_testCase[this.id].records) {
            clean_panel();
            document.getElementById("records-grid").innerHTML = escapeHTML(sideex_testCase[this.id].records);
            reAssignId("records-1", "records-" + getRecordsNum());
            attachEvent(1, getRecordsNum());
        } else {
            clean_panel();
            document.getElementById("records-grid").innerHTML = escapeHTML('<input id="records-count" type=hidden value=0></input>');
        }
        // prevent event trigger on parent from child
        event.stopPropagation();
    }, false);

    var menu = document.createElement("div");
    menu.setAttribute("class", "menu");
    menu.setAttribute("id", "menu" + id);
    appendContextMenu(menu, true);
    p.appendChild(menu);

    // right click
    p.addEventListener("contextmenu", function(event) {
        event.preventDefault();
        event.stopPropagation();
        saveOldCase();
        setSelectedCase(this.id);
        var mid = "#" + "menu" + id;
        console.log($(mid));
        $(".menu").css("left", event.pageX);
        $(".menu").css("top", event.pageY);
        $(mid).show();
    }, false);

    closeConfirm(true);
}

function addTestSuite(title, id) {
    var text = document.createElement("strong");
    text.innerHTML = escapeHTML(title);
    var div = document.createElement("div");
    div.setAttribute("id", id);
    div.setAttribute("contextmenu", "menu" + id);
    div.setAttribute("class", "message");
    div.appendChild(text);

    var s_suite = getSelectedSuite();
    if (s_suite) {
        s_suite.parentNode.insertBefore(div, s_suite.nextSibling);
    } else {
        document.getElementById("testCase-grid").appendChild(div);
    }

    cleanSelected();
    div.classList.add("selectedSuite");
    // attach event
    div.addEventListener("click", function(event) {
        if (this.getElementsByTagName("p").length != 0) {
            this.getElementsByTagName("p")[0].click();
        } else {
            event.stopPropagation();
            saveOldCase();
            cleanSelected();
            this.classList.add("selectedSuite");
            clean_panel();
            // document.getElementById("records-grid").innerHTML = "";
        }
    }, false);

    var menu = document.createElement("div");
    menu.setAttribute("class", "menu");
    menu.setAttribute("id", "menu" + id);
    appendContextMenu(menu, false);
    div.appendChild(menu);

    // right click
    div.addEventListener("contextmenu", function(event) {
        event.preventDefault();
        event.stopPropagation();
        saveOldCase();
        setSelectedSuite(this.id);
        var mid = "#" + "menu" + id;
        console.log($(mid));
        $(".menu").css("left", event.pageX);
        $(".menu").css("top", event.pageY);
        $(mid).show();
    }, false);

    makeCaseSortable(div);
}

document.getElementById("add-testSuite").addEventListener("click", function(event) {
    event.stopPropagation();
    var title = prompt("Please enter the Test Suite's title", "Untitled Test Suite");
    if (title) {
        var id = "suite" + sideex_testSuite.count;
        sideex_testSuite.count++;
        sideex_testSuite[id] = {
            file_name: title + ".html",
            title: title
        };
        addTestSuite(title, id);
    }
}, false);

document.getElementById("add-testSuite-menu").addEventListener("click", function(event) {
    event.stopPropagation();
    document.getElementById('add-testSuite').click();
}, false);

var confirmCloseSuite = function(question) {
    var defer = $.Deferred();
    $('

')
        .html(question)
        .dialog({
            title: "Save?",
            resizable: false,
            height: "auto",
            width: 400,
            modal: true,
            buttons: {
                "Yes": function() {
                    defer.resolve("true");
                    $(this).dialog("close");
                },
                "No": function() {
                    defer.resolve("false");
                    $(this).dialog("close");
                },
                Cancel: function() {
                    $(this).dialog("close");
                }
            },
            close: function() {
                $(this).remove();
            }
        });
    return defer.promise();
};

var remove_testSuite = function() {
    var s_suite = getSelectedSuite();
    sideex_testSuite[s_suite.id] = null;
    s_suite.parentNode.removeChild(s_suite);
    clean_panel();
};

document.getElementById("close-testSuite").addEventListener('click', function(event) {
    event.stopPropagation();
    var s_suite = getSelectedSuite();
    if (s_suite) {
        if ($(s_suite).find(".modified").length) {
            confirmCloseSuite("Would you like to save this test suite?").then(function(answer) {
                if (answer === "true")
                    downloadSuite(s_suite, remove_testSuite);
                else
                    remove_testSuite(s_suite);
            });
        } else {
            remove_testSuite(s_suite);
        }
        // document.getElementById("records-grid").innerHTML = "";
    }
}, false);

document.getElementById("add-testCase").addEventListener("click", function(event) {
    var title = prompt("Please enter the Test Case's title", "Untitled Test Case");
    if (title) {
        var id = "case" + sideex_testCase.count;
        sideex_testCase.count++;
        addTestCase(title, id);
    }
}, false);

var remove_testCase = function() {
    var s_case = getSelectedCase();
    sideex_testCase[s_case.id] = null;
    s_case.parentNode.removeChild(s_case);
    clean_panel();
};

document.getElementById("delete-testCase").addEventListener('click', function() {
    var s_case = getSelectedCase();
    console.log(s_case);
    if (s_case) {
        if ($(s_case).hasClass("modified")) {
            confirmCloseSuite("Would you like to save this test case?").then(function(answer) {
                if (answer === "true")
                    downloadSuite(getSelectedSuite(), remove_testCase);
                else
                    remove_testCase();
            });
        } else {
            remove_testCase();
        }
        // document.getElementById("records-grid").innerHTML = "";
    }
}, false);
<|endoftext|>


<commit_before>/* maximum number of results per page */
var MAX_PAGE_SIZE = 4

/* global pagination structure */
window.pagination =
{
    results : null,
    pages : 1,
    page : {},
    currentPage : 1
}

/* hide results and pagination containers at page load */
$('#pagination-container').hide();
$('#results-container').hide();
$('#input-search').focus();

/* override default behaviour of when 'Enter'
 * key pressed. Makes search request instead. */
$('.input').keypress(function(event)
{
    if (event.which == 13)
    {
       event.preventDefault();
       $('#btn-submit').click();
    }
});

$(document).keydown(function(event)
{
    if (!$('*:focus').is($('#input-search'))) {

        // right arrow
        if (event.which == 39)
        {
            event.preventDefault();
            $('#next').click();
        }

        // left arrow
        if (event.which == 37)
        {
            event.preventDefault();
            $('#previous').click();
        }
    }
});

/* when search/submit button clicked query terms
 * are stored and a search request is sent */
$('#btn-submit').click(function(event)
{
    event.preventDefault();
    var query_terms = $('#input-search').val();
    searchRequest(query_terms);
});

/* sends an AJAX GET request to Django's search
 * view, paginating results on success.*/
function searchRequest(query_terms)
{
    $.ajax
    ({
        type: "GET",
        url: "/search/",
        data: {'q' : query_terms},
        success: paginateResults
    });
}

/* divides up the result list into pages
 * and returns the first page */
function paginateResults(data)
{
    // store search results
    var results = data["results"];

    // store results in pagination namespace
    window.pagination.results = results;

    // use integer division to determine minimum number of pages
    var pages = ~~(results.length / MAX_PAGE_SIZE);

    // store minimum number of pages in namespace
    window.pagination.pages = pages;

    // if 0 then need at least one page
    if (pages == 0) {
        window.pagination.pages = 1
    }

    // add extra page for remainder results
    if (results.length % MAX_PAGE_SIZE != 0) {
        if (results.length > 5) {
            window.pagination.pages += 1;
        }
    }

    // populate page lookup hash
    var start = 0,
          end = MAX_PAGE_SIZE;

    for (var i=0; i<window.pagination.pages; i++) {
        window.pagination.page[i+1] = results.slice(start, end);
        start += MAX_PAGE_SIZE;
        end += MAX_PAGE_SIZE;
    }

    // display first page
    displayResults(window.pagination.page[1]);
}

/* writes results to the appropriate results
 * div.*/
function displayResults(results)
{
    // set pagination status
    $('#pagination-middle').html(window.pagination.currentPage + " of " + window.pagination.pages);

    clearResults();

    var resultDiv = $('#result-list');

    if (results.length == 0) {

        $('#pagination-container').hide();

        $('<span/>', {
            id: 'no-results',
            text: 'No results found.'
        }).appendTo(resultDiv);
    }

    // cache current page
    var currentPage = window.pagination.currentPage;

    // append results to div, with page derived index
    var index = (currentPage * MAX_PAGE_SIZE) - (MAX_PAGE_SIZE - 1);

    // page derived index attribute assignment
    resultDiv.attr('start', index);

    // add results to div
    for (var i=0; i<results.length; i++) {
        resultDiv.append(createSpannedResult(results[i])).fadeIn("slow");
    }

    $('#input-search').blur();
}

function createSpannedResult(result)
{
    var listElement = $('<li/>');

    // result title
    $('<span/>', {
        class: 'result-title',
        text: result['title']
    }).appendTo(listElement);

    // result description
    $('<span/>', {
        class: 'result-desc',
        text: result['summary']
    }).appendTo(listElement);

    $('<a />', {
        href: result['url'],
        text: result['url']
    }).appendTo(
        $('<span/>', {
            class: 'result-url'
        }).appendTo(listElement));

    return listElement
}

/* clears results from results div and hides it. */
function clearResults()
{
    $('#result-list').empty().hide();
    $('#pagination-container').show();
    $('#results-container').show();
}

/* handler for '<<' pagination button */
$('#first').click(function(event)
{
    window.pagination.currentPage = 1;
    displayResults(window.pagination.page[1]);
});

/* handler for '<' pagination button */
$('#previous').click(function(event)
{
    var currentPage = window.pagination.currentPage;
    if (currentPage > 1) {
        currentPage -= 1;
        window.pagination.currentPage = currentPage;
        displayResults(window.pagination.page[currentPage]);
    }
});

/* handler for '>' pagination button */
$('#next').click(function(event)
{
    var currentPage = window.pagination.currentPage;
    if (currentPage < window.pagination.pages) {
        currentPage += 1;
        window.pagination.currentPage = currentPage;
        displayResults(window.pagination.page[currentPage]);
    }
});

/* handler for '<' pagination button */
$('#last').click(function(event)
{
    var final_page = window.pagination.pages;
    window.pagination.currentPage = final_page;
    displayResults(window.pagination.page[final_page]);
});<commit_msg>essentials are working<commit_after>////////////////////////////////
// String formatting function //
////////////////////////////////

String.prototype.format = function() {
  var args = arguments;
  return this.replace(/{(\d+)}/g, function(match, number) {
    return typeof args[number] != 'undefined'
      ? args[number]
      : match
    ;
  });
};

////////////////////////
// Pagination Globals //
////////////////////////

// global pagination vars
window.pagination =
{
    maxPageSize: 4,             // max results per page
    results : null,             // list of results
    pages : 1,                  // how many pages there are
    page : {},                  // page lookup map
    currentPage : 1             // current page
};

///////////////////
// Cached JQuery //
///////////////////

var paginationContainer = $('#pagination-container');
var resultsContainer = $('#results-container');
var searchInput = $('#search-input');

// hide pagination, results and focus search input
paginationContainer.hide();
resultsContainer.hide();
searchInput.focus();

// override LEFT and RIGHT arrow keys and map to pagination buttons
$(document).keydown(function(event)
{

    if (event.which == 13)
    {
       event.preventDefault();
       $('#search-btn').click();
    }

    if (!$('*:focus').is(searchInput)) {

        // right arrow
        if (event.which == 39)
        {
            event.preventDefault();
            $('#next-btn').click();
        }

        // left arrow
        if (event.which == 37)
        {
            event.preventDefault();
            $('#previous-btn').click();
        }
    }
});

// query terms stored and a search request is sent
$('#search-btn').click(function(event)
{
    event.preventDefault();
    var query_terms = searchInput.val();
    searchRequest(query_terms);
});

// sends an AJAX GET request to searchlab, paginating results on success
function searchRequest(query_terms)
{
    $.ajax
    ({
        type: "GET",
        url: "/search/",
        data: {'q' : query_terms},
        success: paginateResults
    });
}

// calculates and initialises pagination, passing first page to be displayed
function paginateResults(data)
{
    // store search results
    var results = data["results"];
    window.pagination.results = results;

    var maxPageSize = window.pagination.maxPageSize;

    // store minimum number of pages in namespace
    var pages = ~~(results.length / maxPageSize);
    window.pagination.pages = pages;

    // if 0 then need at least one page
    if (pages == 0) {
        window.pagination.pages = 1
    }

    // add extra page for remainder results
    if (results.length % maxPageSize != 0) {
        if (results.length > 5) {
            window.pagination.pages += 1;
        }
    }

    // populate page lookup hash
    var start = 0,
          end = maxPageSize;

    for (var i=0; i<window.pagination.pages; i++) {
        window.pagination.page[i+1] = results.slice(start, end);
        start += maxPageSize;
        end += maxPageSize;
    }

    // display first page
    displayResults(window.pagination.page[1]);
}

// displays single page
function displayResults(results)
{
    // clear previous results
    resultsContainer.hide().empty();

    // set pagination status
    $('#page-btn').html(window.pagination.currentPage + " of " + window.pagination.pages);

    if (results.length == 0) {

        $('<span/>', {
            id: 'no-results',
            text: 'No results found.'
        }).appendTo(resultsContainer);
    }

    // cache current page
    var currentPage = window.pagination.currentPage;
    var maxPageSize = window.pagination.maxPageSize;

    // append results to div, with page derived index
    var index = (currentPage * maxPageSize) - (maxPageSize - 1);

    // page derived index attribute assignment
    resultsContainer.attr('start', index);

    var resultHTML = $('#result-template').html();

    // add results to div
    for (var i=0; i<results.length; i++) {

        var title = results[i]['title'];
        var summary = results[i]['summary'];
        var url = results[i]['url'];

        resultsContainer.append(resultHTML.format(title, url, summary)).fadeIn("slow");
        paginationContainer.fadeIn("slow");
    }

    searchInput.blur();
}

/* handler for '<<' pagination button */
$('#first-btn').click(function(event)
{
    window.pagination.currentPage = 1;
    displayResults(window.pagination.page[1]);
});

/* handler for '<' pagination button */
$('#previous-btn').click(function(event)
{
    var currentPage = window.pagination.currentPage;
    if (currentPage > 1) {
        currentPage -= 1;
        window.pagination.currentPage = currentPage;
        displayResults(window.pagination.page[currentPage]);
    }
});

/* handler for '>' pagination button */
$('#next-btn').click(function(event)
{
    var currentPage = window.pagination.currentPage;
    if (currentPage < window.pagination.pages) {
        currentPage += 1;
        window.pagination.currentPage = currentPage;
        displayResults(window.pagination.page[currentPage]);
    }
});

/* handler for '<' pagination button */
$('#last-btn').click(function(event)
{
    var final_page = window.pagination.pages;
    window.pagination.currentPage = final_page;
    displayResults(window.pagination.page[final_page]);
});
<|endoftext|>