<commit_before>"use strict";

var ObjectId = require("mongodb").ObjectId;
require("mongodb-toolkit");
var generateCode = require("../../../utils/code-generator");

var BuyerManager = require('../../master/buyer-manager');
var StorageManager = require('../../master/storage-manager');
var InventoryDocumentManager = require('../inventory-document-manager');
var InventorySummaryManager = require('../inventory-summary-manager');

var Models = require("dl-models");
var Map = Models.map;
var FpShipmentDocumentModel = Models.inventory.finishingPrinting.FPShipmentDocument;

var BaseManager = require("module-toolkit").BaseManager;
var i18n = require("dl-i18n");
var moment = require("moment");

module.exports = class FPPackingShipmentDocumentManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(Map.inventory.finishingPrinting.collection.FPPackingShipmentDocument);

        this.buyerManager = new BuyerManager(db, user);
        this.storageManager = new StorageManager(db, user);
        this.inventoryDocumentManager = new InventoryDocumentManager(db, user);
        this.inventorySummaryManager = new InventorySummaryManager(db, user);
    }

    _getQuery(paging) {
        var _default = {
            _deleted: false
        },
            pagingFilter = paging.filter || {},
            keywordFilter = {},
            query = {};

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");
            var codeFilter = {
                "code": {
                    "$regex": regex
                }
            };
            var createdDateFilter = {
                "_createdDate": {
                    "$regex": regex
                }
            };
            var shipmentNumberFilter = {
                "shipmentNumber": {
                    "$regex": regex
                }
            };
            var deliveryCodeFilter = {
                "deliveryCode": {
                    "$regex": regex
                }
            };
            var productIdentityFilter = {
                "productIdentity": {
                    "$regex": regex
                }
            };
            var buyerFilter = {
                "buyerName": {
                    "$regex": regex
                }
            };
            var buyerCodeFilter = {
                "buyerCode": {
                    "$regex": regex
                }
            };
            var createdByFilter = {
                "_createdBy": {
                    "$regex": regex
                }
            };
            keywordFilter["$or"] = [codeFilter, createdDateFilter, shipmentNumberFilter, deliveryCodeFilter, productIdentityFilter, buyerFilter, buyerCodeFilter, createdByFilter];
        }
        query["$and"] = [_default, keywordFilter, pagingFilter];
        return query;
    }

    _beforeInsert(data) {
        data.code = generateCode();
        return Promise.resolve(data);
    }

    _validate(data) {

        var errors = {};
        var valid = data;

        // valid.details = valid.details instanceof Array ? valid.details : [];
        // var items = valid.details.map((detail) => detail.items ? detail.items : null);

        var getDbShipmentDocument = this.collection.singleOrDefault({
            _id: new ObjectId(valid._id)
        });

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

        valid.details = valid.details || [];

        var products = [];

        for (var detail of valid.details) {
            for (var item of detail.items) {
                products.push(item.productCode);
            }
        }

        var getBuyer = valid.buyerId && ObjectId.isValid(valid.buyerId) ? this.buyerManager.getSingleByIdOrDefault(valid.buyerId) : Promise.resolve(null);

        var getStorage = valid.details ? this.storageManager.collection.find({ name: "Gudang Jadi Finishing Printing" }).toArray() : Promise.resolve([]);

        var getInventorySummary = products.length != 0 ? this.inventorySummaryManager.collection.find({ "productCode": { "$in": products }, "quantity": { "$gt": 0 }, storageName: "Gudang Jadi Finishing Printing" }, { "productCode": 1, "quantity": 1, "uom": 1 }).toArray() : Promise.resolve([]);

        return Promise.all([getDbShipmentDocument, getDuplicateShipmentDocument, getBuyer, getStorage, getInventorySummary])
            .then((results) => {
                var _dbShipmentDocument = results[0];
                var _duplicateShipmentDocument = results[1];
                var _buyer = results[2];
                var _storages = results[3];
                var _products = results[4];

                if (_dbShipmentDocument)
                    valid.code = _dbShipmentDocument.code; // prevent code changes.

                if (_duplicateShipmentDocument)
                    errors["code"] = i18n.__("ShipmentDocument.code.isExist: %s is exist", i18n.__("ShipmentDocument.code._:Code"));

                if (!valid.buyerId || valid.buyerId === '')
                    errors["buyerId"] = i18n.__("ShipmentDocument.buyerId.isExists:%s is not exists", i18n.__("ShipmentDocument.buyerId._:Buyer")); //"Buyer harus diisi";
                else if (!_buyer)
                    errors["buyerId"] = i18n.__("ShipmentDocument.buyerId.isRequired: %s not found", i18n.__("ShipmentDocument.buyerId._:Buyer"));

                if (!valid.shipmentNumber || valid.shipmentNumber === "")
                    errors["shipmentNumber"] = i18n.__("ShipmentDocument.shipmentNumber.isRequired:%s is required", i18n.__("ShipmentDocument.shipmentNumber._:NO."));

                if (!valid.productIdentity || valid.productIdentity === "")
                    errors["productIdentity"] = i18n.__("ShipmentDocument.productIdentity.isRequired:%s is required", i18n.__("ShipmentDocument.productIdentity._:Kode Produk"));

                if (!valid.deliveryCode || valid.deliveryCode === "")
                    errors["deliveryCode"] = i18n.__("ShipmentDocument.deliveryCode.isRequired:%s is required", i18n.__("ShipmentDocument.deliveryCode._:DO No"));

                if (valid.details.length > 0) {
                    var detailErrors = [];
                    for (var i = 0; i < valid.details.length; i++) {
                        var detailError = {};
                        if (!valid.details[i].productionOrderId || !valid.details[i].productionOrderId === "") {
                            detailError["productionOrderId"] = i18n.__("PackingReceipt.details.productionOrderId.isRequired:%s is required", i18n.__("PackingReceipt.details.productionOrderId._:Nomor Order")); //"Nomor order harus diisi";
                        }
                        if (!valid.details[i].items || valid.details[i].items.length === 0) {
                            detailError["productionOrderNo"] = i18n.__("PackingReceipt.details.productionOrderNo.isRequired:%s is required", i18n.__("PackingReceipt.details.productionOrderNo._:Nomor Order")); //"Harus ada item";
                        }
                        else {
                            var itemErrors = [];
                            var items = valid.details[i].items;

                            for (var j = 0; j < items.length; j++) {
                                var itemError = {};

                                var productInvSummary = _products.find(p => p.productCode === items[j].productCode && p.uom === items[j].uomUnit);

                                if (!items[j].quantity || items[j].quantity <= 0) {
                                    itemError["quantity"] = i18n.__("PackingReceipt.details.items.quantity.mustBeGreater:%s must be greater than zero", i18n.__("PackingReceipt.details.items.quantity._:Quantity")); //"Kuantitas harus lebih besar dari 0";
                                }
                                else if(items[j].quantity > productInvSummary.quantity) {
                                    itemError["quantity"] = i18n.__("PackingReceipt.details.items.quantity.mustBeLessEqual:%s must be less than or equal to stock", i18n.__("PackingReceipt.details.items.quantity._:Quantity")); //"Kuantitas harus lebih kecil atau sama dengan stock";
                                }

                                itemErrors.push(itemError);
                            }

                            for (var itemError of itemErrors) {
                                if (Object.getOwnPropertyNames(itemError).length > 0) {
                                    detailError.items = itemErrors;
                                    break;
                                }
                            }
                        }

                        detailErrors.push(detailError);
                    }

                    for (var detailError of detailErrors) {
                        if (Object.getOwnPropertyNames(detailError).length > 0) {
                            errors.details = detailErrors;
                            break;
                        }
                    }
                }

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

                //Inventory Document Validation
                valid.storageId = _storages.length > 0 ? new ObjectId(_storages[0]._id) : null;
                valid.storageName = _storages[0].name;
                valid.storageReferenceType = "Pengiriman Barang Gudang Jadi";
                valid.storageType = "OUT";

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

                valid.stamp(this.user.username, "manager");
                return Promise.resolve(valid);
            })
    }

    _createIndexes() {
        var dateIndex = {
            name: `ix_${Map.inventory.finishingPrinting.collection.FPPackingShipmentDocument}__updatedDate`,
            key: {
                _updatedDate: -1
            }
        }
        var codeIndex = {
            name: `ix_${Map.inventory.finishingPrinting.collection.FPPackingShipmentDocument}_code`,
            key: {
                code: 1
            },
            unique: true
        };

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

    _afterInsert(id) {
        var fpShipmentDocumentId = id;
        return this.getSingleById(id)
            .then((fpShipmentDocument) => {
                var fpShipmentDocument = fpShipmentDocument;
                var insertItems = fpShipmentDocument.details.map((detail) => {
                    var data = {
                        date: fpShipmentDocument._createdDate,
                        referenceNo: `RFNO-${fpShipmentDocument.code}`,
                        referenceType: fpShipmentDocument.storageReferenceType,
                        type: fpShipmentDocument.storageType,
                        storageId: fpShipmentDocument.storageId,
                        storageName: fpShipmentDocument.storageName,
                        items: detail.items
                    }
                    return this.inventoryDocumentManager.create(data)
                })
                return Promise.all(insertItems)
                    .then((result) => Promise.resolve(fpShipmentDocumentId))
            })
    }

    _afterUpdate(id) {
        var fpShipmentDocumentId = id;
        return this.getSingleById(id)
            .then((fpShipmentDocument) => {
                var fpShipmentDocument = fpShipmentDocument;
                var insertItems = fpShipmentDocument.details.map((detail) => {
                    var data = {
                        date: new Date(),
                        referenceNo: `RFNO-${fpShipmentDocument.code}`,
                        referenceType: fpShipmentDocument.storageReferenceType,
                        type: "IN",
                        storageId: fpShipmentDocument.storageId,
                        storageName: fpShipmentDocument.storageName,
                        items: detail.items
                    }
                    return this.inventoryDocumentManager.create(data)
                })
                return Promise.all(insertItems)
                    .then((result) => Promise.resolve(fpShipmentDocumentId))
            })
    }

    getPdf(data) {
        return new Promise((resolve, reject) => {
            var getDefinition = require("../../../pdf/definitions/fp-shipment-document");
            var definition = getDefinition(data);

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

    getShipmentReport(info) {
        var _defaultFilter = {
            _deleted: false,
            isVoid: false
        };
        var shipmentNumberFilter = {};
        var deliveryCodeFilter = {};
        var productIdentityFilter = {};
        var buyerFilter = {};
        var productionOrderFilter = {};
        var dateFromFilter = {};
        var dateToFilter = {};
        var query = {};

        var dateFrom = info.dateFrom ? (new Date(info.dateFrom)) : (new Date(1900, 1, 1));
        var dateTo = info.dateTo ? (new Date(info.dateTo + "T23:59")) : (new Date());
        var now = new Date();

        if (info.shipmentNumber && info.shipmentNumber != '') {
            shipmentNumberFilter = { "shipmentNumber": info.shipmentNumber };
        }

        if (info.deliveryCode && info.deliveryCode != '') {
            deliveryCodeFilter = { "deliveryCode": info.deliveryCode };
        }

        if (info.productIdentity && info.productIdentity != '') {
            productIdentityFilter = { "productIdentity": info.productIdentity };
        }

        if (info.buyerId && info.buyerId != '') {
            buyerFilter = { "buyerId": new ObjectId(info.buyerId) };
        }

        if (info.productionOrderNo && info.productionOrderNo != '') {
            productionOrderFilter = { "details.productionOrderNo": info.productionOrderNo };
        }

        var filterDate = {
            "_createdDate": {
                $gte: new Date(dateFrom),
                $lte: new Date(dateTo)
            }
        };

        query = { '$and': [_defaultFilter, shipmentNumberFilter, deliveryCodeFilter, productIdentityFilter, buyerFilter, productionOrderFilter, filterDate] };

        return this._createIndexes()
            .then((createIndexResults) => {
                return this.collection
                    .where(query)
                    .execute();
            });
    }

    getXls(result, query) {
        var xls = {};
        xls.data = [];
        xls.options = [];
        xls.name = '';

        var index = 0;
        var dateFormat = "DD/MM/YYYY";

        for (var shipment of result.data) {

            for (var detail of shipment.details) {

                for (var field of detail.items) {

                    var item = {};
                    index += 1;
                    item["No"] = index;
                    item["Tanggal"] = shipment._createdDate ? moment(new Date(shipment._createdDate)).format(dateFormat) : '';
                    item["Kode"] = shipment.code ? shipment.code : '';
                    item["Kode Pengiriman"] = shipment.shipmentNumber ? shipment.shipmentNumber : '';
                    item["Kode Delivery Order"] = shipment.deliveryCode ? shipment.deliveryCode : '';
                    item["Nomor Order"] = detail.productionOrderNo ? detail.productionOrderNo : '';
                    item["Buyer"] = shipment.buyerName ? shipment.buyerName : '';
                    item["Nama Barang"] = field.productName ? field.productName : '';
                    item["Satuan"] = field.uomUnit ? field.uomUnit : '';
                    item["Kuantiti Satuan"] = field.quantity ? field.quantity : 0;
                    item["Panjang Total"] = field.length ? (field.length * field.quantity).toFixed(2) : 0;
                    item["Berat Total"] = field.weight ? (field.weight * field.quantity).toFixed(2) : 0;

                    xls.options["No"] = "number";
                    xls.options["Tanggal"] = "string";
                    xls.options["Kode"] = "string";
                    xls.options["Kode Pengiriman"] = "string";
                    xls.options["Kode Delivery Order"] = "string";
                    xls.options["Nomor Order"] = "string";
                    xls.options["Buyer"] = "string";
                    xls.options["Nama Barang"] = "string";
                    xls.options["Satuan"] = "string";
                    xls.options["Kuantiti Satuan"] = "number";
                    xls.options["Panjang Total"] = "number";
                    xls.options["Berat Total"] = "number";

                    xls.data.push(item);

                }

            }

        }

        if (query.dateFrom && query.dateTo) {
            xls.name = `Shipment Document ${moment(new Date(query.dateFrom)).format(dateFormat)} - ${moment(new Date(query.dateTo)).format(dateFormat)}.xlsx`;
        }
        else if (!query.dateFrom && query.dateTo) {
            xls.name = `Shipment Document ${moment(new Date(query.dateTo)).format(dateFormat)}.xlsx`;
        }
        else if (query.dateFrom && !query.dateTo) {
            xls.name = `Shipment Document ${moment(new Date(query.dateFrom)).format(dateFormat)}.xlsx`;
        }
        else
            xls.name = `Shipment Document.xlsx`;

        return Promise.resolve(xls);
    }
};
<commit_msg>Update Shipment Document<commit_after>"use strict";

var ObjectId = require("mongodb").ObjectId;
require("mongodb-toolkit");
var generateCode = require("../../../utils/code-generator");

var BuyerManager = require('../../master/buyer-manager');
var StorageManager = require('../../master/storage-manager');
var InventoryDocumentManager = require('../inventory-document-manager');
var InventorySummaryManager = require('../inventory-summary-manager');

var Models = require("dl-models");
var Map = Models.map;
var FpShipmentDocumentModel = Models.inventory.finishingPrinting.FPShipmentDocument;

var BaseManager = require("module-toolkit").BaseManager;
var i18n = require("dl-i18n");
var moment = require("moment");

module.exports = class FPPackingShipmentDocumentManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(Map.inventory.finishingPrinting.collection.FPPackingShipmentDocument);

        this.buyerManager = new BuyerManager(db, user);
        this.storageManager = new StorageManager(db, user);
        this.inventoryDocumentManager = new InventoryDocumentManager(db, user);
        this.inventorySummaryManager = new InventorySummaryManager(db, user);
    }

    _getQuery(paging) {
        var _default = {
            _deleted: false
        },
            pagingFilter = paging.filter || {},
            keywordFilter = {},
            query = {};

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");
            var codeFilter = {
                "code": {
                    "$regex": regex
                }
            };
            var createdDateFilter = {
                "_createdDate": {
                    "$regex": regex
                }
            };
            var shipmentNumberFilter = {
                "shipmentNumber": {
                    "$regex": regex
                }
            };
            var deliveryCodeFilter = {
                "deliveryCode": {
                    "$regex": regex
                }
            };
            var productIdentityFilter = {
                "productIdentity": {
                    "$regex": regex
                }
            };
            var buyerFilter = {
                "buyerName": {
                    "$regex": regex
                }
            };
            var buyerCodeFilter = {
                "buyerCode": {
                    "$regex": regex
                }
            };
            var createdByFilter = {
                "_createdBy": {
                    "$regex": regex
                }
            };
            keywordFilter["$or"] = [codeFilter, createdDateFilter, shipmentNumberFilter, deliveryCodeFilter, productIdentityFilter, buyerFilter, buyerCodeFilter, createdByFilter];
        }
        query["$and"] = [_default, keywordFilter, pagingFilter];
        return query;
    }

    _beforeInsert(data) {
        data.code = generateCode();
        return Promise.resolve(data);
    }

    _validate(data) {

        var errors = {};
        var valid = data;

        // valid.details = valid.details instanceof Array ? valid.details : [];
        // var items = valid.details.map((detail) => detail.items ? detail.items : null);

        var getDbShipmentDocument = this.collection.singleOrDefault({
            _id: new ObjectId(valid._id)
        });

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

        valid.details = valid.details || [];

        var products = [];

        for (var detail of valid.details) {
            for (var item of detail.items) {
                products.push(item.productCode);
            }
        }

        var getBuyer = valid.buyerId && ObjectId.isValid(valid.buyerId) ? this.buyerManager.getSingleByIdOrDefault(valid.buyerId) : Promise.resolve(null);

        var getStorage = valid.details ? this.storageManager.collection.find({ name: "Gudang Jadi Finishing Printing" }).toArray() : Promise.resolve([]);

        var getInventorySummary = products.length != 0 ? this.inventorySummaryManager.collection.find({ "productCode": { "$in": products }, "quantity": { "$gt": 0 }, storageName: "Gudang Jadi Finishing Printing" }, { "productCode": 1, "quantity": 1, "uom": 1 }).toArray() : Promise.resolve([]);

        return Promise.all([getDbShipmentDocument, getDuplicateShipmentDocument, getBuyer, getStorage, getInventorySummary])
            .then((results) => {
                var _dbShipmentDocument = results[0];
                var _duplicateShipmentDocument = results[1];
                var _buyer = results[2];
                var _storages = results[3];
                var _products = results[4];

                if (_dbShipmentDocument)
                    valid.code = _dbShipmentDocument.code; // prevent code changes.

                if (_duplicateShipmentDocument)
                    errors["code"] = i18n.__("ShipmentDocument.code.isExist: %s is exist", i18n.__("ShipmentDocument.code._:Code"));

                if (!valid.buyerId || valid.buyerId === '')
                    errors["buyerId"] = i18n.__("ShipmentDocument.buyerId.isExists:%s is not exists", i18n.__("ShipmentDocument.buyerId._:Buyer")); //"Buyer harus diisi";
                else if (!_buyer)
                    errors["buyerId"] = i18n.__("ShipmentDocument.buyerId.isRequired: %s not found", i18n.__("ShipmentDocument.buyerId._:Buyer"));

                if (!valid.shipmentNumber || valid.shipmentNumber === "")
                    errors["shipmentNumber"] = i18n.__("ShipmentDocument.shipmentNumber.isRequired:%s is required", i18n.__("ShipmentDocument.shipmentNumber._:NO."));

                if (!valid.productIdentity || valid.productIdentity === "")
                    errors["productIdentity"] = i18n.__("ShipmentDocument.productIdentity.isRequired:%s is required", i18n.__("ShipmentDocument.productIdentity._:Kode Produk"));

                if (!valid.deliveryCode || valid.deliveryCode === "")
                    errors["deliveryCode"] = i18n.__("ShipmentDocument.deliveryCode.isRequired:%s is required", i18n.__("ShipmentDocument.deliveryCode._:DO No"));

                if (valid.details.length > 0) {
                    var detailErrors = [];
                    for (var i = 0; i < valid.details.length; i++) {
                        var detailError = {};
                        if (!valid.details[i].productionOrderId || !valid.details[i].productionOrderId === "") {
                            detailError["productionOrderId"] = i18n.__("PackingReceipt.details.productionOrderId.isRequired:%s is required", i18n.__("PackingReceipt.details.productionOrderId._:Nomor Order")); //"Nomor order harus diisi";
                        }
                        if (!valid.details[i].items || valid.details[i].items.length === 0) {
                            detailError["productionOrderNo"] = i18n.__("PackingReceipt.details.productionOrderNo.isRequired:%s is required", i18n.__("PackingReceipt.details.productionOrderNo._:Nomor Order")); //"Harus ada item";
                        }
                        else {
                            var itemErrors = [];
                            var items = valid.details[i].items;

                            for (var j = 0; j < items.length; j++) {
                                var itemError = {};

                                var productInvSummary = _products.find(p => p.productCode === items[j].productCode && p.uom === items[j].uomUnit);

                                if (!items[j].quantity || items[j].quantity <= 0) {
                                    itemError["quantity"] = i18n.__("PackingReceipt.details.items.quantity.mustBeGreater:%s must be greater than zero", i18n.__("PackingReceipt.details.items.quantity._:Quantity")); //"Kuantitas harus lebih besar dari 0";
                                }
                                else if(productInvSummary && (items[j].quantity > productInvSummary.quantity)) {
                                    itemError["quantity"] = i18n.__("PackingReceipt.details.items.quantity.mustBeLessEqual:%s must be less than or equal to stock", i18n.__("PackingReceipt.details.items.quantity._:Quantity")); //"Kuantitas harus lebih kecil atau sama dengan stock";
                                }

                                itemErrors.push(itemError);
                            }

                            for (var itemError of itemErrors) {
                                if (Object.getOwnPropertyNames(itemError).length > 0) {
                                    detailError.items = itemErrors;
                                    break;
                                }
                            }
                        }

                        detailErrors.push(detailError);
                    }

                    for (var detailError of detailErrors) {
                        if (Object.getOwnPropertyNames(detailError).length > 0) {
                            errors.details = detailErrors;
                            break;
                        }
                    }
                }

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

                //Inventory Document Validation
                valid.storageId = _storages.length > 0 ? new ObjectId(_storages[0]._id) : null;
                valid.storageName = _storages[0].name;
                valid.storageReferenceType = "Pengiriman Barang Gudang Jadi";
                valid.storageType = "OUT";

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

                valid.stamp(this.user.username, "manager");
                return Promise.resolve(valid);
            })
    }

    _createIndexes() {
        var dateIndex = {
            name: `ix_${Map.inventory.finishingPrinting.collection.FPPackingShipmentDocument}__updatedDate`,
            key: {
                _updatedDate: -1
            }
        }
        var codeIndex = {
            name: `ix_${Map.inventory.finishingPrinting.collection.FPPackingShipmentDocument}_code`,
            key: {
                code: 1
            },
            unique: true
        };

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

    _afterInsert(id) {
        var fpShipmentDocumentId = id;
        return this.getSingleById(id)
            .then((fpShipmentDocument) => {
                var fpShipmentDocument = fpShipmentDocument;
                var insertItems = fpShipmentDocument.details.map((detail) => {
                    var data = {
                        date: fpShipmentDocument._createdDate,
                        referenceNo: `RFNO-${fpShipmentDocument.code}`,
                        referenceType: fpShipmentDocument.storageReferenceType,
                        type: fpShipmentDocument.storageType,
                        storageId: fpShipmentDocument.storageId,
                        storageName: fpShipmentDocument.storageName,
                        items: detail.items
                    }
                    return this.inventoryDocumentManager.create(data)
                })
                return Promise.all(insertItems)
                    .then((result) => Promise.resolve(fpShipmentDocumentId))
            })
    }

    _afterUpdate(id) {
        var fpShipmentDocumentId = id;
        return this.getSingleById(id)
            .then((fpShipmentDocument) => {
                var fpShipmentDocument = fpShipmentDocument;
                var insertItems = fpShipmentDocument.details.map((detail) => {
                    var data = {
                        date: new Date(),
                        referenceNo: `RFNO-${fpShipmentDocument.code}`,
                        referenceType: fpShipmentDocument.storageReferenceType,
                        type: "IN",
                        storageId: fpShipmentDocument.storageId,
                        storageName: fpShipmentDocument.storageName,
                        items: detail.items
                    }
                    return this.inventoryDocumentManager.create(data)
                })
                return Promise.all(insertItems)
                    .then((result) => Promise.resolve(fpShipmentDocumentId))
            })
    }

    getPdf(data) {
        return new Promise((resolve, reject) => {
            var getDefinition = require("../../../pdf/definitions/fp-shipment-document");
            var definition = getDefinition(data);

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

    getShipmentReport(info) {
        var _defaultFilter = {
            _deleted: false,
            isVoid: false
        };
        var shipmentNumberFilter = {};
        var deliveryCodeFilter = {};
        var productIdentityFilter = {};
        var buyerFilter = {};
        var productionOrderFilter = {};
        var dateFromFilter = {};
        var dateToFilter = {};
        var query = {};

        var dateFrom = info.dateFrom ? (new Date(info.dateFrom)) : (new Date(1900, 1, 1));
        var dateTo = info.dateTo ? (new Date(info.dateTo + "T23:59")) : (new Date());
        var now = new Date();

        if (info.shipmentNumber && info.shipmentNumber != '') {
            shipmentNumberFilter = { "shipmentNumber": info.shipmentNumber };
        }

        if (info.deliveryCode && info.deliveryCode != '') {
            deliveryCodeFilter = { "deliveryCode": info.deliveryCode };
        }

        if (info.productIdentity && info.productIdentity != '') {
            productIdentityFilter = { "productIdentity": info.productIdentity };
        }

        if (info.buyerId && info.buyerId != '') {
            buyerFilter = { "buyerId": new ObjectId(info.buyerId) };
        }

        if (info.productionOrderNo && info.productionOrderNo != '') {
            productionOrderFilter = { "details.productionOrderNo": info.productionOrderNo };
        }

        var filterDate = {
            "_createdDate": {
                $gte: new Date(dateFrom),
                $lte: new Date(dateTo)
            }
        };

        query = { '$and': [_defaultFilter, shipmentNumberFilter, deliveryCodeFilter, productIdentityFilter, buyerFilter, productionOrderFilter, filterDate] };

        return this._createIndexes()
            .then((createIndexResults) => {
                return this.collection
                    .where(query)
                    .execute();
            });
    }

    getXls(result, query) {
        var xls = {};
        xls.data = [];
        xls.options = [];
        xls.name = '';

        var index = 0;
        var dateFormat = "DD/MM/YYYY";

        for (var shipment of result.data) {

            for (var detail of shipment.details) {

                for (var field of detail.items) {

                    var item = {};
                    index += 1;
                    item["No"] = index;
                    item["Tanggal"] = shipment._createdDate ? moment(new Date(shipment._createdDate)).format(dateFormat) : '';
                    item["Kode"] = shipment.code ? shipment.code : '';
                    item["Kode Pengiriman"] = shipment.shipmentNumber ? shipment.shipmentNumber : '';
                    item["Kode Delivery Order"] = shipment.deliveryCode ? shipment.deliveryCode : '';
                    item["Nomor Order"] = detail.productionOrderNo ? detail.productionOrderNo : '';
                    item["Buyer"] = shipment.buyerName ? shipment.buyerName : '';
                    item["Nama Barang"] = field.productName ? field.productName : '';
                    item["Satuan"] = field.uomUnit ? field.uomUnit : '';
                    item["Kuantiti Satuan"] = field.quantity ? field.quantity : 0;
                    item["Panjang Total"] = field.length ? (field.length * field.quantity).toFixed(2) : 0;
                    item["Berat Total"] = field.weight ? (field.weight * field.quantity).toFixed(2) : 0;

                    xls.options["No"] = "number";
                    xls.options["Tanggal"] = "string";
                    xls.options["Kode"] = "string";
                    xls.options["Kode Pengiriman"] = "string";
                    xls.options["Kode Delivery Order"] = "string";
                    xls.options["Nomor Order"] = "string";
                    xls.options["Buyer"] = "string";
                    xls.options["Nama Barang"] = "string";
                    xls.options["Satuan"] = "string";
                    xls.options["Kuantiti Satuan"] = "number";
                    xls.options["Panjang Total"] = "number";
                    xls.options["Berat Total"] = "number";

                    xls.data.push(item);

                }

            }

        }

        if (query.dateFrom && query.dateTo) {
            xls.name = `Shipment Document ${moment(new Date(query.dateFrom)).format(dateFormat)} - ${moment(new Date(query.dateTo)).format(dateFormat)}.xlsx`;
        }
        else if (!query.dateFrom && query.dateTo) {
            xls.name = `Shipment Document ${moment(new Date(query.dateTo)).format(dateFormat)}.xlsx`;
        }
        else if (query.dateFrom && !query.dateTo) {
            xls.name = `Shipment Document ${moment(new Date(query.dateFrom)).format(dateFormat)}.xlsx`;
        }
        else
            xls.name = `Shipment Document.xlsx`;

        return Promise.resolve(xls);
    }
};
<|endoftext|>


<commit_before>/**
  * author: Taynara Sene
  * github: taahsene

  * Compra Rapida (Home)- para loja Tray Commerce- Opencode

  * **Utilização**
  *
  * Faça a chamada do snippet de quantidade no snippet de Produtos
  * {% element 'snippets/qtd_home'{"product": product}  %}
  *
  * Adicione o Botão comprar
  * <button type="submit" class="comprar"data-app="product.buy-button" data-product ="{{ product.id }}" >  </button>
  */

  // Quantidade
  jQuery('[data-app="product.qty"]').on('click', function() {
    var $productId = jQuery(this).attr('data-product');
    var value = parseInt(jQuery('#qtd'+$productId).attr('value'));
    var option = jQuery(this).attr('data-action')== 'minus' ? -1 : 1

    value += option;
    if(value > 0)
      jQuery('#qtd'+$productId).attr('value',value);
  })

  //Comprar
  jQuery('[data-app="product.buy-button"]').on('click', function() {
    var $productId = jQuery(this).attr('data-product');
    var $dataSession = jQuery("html").attr("data-session");
    var $productQtd = parseInt(jQuery('#qtd'+$productId).attr('value'));
    var self = this;

    jQuery.ajax({
      method: "POST",
      url: "/web_api/cart/",
      contentType: "application/json; charset=utf-8",
      data: '{"Cart":{"session_id":"'+$dataSession+'","product_id":"'+$productId+'","quantity":'+$productQtd+'}}'
    }).done(function( response, textStatus, jqXHR ) {
      jQuery(self).text("Adicionado!")

      //Função para exibir a modal
      reloaderPreview(showModal);
    }).fail(function( jqXHR, status, errorThrown ){
      var response = jQuery.parseJSON( jqXHR.responseText );
      // Exibe a mensagem de erro (estoque insuficiente, etc)
      alert(response.causes[0])
    });
  })

  function reloaderPreview(callback) {
    //Renderiza novamente o componente de cart-preview
    store.render.init();
    setTimeout(function() {
      callback();
    }, 800);
  }

  // Dispara a modal
  function showModal() {
      jQuery('.cart-preview').modal('show');
  }
<commit_msg>fix Same products on the same page<commit_after>/**
  * author: Taynara Sene
  * github: taahsene

  * Compra Rapida (Home)- para loja Tray Commerce- Opencode

  * **Utilização**
  *
  * Faça a chamada do snippet de quantidade no snippet de Produtos
  * {% element 'snippets/qtd_home'{"product": product}  %}
  *
  * Adicione o Botão comprar
  * <button type="submit" class="comprar"data-app="product.buy-button" data-product ="{{ product.id }}" >  </button>
  */

  // Quantidade
  jQuery('[data-app="product.qty"]').on('click', function() {
    var $input = jQuery(this).parent().find('input')[0];
    var value = parseInt(jQuery($input).attr('value'));
    var option = jQuery(this).attr('data-action')== 'minus' ? -1 : 1

    value += option;
    if(value > 0)
      jQuery($input).attr('value',value);
  })

  //Comprar
  jQuery('[data-app="product.buy-button"]').on('click', function() {
    var $input = jQuery(this).parent().parent().find('input')[0];
    var $productId = jQuery(this).attr('data-product');
    var $dataSession = jQuery("html").attr("data-session");
    var $productQtd = parseInt(jQuery($input).attr('value'));
    var self = this;
    jQuery.ajax({
      method: "POST",
      url: "/web_api/cart/",
      contentType: "application/json; charset=utf-8",
      data: '{"Cart":{"session_id":"'+$dataSession+'","product_id":"'+$productId+'","quantity":'+$productQtd+'}}'
    }).done(function( response, textStatus, jqXHR ) {
      jQuery(self).text("Adicionado!")
      // alert("Produto Adicionado ao Carrinho!");

      //Função para exibir a modal
      reloaderPreview(showModal);
    }).fail(function( jqXHR, status, errorThrown ){
      var response = jQuery.parseJSON( jqXHR.responseText );
      // Exibe a mensagem de erro (estoque insuficiente, etc)
      alert(response.causes[0])
    });
  })

  function reloaderPreview(callback) {
    //Renderiza novamente o componente de cart-preview
    store.render.init();
    setTimeout(function() {
      callback();
    }, 800);
  }

  // Dispara a modal
  function showModal() {
      jQuery('.cart-preview').modal('show');
  }
<|endoftext|>


<commit_before>var seaport = require('../../');
var ports = seaport.createServer().listen(5001);

var bouncy = require('bouncy');
bouncy(function (req, bounce) {
    var domains = (req.headers.host || '').split('.');
    var ps = ports.query(domains.slice(0,-1).join('.'));

    if (ps.length === 0) {
        var res = bounce.respond();
        res.end('service not available\n');
    }
    else {
        bounce(ps[0].host, ps[0].port);
    }
}).listen(5000);
<commit_msg>better domains for the router example<commit_after>var seaport = require('../../');
var ports = seaport.createServer().listen(5001);

var bouncy = require('bouncy');
bouncy(function (req, bounce) {
    var domains = (req.headers.host || '').split('.');
    var service = 'http@' + ({
        unstable : '0.1.x',
        stable : '0.0.0',
    }[domains[0]] || '0.0.0');

    var ps = ports.query(service);

    if (ps.length === 0) {
        var res = bounce.respond();
        res.end('service not available\n');
    }
    else {
        bounce(ps[0].host, ps[0].port);
    }
}).listen(5000);
<|endoftext|>


<commit_before>// @flow

import React from 'react';
import _ from 'lodash';

import SearchIcon from 'react-icons/lib/fa/search';
import { compose, withState, branch, renderComponent } from 'recompose';
import { humanify } from '@ncigdc/utils/string';
import { makeFilter } from '@ncigdc/utils/filters';
import Card from '@ncigdc/uikit/Card';
import { Row, Column } from '@ncigdc/uikit/Flex';
import Input from '@ncigdc/uikit/Form/Input';
import EntityPageVerticalTable from '@ncigdc/components/EntityPageVerticalTable';
import Hidden from '@ncigdc/components/Hidden';
import DownloadButton from '@ncigdc/components/DownloadButton';
import { withTheme } from '@ncigdc/theme';
import { visualizingButton } from '@ncigdc/theme/mixins';
import Button from '@ncigdc/uikit/Button';
import Emitter from '@ncigdc/utils/emitter';
import BioTreeView from './BioTreeView';
import { search, idFields, formatValue } from './utils';
import ImageViewerLink from '@ncigdc/components/Links/ImageViewerLink';
import ShoppingCartIcon from '@ncigdc/theme/icons/ShoppingCart';
import DownloadIcon from '@ncigdc/theme/icons/Download';
import { iconButton } from '@ncigdc/theme/mixins';
import { Tooltip } from '@ncigdc/uikit/Tooltip';
import { MicroscopeIcon } from '@ncigdc/theme/icons';
import { entityTypes } from './';
import withRouter from '@ncigdc/utils/withRouter';
import { DISPLAY_SLIDES } from '@ncigdc/utils/constants';

const styles = {
  button: {
    color: '#333',
    backgroundColor: '#fff',
    borderColor: '#ccc',
    minWidth: '115px',
    minHeight: '34px',
    display: 'inline-flex',
    outline: 'none',
  },
  searchIcon: theme => ({
    backgroundColor: theme.greyScale5,
    color: theme.greyScale2,
    padding: '0.8rem',
    width: '3.4rem',
    height: '3.4rem',
    borderRadius: '4px 0 0 4px',
    border: `1px solid ${theme.greyScale4}`,
    borderRight: 'none',
  }),
};

const getType = node => entityTypes.find(type => node[`${type.s}_id`]).s;

export default compose(
  withRouter,
  branch(
    ({ viewer }) => !viewer.repository.cases.hits.edges[0],
    renderComponent(() =>
No case found.
),
  ),
  withState('allExpanded', 'setAllExpanded', false),
  withState('expandAllFirstClick', 'setExpandAllFirstClick', true),
  withState(
    'state',
    'setState',
    ({ viewer: { repository: { cases: { hits: { edges } } } }, bioId }) => {
      const p = edges[0].node;
      const selectedEntity = p.samples.hits.edges[0].node;
      return {
        selectedEntity,
        type: getType(selectedEntity),
        query: bioId || '',
      };
    },
  ),
  withTheme,
)(
  ({
    history,
    push,
    theme,
    viewer: { repository: { cases: { hits: { edges } } } },
    state: { selectedEntity: se, type, query },
    setState,
    setAllExpanded,
    allExpanded,
    expandAllFirstClick,
    setExpandAllFirstClick,
  }) => {
    const p = edges[0].node;

    const founds = p.samples.hits.edges.map(e => search(query, e));
    const flattened = _.flatten(founds);
    const foundNode = ((flattened || [])[0] || { node: {} }).node;
    const selectedNode = (query && foundNode) || se;
    const foundType = (query && getType(foundNode)) || type;
    const selectedEntity = Object.keys(selectedNode).length
      ? selectedNode
      : p.samples.hits.edges[0].node;

    return (
      <Card
        className="test-biospecimen-card"
        style={{ flex: 1 }}
        title={
          <Row style={{ justifyContent: 'space-between' }}>
            Biospecimen
            <DownloadButton
              className="test-download-biospecimen"
              style={visualizingButton}
              filename={`biospecimen.case-${p.case_id}`}
              endpoint="cases"
              activeText="Processing"
              inactiveText="Export"
              filters={makeFilter([
                { field: 'cases.case_id', value: p.case_id },
              ])}
              fields={['case_id']}
              dataExportExpands={[
                'samples',
                'samples.portions',
                'samples.portions.analytes',
                'samples.portions.analytes.aliquots',
                'samples.portions.analytes.aliquots.annotations',
                'samples.portions.analytes.annotations',
                'samples.portions.submitter_id',
                'samples.portions.slides',
                'samples.portions.annotations',
                'samples.portions.center',
              ]}
            />
          </Row>
        }
      >
        <Row>
          <Column flex="3" style={{ padding: '0 15px' }}>
            <Row style={{ justifyContent: 'space-between' }}>
              <Row style={{ width: '70%' }}>

                  <SearchIcon style={styles.searchIcon(theme)} />
                  <Hidden>Search</Hidden>

                <Input
                  id="search-biospecimen"
                  name="search-biospecimen"
                  onChange={({ target }) =>
                    setState(s => ({ ...s, query: target.value }))}
                  placeholder="Search"
                  value={query}
                  style={{ borderRadius: '0 4px 4px 0' }}
                />
              </Row>
              <Button
                style={{
                  paddingLeft: '10px',
                }}
                onClick={() => {
                  Emitter.emit('expand', !allExpanded);
                  setExpandAllFirstClick(false);
                  setAllExpanded(!allExpanded);
                }}
              >
                {allExpanded ? 'Collapse All' : 'Expand All'}
              </Button>
            </Row>

            <Column style={{ padding: '10px' }}>
              <BioTreeView
                entities={{ ...p.samples, expanded: expandAllFirstClick }}
                type={{ s: 'sample', p: 'samples' }}
                query={query}
                selectedEntity={selectedEntity}
                selectEntity={(selectedEntity, type) => {
                  setState(s => ({
                    ...s,
                    selectedEntity,
                    type: type.s,
                    query: '',
                  }));
                  push({
                    ...history.location,
                    query: {
                      ...history.location.query,
                      bioId: selectedEntity[`${type.s}_id`],
                    },
                  });
                }}
                defaultExpanded={allExpanded}
              />
            </Column>
          </Column>
          <Column flex="4">
            <EntityPageVerticalTable
              thToTd={[
                { th: `${foundType} ID`, td: selectedEntity.submitter_id },
                {
                  th: `${foundType} UUID`,
                  td: selectedEntity[idFields.find(id => selectedEntity[id])],
                },
                ...Object.entries(selectedEntity)
                  .filter(
                    ([key]) =>
                      ![
                        'submitter_id',
                        'expanded',
                        `${foundType}_id`,
                        '__dataID__',
                      ].includes(key),
                  )
                  .map(([key, val]) => {
                    if (
                      ['portions', 'aliquots', 'analytes', 'slides'].includes(
                        key,
                      )
                    ) {
                      return {
                        th: humanify({ term: key }),
                        td: formatValue(val.hits.total),
                      };
                    }
                    return {
                      th: humanify({ term: key }),
                      td: formatValue(val),
                    };
                  }),
                ...(DISPLAY_SLIDES &&
                  foundType === 'slide' && [
                    {
                      th: 'Slide Image',
                      td: (
                        <Row>
                          <Tooltip Component="View Slide Image">
                            <ImageViewerLink
                              isIcon
                              query={{
                                filters: makeFilter([
                                  { field: 'cases.case_id', value: p.case_id },
                                ]),
                                selectedId: `${selectedEntity.submitter_id}.${selectedEntity.slide_id}`,
                              }}
                            >
                              <MicroscopeIcon />
                            </ImageViewerLink>{' '}
                          </Tooltip>
                          <Tooltip Component="Add to cart">
                            <Button
                              className="test-toggle-cart"
                              leftIcon={<ShoppingCartIcon />}
                              style={{ ...iconButton, marginLeft: '0.5rem' }}
                              disabled
                            />
                          </Tooltip>
                          <Tooltip Component="Download">
                            <Button
                              className="test-toggle-cart"
                              style={{ ...iconButton, marginLeft: '0.5rem' }}
                              leftIcon={<DownloadIcon />}
                              disabled
                            />
                          </Tooltip>
                        </Row>
                      ),
                    },
                  ]),
              ]}
              style={{ flex: '1 1 auto' }}
            />
          </Column>
        </Row>
      </Card>
    );
  },
);
<commit_msg>🐛 PRTL-1954 null guard in biocard when no samples<commit_after>// @flow

import React from 'react';
import _ from 'lodash';

import SearchIcon from 'react-icons/lib/fa/search';
import { compose, withState, branch, renderComponent } from 'recompose';
import { humanify } from '@ncigdc/utils/string';
import { makeFilter } from '@ncigdc/utils/filters';
import Card from '@ncigdc/uikit/Card';
import { Row, Column } from '@ncigdc/uikit/Flex';
import Input from '@ncigdc/uikit/Form/Input';
import EntityPageVerticalTable from '@ncigdc/components/EntityPageVerticalTable';
import Hidden from '@ncigdc/components/Hidden';
import DownloadButton from '@ncigdc/components/DownloadButton';
import { withTheme } from '@ncigdc/theme';
import { visualizingButton } from '@ncigdc/theme/mixins';
import Button from '@ncigdc/uikit/Button';
import Emitter from '@ncigdc/utils/emitter';
import BioTreeView from './BioTreeView';
import { search, idFields, formatValue } from './utils';
import ImageViewerLink from '@ncigdc/components/Links/ImageViewerLink';
import ShoppingCartIcon from '@ncigdc/theme/icons/ShoppingCart';
import DownloadIcon from '@ncigdc/theme/icons/Download';
import { iconButton } from '@ncigdc/theme/mixins';
import { Tooltip } from '@ncigdc/uikit/Tooltip';
import { MicroscopeIcon } from '@ncigdc/theme/icons';
import { entityTypes } from './';
import withRouter from '@ncigdc/utils/withRouter';
import { DISPLAY_SLIDES } from '@ncigdc/utils/constants';

const styles = {
  button: {
    color: '#333',
    backgroundColor: '#fff',
    borderColor: '#ccc',
    minWidth: '115px',
    minHeight: '34px',
    display: 'inline-flex',
    outline: 'none',
  },
  searchIcon: theme => ({
    backgroundColor: theme.greyScale5,
    color: theme.greyScale2,
    padding: '0.8rem',
    width: '3.4rem',
    height: '3.4rem',
    borderRadius: '4px 0 0 4px',
    border: `1px solid ${theme.greyScale4}`,
    borderRight: 'none',
  }),
};

const getType = node => entityTypes.find(type => node[`${type.s}_id`]).s;

export default compose(
  withRouter,
  branch(
    ({ viewer }) => !viewer.repository.cases.hits.edges[0],
    renderComponent(() =>
No case found.
),
  ),
  branch(
    ({ viewer }) =>
      !viewer.repository.cases.hits.edges[0].node.samples.hits.edges.length,
    renderComponent(() =>
No biospecimen data found.
),
  ),
  withState('allExpanded', 'setAllExpanded', false),
  withState('expandAllFirstClick', 'setExpandAllFirstClick', true),
  withState(
    'state',
    'setState',
    ({ viewer: { repository: { cases: { hits: { edges } } } }, bioId }) => {
      const p = edges[0].node;
      const selectedEntity = p.samples.hits.edges[0].node;
      return {
        selectedEntity,
        type: getType(selectedEntity),
        query: bioId || '',
      };
    },
  ),
  withTheme,
)(
  ({
    history,
    push,
    theme,
    viewer: { repository: { cases: { hits: { edges } } } },
    state: { selectedEntity: se, type, query },
    setState,
    setAllExpanded,
    allExpanded,
    expandAllFirstClick,
    setExpandAllFirstClick,
  }) => {
    const p = edges[0].node;

    const founds = p.samples.hits.edges.map(e => search(query, e));
    const flattened = _.flatten(founds);
    const foundNode = ((flattened || [])[0] || { node: {} }).node;
    const selectedNode = (query && foundNode) || se;
    const foundType = (query && getType(foundNode)) || type;
    const selectedEntity = Object.keys(selectedNode).length
      ? selectedNode
      : p.samples.hits.edges[0].node;

    return (
      <Card
        className="test-biospecimen-card"
        style={{ flex: 1 }}
        title={
          <Row style={{ justifyContent: 'space-between' }}>
            Biospecimen
            <DownloadButton
              className="test-download-biospecimen"
              style={visualizingButton}
              filename={`biospecimen.case-${p.case_id}`}
              endpoint="cases"
              activeText="Processing"
              inactiveText="Export"
              filters={makeFilter([
                { field: 'cases.case_id', value: p.case_id },
              ])}
              fields={['case_id']}
              dataExportExpands={[
                'samples',
                'samples.portions',
                'samples.portions.analytes',
                'samples.portions.analytes.aliquots',
                'samples.portions.analytes.aliquots.annotations',
                'samples.portions.analytes.annotations',
                'samples.portions.submitter_id',
                'samples.portions.slides',
                'samples.portions.annotations',
                'samples.portions.center',
              ]}
            />
          </Row>
        }
      >
        <Row>
          <Column flex="3" style={{ padding: '0 15px' }}>
            <Row style={{ justifyContent: 'space-between' }}>
              <Row style={{ width: '70%' }}>

                  <SearchIcon style={styles.searchIcon(theme)} />
                  <Hidden>Search</Hidden>

                <Input
                  id="search-biospecimen"
                  name="search-biospecimen"
                  onChange={({ target }) =>
                    setState(s => ({ ...s, query: target.value }))}
                  placeholder="Search"
                  value={query}
                  style={{ borderRadius: '0 4px 4px 0' }}
                />
              </Row>
              <Button
                style={{
                  paddingLeft: '10px',
                }}
                onClick={() => {
                  Emitter.emit('expand', !allExpanded);
                  setExpandAllFirstClick(false);
                  setAllExpanded(!allExpanded);
                }}
              >
                {allExpanded ? 'Collapse All' : 'Expand All'}
              </Button>
            </Row>

            <Column style={{ padding: '10px' }}>
              <BioTreeView
                entities={{ ...p.samples, expanded: expandAllFirstClick }}
                type={{ s: 'sample', p: 'samples' }}
                query={query}
                selectedEntity={selectedEntity}
                selectEntity={(selectedEntity, type) => {
                  setState(s => ({
                    ...s,
                    selectedEntity,
                    type: type.s,
                    query: '',
                  }));
                  push({
                    ...history.location,
                    query: {
                      ...history.location.query,
                      bioId: selectedEntity[`${type.s}_id`],
                    },
                  });
                }}
                defaultExpanded={allExpanded}
              />
            </Column>
          </Column>
          <Column flex="4">
            <EntityPageVerticalTable
              thToTd={[
                { th: `${foundType} ID`, td: selectedEntity.submitter_id },
                {
                  th: `${foundType} UUID`,
                  td: selectedEntity[idFields.find(id => selectedEntity[id])],
                },
                ...Object.entries(selectedEntity)
                  .filter(
                    ([key]) =>
                      ![
                        'submitter_id',
                        'expanded',
                        `${foundType}_id`,
                        '__dataID__',
                      ].includes(key),
                  )
                  .map(([key, val]) => {
                    if (
                      ['portions', 'aliquots', 'analytes', 'slides'].includes(
                        key,
                      )
                    ) {
                      return {
                        th: humanify({ term: key }),
                        td: formatValue(val.hits.total),
                      };
                    }
                    return {
                      th: humanify({ term: key }),
                      td: formatValue(val),
                    };
                  }),
                ...(DISPLAY_SLIDES &&
                  foundType === 'slide' && [
                    {
                      th: 'Slide Image',
                      td: (
                        <Row>
                          <Tooltip Component="View Slide Image">
                            <ImageViewerLink
                              isIcon
                              query={{
                                filters: makeFilter([
                                  { field: 'cases.case_id', value: p.case_id },
                                ]),
                                selectedId: `${selectedEntity.submitter_id}.${selectedEntity.slide_id}`,
                              }}
                            >
                              <MicroscopeIcon />
                            </ImageViewerLink>{' '}
                          </Tooltip>
                          <Tooltip Component="Add to cart">
                            <Button
                              className="test-toggle-cart"
                              leftIcon={<ShoppingCartIcon />}
                              style={{ ...iconButton, marginLeft: '0.5rem' }}
                              disabled
                            />
                          </Tooltip>
                          <Tooltip Component="Download">
                            <Button
                              className="test-toggle-cart"
                              style={{ ...iconButton, marginLeft: '0.5rem' }}
                              leftIcon={<DownloadIcon />}
                              disabled
                            />
                          </Tooltip>
                        </Row>
                      ),
                    },
                  ]),
              ]}
              style={{ flex: '1 1 auto' }}
            />
          </Column>
        </Row>
      </Card>
    );
  },
);
<|endoftext|>


<commit_before>import { connect } from 'react-redux'
import { reduxForm } from 'redux-form'
import { next } from '../modules/personal_information'
import { REDUX_FORM_CONFIG } from '../config/personal_information_config'

/*  This is a container component. Notice it does not contain any JSX,
    nor does it import React. This component is **only** responsible for
    wiring in the actions and state necessary to render a presentational
    component - in this case, the counter:   */

import PersonalInformation from '../components/PersonalInformation'

/*  Object of action creators (can also be function that returns object).
    Keys will be passed as props to presentational components. Here we are
    implementing our wrapper around increment; the component doesn't care   */

const mapDispatchToProps = {
  next
}

const mapStateToProps = (state) => ({
  pinfo: state.pinfo,
  initialValues: state.pinfo.data
})

const reduxFormConfig = REDUX_FORM_CONFIG

/*  Note: mapStateToProps is where you should use `reselect` to create selectors, ie:

    import { createSelector } from 'reselect'
    const counter = (state) => state.counter
    const tripleCount = createSelector(counter, (count) => count * 3)
    const mapStateToProps = (state) => ({
      counter: tripleCount(state)
    })

    Selectors can compute derived data, allowing Redux to store the minimal possible state.
    Selectors are efficient. A selector is not recomputed unless one of its arguments change.
    Selectors are composable. They can be used as input to other selectors.
    https://github.com/reactjs/reselect    */

export default connect(mapStateToProps, mapDispatchToProps)(reduxForm(reduxFormConfig)(PersonalInformation))
<commit_msg>some more cleanup<commit_after>import { connect } from 'react-redux'
import { reduxForm } from 'redux-form'
import { next } from '../modules/personal_information'
import { REDUX_FORM_CONFIG } from '../config/personal_information_config'
import PersonalInformation from '../components/PersonalInformation'

const mapDispatchToProps = {
  next
}

const mapStateToProps = (state) => ({
  pinfo: state.pinfo,
  initialValues: state.pinfo.data
})

const reduxFormConfig = REDUX_FORM_CONFIG

export default connect(mapStateToProps, mapDispatchToProps)(reduxForm(reduxFormConfig)(PersonalInformation))
<|endoftext|>


<commit_before>/*global QUnit*/
sap.ui.define([
	"test/routing/target/historyIframe/script",
	"sap/ui/Device",
	"./HistoryUtils",
	"sap/ui/core/routing/HashChanger"
], function(oApp, Device, HistoryUtils, HashChanger) {
	"use strict";

	var bWithinFrame = window.self !== window.top;

	// Initialize the HistoryUtils
	QUnit.begin(HistoryUtils.init);

	// Resets the HistoryUtils
	QUnit.done(HistoryUtils.exit);

	QUnit.module("basic", {
		before: HistoryUtils.check,
		beforeEach: function() {
			HashChanger.getInstance().setHash("");
			return oApp.createIFrame();
		},
		afterEach: function() {
			oApp.removeIFrame();
		}
	});

	/*
	 * Firefox can't handle the back navigaiton correctly when this test runs in a testsuite. In a testsuite, each
	 * test is executed with an iframe. Because this test creates another embeded iframe, we have a situation that
	 * an iframe is embeded within another iframe. Everytime when the hash is changed in the deeper nested iframe,
	 * calling window.history.back() will reload the whole test page instead of having a back navigation in the
	 * deeper nested iframe. Therefore the tests that navigate back after a hash change in the deeper nested iframe
	 * have to be excluded in Firefox.
	 */

	if (!(Device.browser.firefox && bWithinFrame)) {
		QUnit.test("Outer(Set)->Inner(Set)->Back->Outer(Set)->Back->Forward", function(assert) {
			var iframe = document.getElementById("iframe1");
			return oApp.setHash("outerHash1")
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					return iframe.contentWindow.setHash("innerHash1");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");

					var oBackPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.back();
					return oBackPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Backwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Backwards", "Direction is correct in inner frame");
					return oApp.setHash("outerHash2");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					var oBackPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.back();
					return oBackPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Backwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Backwards", "Direction is correct in inner frame");
					var oForwardPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.forward();
					return oForwardPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Forwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Forwards", "Direction is correct in inner frame");
				});
		});
	}

	QUnit.test("Inner(Set)->Outer(Set)->Back->Outer(Set)->Back->Forward", function(assert) {
		var iframe = document.getElementById("iframe1");
		return iframe.contentWindow.setHash("outerHash1")
			.then(function() {
				assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
				assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
				return oApp.setHash("innerHash1");
			})
			.then(function() {
				assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
				assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");

				var oBackPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
				window.history.back();
				return oBackPromise;
			})
			.then(function() {
				assert.equal(oApp.getDirection(), "Backwards", "Direction is correct in outer frame");
				assert.equal(iframe.contentWindow.getDirection(), "Backwards", "Direction is correct in inner frame");
				return oApp.setHash("outerHash2");
			})
			.then(function() {
				assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
				assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
				var oBackPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
				window.history.back();
				return oBackPromise;
			})
			.then(function() {
				assert.equal(oApp.getDirection(), "Backwards", "Direction is correct in outer frame");
				assert.equal(iframe.contentWindow.getDirection(), "Backwards", "Direction is correct in inner frame");

				var oForwardPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
				window.history.forward();
				return oForwardPromise;
			})
			.then(function() {
				assert.equal(oApp.getDirection(), "Forwards", "Direction is correct in outer frame");
				assert.equal(iframe.contentWindow.getDirection(), "Forwards", "Direction is correct in inner frame");
			});
	});

	if (!(Device.browser.firefox && bWithinFrame)) {
		QUnit.test("Outer(Set)->Inner(Set)->Back->Inner(Set)->Back->Forward", function(assert) {
			var iframe = document.getElementById("iframe1");
			return oApp.setHash("outerHash1")
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					return iframe.contentWindow.setHash("innerHash1");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");

					var oBackPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.back();
					return oBackPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Backwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Backwards", "Direction is correct in inner frame");
					return iframe.contentWindow.setHash("outerHash2");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					var oBackPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.back();
					return oBackPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Backwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Backwards", "Direction is correct in inner frame");
					var oForwardPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.forward();
					return oForwardPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Forwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Forwards", "Direction is correct in inner frame");
				});
		});
	}

	if (!(Device.browser.firefox && bWithinFrame)) {
		QUnit.test("Outer(Set)->Inner(Set)->Inner(Replace)->Back->Outer(Set)", function(assert) {
			var iframe = document.getElementById("iframe1");
			return oApp.setHash("outerHash1")
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					return iframe.contentWindow.setHash("innerHash1");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					return iframe.contentWindow.replaceHash("innerHash2");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Unknown", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Unknown", "Direction is correct in inner frame");
					var oBackPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.back();
					return oBackPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Backwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Backwards", "Direction is correct in inner frame");
					return oApp.setHash("outerHash2");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
				});
		});
	}

	if (!(Device.browser.firefox && bWithinFrame)) {
		QUnit.test("Outer(Set)->Inner(Set)->Outer(Replace)->Back->Outer(Set)", function(assert) {
			var iframe = document.getElementById("iframe1");
			return oApp.setHash("outerHash1")
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					return iframe.contentWindow.setHash("innerHash1");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					return oApp.replaceHash("innerHash2");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Unknown", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Unknown", "Direction is correct in inner frame");
					var oBackPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.back();
					return oBackPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Backwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Backwards", "Direction is correct in inner frame");
					return oApp.setHash("outerHash2");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
				});
		});
	}

	if (!(Device.browser.firefox && bWithinFrame)) {
		QUnit.test("Outer(Set)->Inner(Set)->Outer(Replace)->Back->Forward", function(assert) {
			var iframe = document.getElementById("iframe1");
			return oApp.setHash("outerHash1")
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					return iframe.contentWindow.setHash("innerHash1");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					return oApp.replaceHash("innerHash2");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Unknown", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Unknown", "Direction is correct in inner frame");
					var oBackPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.back();
					return oBackPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Backwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Backwards", "Direction is correct in inner frame");
					var oForwardPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.forward();
					return oForwardPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Forwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Forwards", "Direction is correct in inner frame");
				});
		});
	}

});
<commit_msg>[INTERNAL] qunit.HistoryIFrameSync: exclude tests when started by webdriver<commit_after>/*global QUnit*/
sap.ui.define([
	"test/routing/target/historyIframe/script",
	"sap/ui/Device",
	"./HistoryUtils",
	"sap/ui/core/routing/HashChanger"
], function(oApp, Device, HistoryUtils, HashChanger) {
	"use strict";

	/*
	 * Some browsers or browsers in specific mode (like Firefox and browser controlled by web driver) can't handle the
	 * back navigation correctly when this test runs in a testsuite. In a testsuite, each test is executed with an
	 * iframe. Because this test creates another embedded iframe, we have a situation that an iframe is embedded within
	 * another iframe. Every time when the hash is changed in the deeper nested iframe, calling window.history.back()
	 * will reload the whole test page instead of having a back navigation in the deeper nested iframe. Therefore the
	 * tests that navigate back after a hash change in the deeper nested iframe have to be excluded in Firefox.
	 */
	var bBackNavigationIFrame = !((Device.browser.firefox || window.navigator.webdriver) && window.self !== window.top);

	// Initialize the HistoryUtils
	QUnit.begin(HistoryUtils.init);

	// Resets the HistoryUtils
	QUnit.done(HistoryUtils.exit);

	QUnit.module("basic", {
		before: HistoryUtils.check,
		beforeEach: function() {
			HashChanger.getInstance().setHash("");
			return oApp.createIFrame();
		},
		afterEach: function() {
			oApp.removeIFrame();
		}
	});

	if (bBackNavigationIFrame) {
		QUnit.test("Outer(Set)->Inner(Set)->Back->Outer(Set)->Back->Forward", function(assert) {
			var iframe = document.getElementById("iframe1");
			return oApp.setHash("outerHash1")
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					return iframe.contentWindow.setHash("innerHash1");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");

					var oBackPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.back();
					return oBackPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Backwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Backwards", "Direction is correct in inner frame");
					return oApp.setHash("outerHash2");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					var oBackPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.back();
					return oBackPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Backwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Backwards", "Direction is correct in inner frame");
					var oForwardPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.forward();
					return oForwardPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Forwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Forwards", "Direction is correct in inner frame");
				});
		});
	}

	QUnit.test("Inner(Set)->Outer(Set)->Back->Outer(Set)->Back->Forward", function(assert) {
		var iframe = document.getElementById("iframe1");
		return iframe.contentWindow.setHash("outerHash1")
			.then(function() {
				assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
				assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
				return oApp.setHash("innerHash1");
			})
			.then(function() {
				assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
				assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");

				var oBackPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
				window.history.back();
				return oBackPromise;
			})
			.then(function() {
				assert.equal(oApp.getDirection(), "Backwards", "Direction is correct in outer frame");
				assert.equal(iframe.contentWindow.getDirection(), "Backwards", "Direction is correct in inner frame");
				return oApp.setHash("outerHash2");
			})
			.then(function() {
				assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
				assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
				var oBackPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
				window.history.back();
				return oBackPromise;
			})
			.then(function() {
				assert.equal(oApp.getDirection(), "Backwards", "Direction is correct in outer frame");
				assert.equal(iframe.contentWindow.getDirection(), "Backwards", "Direction is correct in inner frame");

				var oForwardPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
				window.history.forward();
				return oForwardPromise;
			})
			.then(function() {
				assert.equal(oApp.getDirection(), "Forwards", "Direction is correct in outer frame");
				assert.equal(iframe.contentWindow.getDirection(), "Forwards", "Direction is correct in inner frame");
			});
	});

	if (bBackNavigationIFrame) {
		QUnit.test("Outer(Set)->Inner(Set)->Back->Inner(Set)->Back->Forward", function(assert) {
			var iframe = document.getElementById("iframe1");
			return oApp.setHash("outerHash1")
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					return iframe.contentWindow.setHash("innerHash1");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");

					var oBackPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.back();
					return oBackPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Backwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Backwards", "Direction is correct in inner frame");
					return iframe.contentWindow.setHash("outerHash2");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					var oBackPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.back();
					return oBackPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Backwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Backwards", "Direction is correct in inner frame");
					var oForwardPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.forward();
					return oForwardPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Forwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Forwards", "Direction is correct in inner frame");
				});
		});
	}

	if (bBackNavigationIFrame) {
		QUnit.test("Outer(Set)->Inner(Set)->Inner(Replace)->Back->Outer(Set)", function(assert) {
			var iframe = document.getElementById("iframe1");
			return oApp.setHash("outerHash1")
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					return iframe.contentWindow.setHash("innerHash1");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					return iframe.contentWindow.replaceHash("innerHash2");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Unknown", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Unknown", "Direction is correct in inner frame");
					var oBackPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.back();
					return oBackPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Backwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Backwards", "Direction is correct in inner frame");
					return oApp.setHash("outerHash2");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
				});
		});
	}

	if (bBackNavigationIFrame) {
		QUnit.test("Outer(Set)->Inner(Set)->Outer(Replace)->Back->Outer(Set)", function(assert) {
			var iframe = document.getElementById("iframe1");
			return oApp.setHash("outerHash1")
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					return iframe.contentWindow.setHash("innerHash1");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					return oApp.replaceHash("innerHash2");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Unknown", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Unknown", "Direction is correct in inner frame");
					var oBackPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.back();
					return oBackPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Backwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Backwards", "Direction is correct in inner frame");
					return oApp.setHash("outerHash2");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
				});
		});
	}

	if (bBackNavigationIFrame) {
		QUnit.test("Outer(Set)->Inner(Set)->Outer(Replace)->Back->Forward", function(assert) {
			var iframe = document.getElementById("iframe1");
			return oApp.setHash("outerHash1")
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					return iframe.contentWindow.setHash("innerHash1");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "NewEntry", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "NewEntry", "Direction is correct in inner frame");
					return oApp.replaceHash("innerHash2");
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Unknown", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Unknown", "Direction is correct in inner frame");
					var oBackPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.back();
					return oBackPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Backwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Backwards", "Direction is correct in inner frame");
					var oForwardPromise = Promise.race([oApp.waitForHashChange(), iframe.contentWindow.waitForHashChange()]);
					window.history.forward();
					return oForwardPromise;
				})
				.then(function() {
					assert.equal(oApp.getDirection(), "Forwards", "Direction is correct in outer frame");
					assert.equal(iframe.contentWindow.getDirection(), "Forwards", "Direction is correct in inner frame");
				});
		});
	}

});
<|endoftext|>


<commit_before>var vectorious = require('../../vectorious');

var Vector = vectorious.Vector;
//var Matrix = vectorious.Matrix;

// A few benchmarks.
// Test adding a bunch of numbers

//var repetitions = 1000;
var size = 16;

var c_rep;
var i;

var vector_1, vector_2;
var vector_res;

vector_1 = new vectorious.Vector();
//vector_2 = new vectorious.Vector();

for (i = 0; i < size; i++) {
	vector_1.push(i);
	//vector_2.push(i * 2 + 1);
}

var vector_res;
console.log('vector_1', vector_1);
var hrt_start = process.hrtime();
//for (c_rep = 0; c_rep < repetitions; c_rep++) {

vector_res = vector_1.range(100, 105);

//}

var hrt_diff = process.hrtime(hrt_start);
console.log('vector_res', vector_res);
console.log('hrt_diff', hrt_diff);

throw 'producing incorrect results 01/04/2015. 104, 105 missing from results'<commit_msg>Updated Vector.range(a, b) example<commit_after>var vectorious = require('../../vectorious');

var Vector = vectorious.Vector;

var vector_res = Vector.range(100, 105);
console.log('vector_res', vector_res);
<|endoftext|>


<commit_before>function show_commits(project) {
  project = project.replace(/\s+/g, '');
  var url = "../Jsons/"+project+".json";
  $.getJSON(url, function(json) {
    $('#page-wrapper').html('');
    $('#page-wrapper').append('

Commits - '+project+'

');
    $('#page-wrapper').append('

 Ismael Alvarez (IsmaelAlvarez)
Total: 1

message: Solucionado problema con gradle/maven
time: 2016-04-27 19:05:00
url: https://github.com/IsmaelAlvarez/logisim/commit/0953d5355dca7044b651c1f246314842af7d1674

')
  })
}

function general_view(project) {
  project = project.replace(/\s+/g, '');
  var url = "../Jsons/"+project+".json";
  $.getJSON(url, function(json) {
    $('#page-wrapper').html('');
    $('#page-wrapper').append('

Review - '+project+'

');
    $('#page-wrapper').append('

');
    var datas = [];
    for (var i in json) {
      var usr_name = json[i].nombre.substring(json[i].nombre.indexOf(" ") + 1);
      var d = {user: usr_name, commits: json[i].commits.length, issues: json[i].issues.length, comments: json[i].comments.length};
      datas.push(d);
    }
    Morris.Bar({
      element: 'bar',
      data: datas,
      xkey: 'user',
      ykeys: ['commits', 'issues', 'comments'],
      labels: ['Commits', 'Issues', 'Comentarios'],
      stacked: true,
      resize:true
    });
  });
}
<commit_msg>added commit page<commit_after>function show_commits(project) {
  project = project.replace(/\s+/g, '');
  var url = "../Jsons/"+project+".json";
  $.getJSON(url, function(json) {
    $('#page-wrapper').html('');
    $('#page-wrapper').append('

Commits - '+project+'

');
    for (var i in json) {
      $('#page-wrapper').append('

'+json[i].nombre+' ('+json[i].user+')'+ '
Total: '+json[i].commits.length+'

')
      for (var j in json[i].commits) {
        $('#page-wrapper').append('

message: '+json[i].commits[j].message+'
time: '+json[i].commits[j].time+'
url: '+json[i].commits[j].url+'

')
      }
      $('#page-wrapper').append('

');
    }
  })
}

function general_view(project) {
  project = project.replace(/\s+/g, '');
  var url = "../Jsons/"+project+".json";
  $.getJSON(url, function(json) {
    $('#page-wrapper').html('');
    $('#page-wrapper').append('

Review - '+project+'

');
    $('#page-wrapper').append('

');
    var datas = [];
    for (var i in json) {
      var usr_name = json[i].nombre.substring(json[i].nombre.indexOf(" ") + 1);
      var d = {user: usr_name, commits: json[i].commits.length, issues: json[i].issues.length, comments: json[i].comments.length};
      datas.push(d);
    }
    Morris.Bar({
      element: 'bar',
      data: datas,
      xkey: 'user',
      ykeys: ['commits', 'issues', 'comments'],
      labels: ['Commits', 'Issues', 'Comments'],
      stacked: true,
      resize:true
    });
  });
}
<|endoftext|>