<commit_before>'use strict'
var ObjectId = require("mongodb").ObjectId;
require('mongodb-toolkit');
var DLModels = require('dl-models');
var assert = require('assert');
var map = DLModels.map;
var i18n = require('dl-i18n');
var UnitPaymentPriceCorrectionNote = DLModels.purchasing.UnitPaymentPriceCorrectionNote;
var UnitPaymentOrderManager = require('./unit-payment-order-manager');
var BaseManager = require('../base-manager');

module.exports = class UnitPaymentPriceCorrectionNoteManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.purchasing.collection.UnitPaymentPriceCorrectionNote);
        this.unitPaymentOrderManager = new UnitPaymentOrderManager(db, user);
    }

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

            var getUnitPaymentPriceCorrectionNote = this.collection.singleOrDefault({
                "$and": [{
                    _id: {
                        '$ne': new ObjectId(valid._id)
                    }
                }, {
                    "no": valid.no
                }, {
                    _deleted: false
                }]
            });

            var getUnitPaymentOrder = this.unitPaymentOrderManager.getSingleByIdOrDefault(valid.unitPaymentOrder._id);

            Promise.all([getUnitPaymentPriceCorrectionNote, getUnitPaymentOrder])
                .then(results => {
                    var _unitPaymentPriceCorrectionNote = results[0];
                    var _unitPaymentOrder = results[1];
                    var now = new Date();

                    // if (!valid.no || valid.no == '')
                    //     errors["no"] = i18n.__("UnitPaymentPriceCorrectionNote.no.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.no._:No"));
                    if (_unitPaymentPriceCorrectionNote)
                        errors["no"] = i18n.__("UnitPaymentPriceCorrectionNote.no.isExists:%s is already exists", i18n.__("UnitPaymentPriceCorrectionNote.no._:No"));

                    if (!_unitPaymentOrder)
                        errors["unitPaymentOrder"] = i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder._:Unit Payment Order"));
                    else if (!valid.unitPaymentOrderId)
                        errors["unitPaymentOrder"] = i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder._:Unit Payment Order"));
                    else if (valid.unitPaymentOrder) {
                        if (!valid.unitPaymentOrder._id)
                            errors["unitPaymentOrder"] = i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder._:Unit Payment Order"));
                    }
                    else if (!valid.unitPaymentOrder)
                        errors["unitPaymentOrder"] = i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder._:Unit Payment Order"));

                    if (!valid.invoiceCorrectionNo || valid.invoiceCorrectionNo == '')
                        errors["invoiceCorrectionNo"] = i18n.__("UnitPaymentPriceCorrectionNote.invoiceCorrectionNo.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.invoiceCorrectionNo._:Invoice Correction No"));

                    if (!valid.invoiceCorrectionDate || valid.invoiceCorrectionDate == '')
                        errors["invoiceCorrectionDate"] = i18n.__("UnitPaymentPriceCorrectionNote.invoiceCorrectionDate.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.invoiceCorrectionDate._:Invoice Correction Date"));

                    if (valid.items) {
                        if (valid.items.length > 0) {
                            var itemErrors = [];
                            for (var item of valid.items) {
                                var itemError = {};
                                if (item.pricePerUnit <= 0)
                                    itemError["pricePerUnit"] = i18n.__("UnitPaymentPriceCorrectionNote.items.pricePerUnit.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.items.pricePerUnit._:Price Per Unit"));

                                if (item.priceTotal <= 0)
                                    itemError["priceTotal"] = i18n.__("UnitPaymentPriceCorrectionNote.items.priceTotal.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.items.priceTotal._:Total Price"));

                                itemErrors.push(itemError);
                            }
                            for (var itemError of itemErrors) {
                                for (var prop in itemError) {
                                    errors.items = itemErrors;
                                    break;
                                }
                                if (errors.items)
                                    break;
                            }
                        }

                        // if (valid.items.length == 0)
                        //     errors["items"] = i18n.__("UnitPaymentPriceCorrectionNote.items.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.items._:Item"));
                    }
                    else {
                        errors["items"] = i18n.__("UnitPaymentPriceCorrectionNote.items.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.items._:Item"));
                    }

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

                    valid.unitPaymentOrderId = _unitPaymentOrder._id;
                    valid.unitPaymentOrder = _unitPaymentOrder;

                    for (var item of valid.items) {
                        for (var _unitPaymentOrderItem of _unitPaymentOrder.items) {
                            for (var unitReceiptNoteItem of _unitPaymentOrderItem.unitReceiptNote.items) {
                                var _purchaseOrderExternalId = new ObjectId(item.purchaseOrderExternalId);
                                var _productId = new ObjectId(item.productId);

                                if (_purchaseOrderExternalId.equals(unitReceiptNoteItem.purchaseOrder.purchaseOrderExternalId) && _productId.equals(unitReceiptNoteItem.product._id)) {
                                    item.purchaseOrderExternalId = unitReceiptNoteItem.purchaseOrder.purchaseOrderExternalId;
                                    item.purchaseOrderExternal = unitReceiptNoteItem.purchaseOrder.purchaseOrderExternal;
                                    item.purchaseRequestId = unitReceiptNoteItem.purchaseOrder.purchaseRequestId;
                                    item.purchaseRequest = unitReceiptNoteItem.purchaseOrder.purchaseRequest;
                                    item.productId = unitReceiptNoteItem.product._id;
                                    item.product = unitReceiptNoteItem.product;
                                    item.quantity = unitReceiptNoteItem.deliveredQuantity;
                                    item.uom = unitReceiptNoteItem.deliveredUom;
                                    item.currency = unitReceiptNoteItem.currency;
                                    item.currencyRate = unitReceiptNoteItem.currencyRate;
                                    break;
                                }
                            }
                        }
                    }

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

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

        });
    }

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

        var query = {};

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

            var filterNo = {
                'no': {
                    '$regex': regex
                }
            };

            var filterSupplierName = {
                'unitPaymentOrder.supplier.name': {
                    '$regex': regex
                }
            };

            var filterUnitCoverLetterNo = {
                "unitCoverLetterNo": {
                    '$regex': regex
                }
            };

            keywordFilter = {
                '$or': [filterNo, filterSupplierName, filterUnitCoverLetterNo]
            };
        }
        query = {
            '$and': [deletedFilter, paging.filter, keywordFilter]
        }
        return query;
    }

    _createIndexes() {
        var createdDateIndex = {
            name: `ix_${map.master.collection.PurchaseOrder}__createdDate`,
            key: {
                _createdDate: -1
            }
        }
        var poNoIndex = {
            name: `ix_${map.master.collection.PurchaseOrder}_no`,
            key: {
                no: -1
            },
            unique: true
        }

        return this.collection.createIndexes([createdDateIndex, poNoIndex]);
    }

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

            this.getSingleById(id)
                .then(unitReceiptNote => {
                    var getDefinition = require('../../pdf/definitions/unit-payment-correction-note');
                    var definition = getDefinition(unitReceiptNote);

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

        });
    }

    generateNo(unit) {
        var now = new Date();
        var stamp = now / 1000 | 0;
        var code = stamp.toString();
        var locale = 'id-ID';
        var moment = require('moment');
        moment.locale(locale);
        var no = `NDO${unit.code.toUpperCase()}${moment(new Date()).format("YYMM")}${code}`;
        return no;
    }

    create(unitPaymentPriceCorrectionNote) {
        return new Promise((resolve, reject) => {
            this._createIndexes()
                .then((createIndexResults) => {
                    this._validate(unitPaymentPriceCorrectionNote)
                        .then(validData => {
                            validData.no = this.generateNo(validData.unitPaymentOrder.unit.code, validData.unitPaymentOrder.category.code);
                            this.collection.insert(validData)
                                .then(id => {
                                    resolve(id);
                                })
                                .catch(e => {
                                    reject(e);
                                });
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

}
<commit_msg>delete method generateNo (#161)<commit_after>'use strict'
var ObjectId = require("mongodb").ObjectId;
require('mongodb-toolkit');
var DLModels = require('dl-models');
var assert = require('assert');
var map = DLModels.map;
var i18n = require('dl-i18n');
var UnitPaymentPriceCorrectionNote = DLModels.purchasing.UnitPaymentPriceCorrectionNote;
var UnitPaymentOrderManager = require('./unit-payment-order-manager');
var BaseManager = require('../base-manager');

module.exports = class UnitPaymentPriceCorrectionNoteManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.purchasing.collection.UnitPaymentPriceCorrectionNote);
        this.unitPaymentOrderManager = new UnitPaymentOrderManager(db, user);
    }

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

            var getUnitPaymentPriceCorrectionNote = this.collection.singleOrDefault({
                "$and": [{
                    _id: {
                        '$ne': new ObjectId(valid._id)
                    }
                }, {
                        "no": valid.no
                    }, {
                        _deleted: false
                    }]
            });

            var getUnitPaymentOrder = this.unitPaymentOrderManager.getSingleByIdOrDefault(valid.unitPaymentOrder._id);

            Promise.all([getUnitPaymentPriceCorrectionNote, getUnitPaymentOrder])
                .then(results => {
                    var _unitPaymentPriceCorrectionNote = results[0];
                    var _unitPaymentOrder = results[1];
                    var now = new Date();

                    // if (!valid.no || valid.no == '')
                    //     errors["no"] = i18n.__("UnitPaymentPriceCorrectionNote.no.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.no._:No"));
                    if (_unitPaymentPriceCorrectionNote)
                        errors["no"] = i18n.__("UnitPaymentPriceCorrectionNote.no.isExists:%s is already exists", i18n.__("UnitPaymentPriceCorrectionNote.no._:No"));

                    if (!_unitPaymentOrder)
                        errors["unitPaymentOrder"] = i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder._:Unit Payment Order"));
                    else if (!valid.unitPaymentOrderId)
                        errors["unitPaymentOrder"] = i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder._:Unit Payment Order"));
                    else if (valid.unitPaymentOrder) {
                        if (!valid.unitPaymentOrder._id)
                            errors["unitPaymentOrder"] = i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder._:Unit Payment Order"));
                    }
                    else if (!valid.unitPaymentOrder)
                        errors["unitPaymentOrder"] = i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.unitPaymentOrder._:Unit Payment Order"));

                    if (!valid.invoiceCorrectionNo || valid.invoiceCorrectionNo == '')
                        errors["invoiceCorrectionNo"] = i18n.__("UnitPaymentPriceCorrectionNote.invoiceCorrectionNo.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.invoiceCorrectionNo._:Invoice Correction No"));

                    if (!valid.invoiceCorrectionDate || valid.invoiceCorrectionDate == '')
                        errors["invoiceCorrectionDate"] = i18n.__("UnitPaymentPriceCorrectionNote.invoiceCorrectionDate.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.invoiceCorrectionDate._:Invoice Correction Date"));

                    if (valid.items) {
                        if (valid.items.length > 0) {
                            var itemErrors = [];
                            for (var item of valid.items) {
                                var itemError = {};
                                if (item.pricePerUnit <= 0)
                                    itemError["pricePerUnit"] = i18n.__("UnitPaymentPriceCorrectionNote.items.pricePerUnit.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.items.pricePerUnit._:Price Per Unit"));

                                if (item.priceTotal <= 0)
                                    itemError["priceTotal"] = i18n.__("UnitPaymentPriceCorrectionNote.items.priceTotal.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.items.priceTotal._:Total Price"));

                                itemErrors.push(itemError);
                            }
                            for (var itemError of itemErrors) {
                                for (var prop in itemError) {
                                    errors.items = itemErrors;
                                    break;
                                }
                                if (errors.items)
                                    break;
                            }
                        }

                        // if (valid.items.length == 0)
                        //     errors["items"] = i18n.__("UnitPaymentPriceCorrectionNote.items.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.items._:Item"));
                    }
                    else {
                        errors["items"] = i18n.__("UnitPaymentPriceCorrectionNote.items.isRequired:%s is required", i18n.__("UnitPaymentPriceCorrectionNote.items._:Item"));
                    }

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

                    valid.unitPaymentOrderId = _unitPaymentOrder._id;
                    valid.unitPaymentOrder = _unitPaymentOrder;

                    for (var item of valid.items) {
                        for (var _unitPaymentOrderItem of _unitPaymentOrder.items) {
                            for (var unitReceiptNoteItem of _unitPaymentOrderItem.unitReceiptNote.items) {
                                var _purchaseOrderExternalId = new ObjectId(item.purchaseOrderExternalId);
                                var _productId = new ObjectId(item.productId);

                                if (_purchaseOrderExternalId.equals(unitReceiptNoteItem.purchaseOrder.purchaseOrderExternalId) && _productId.equals(unitReceiptNoteItem.product._id)) {
                                    item.purchaseOrderExternalId = unitReceiptNoteItem.purchaseOrder.purchaseOrderExternalId;
                                    item.purchaseOrderExternal = unitReceiptNoteItem.purchaseOrder.purchaseOrderExternal;
                                    item.purchaseRequestId = unitReceiptNoteItem.purchaseOrder.purchaseRequestId;
                                    item.purchaseRequest = unitReceiptNoteItem.purchaseOrder.purchaseRequest;
                                    item.productId = unitReceiptNoteItem.product._id;
                                    item.product = unitReceiptNoteItem.product;
                                    item.quantity = unitReceiptNoteItem.deliveredQuantity;
                                    item.uom = unitReceiptNoteItem.deliveredUom;
                                    item.currency = unitReceiptNoteItem.currency;
                                    item.currencyRate = unitReceiptNoteItem.currencyRate;
                                    break;
                                }
                            }
                        }
                    }

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

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

        });
    }

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

        var query = {};

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

            var filterNo = {
                'no': {
                    '$regex': regex
                }
            };

            var filterSupplierName = {
                'unitPaymentOrder.supplier.name': {
                    '$regex': regex
                }
            };

            var filterUnitCoverLetterNo = {
                "unitCoverLetterNo": {
                    '$regex': regex
                }
            };

            keywordFilter = {
                '$or': [filterNo, filterSupplierName, filterUnitCoverLetterNo]
            };
        }
        query = {
            '$and': [deletedFilter, paging.filter, keywordFilter]
        }
        return query;
    }

    _createIndexes() {
        var createdDateIndex = {
            name: `ix_${map.master.collection.PurchaseOrder}__createdDate`,
            key: {
                _createdDate: -1
            }
        }
        var poNoIndex = {
            name: `ix_${map.master.collection.PurchaseOrder}_no`,
            key: {
                no: -1
            },
            unique: true
        }

        return this.collection.createIndexes([createdDateIndex, poNoIndex]);
    }

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

            this.getSingleById(id)
                .then(unitReceiptNote => {
                    var getDefinition = require('../../pdf/definitions/unit-payment-correction-note');
                    var definition = getDefinition(unitReceiptNote);

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

        });
    }

    generateNo(unit, category) {
        var now = new Date();
        var stamp = now / 1000 | 0;
        var code = stamp.toString();
        var locale = 'id-ID';
        var moment = require('moment');
        moment.locale(locale);
        var no = `NDO${unit.toUpperCase()}${category.toUpperCase()}${moment(new Date()).format("YYMM")}${code}`;
        return no;
    }

    create(unitPaymentPriceCorrectionNote) {
        return new Promise((resolve, reject) => {
            this._createIndexes()
                .then((createIndexResults) => {
                    this._validate(unitPaymentPriceCorrectionNote)
                        .then(validData => {
                            validData.no = this.generateNo(validData.unitPaymentOrder.unit.code, validData.unitPaymentOrder.category.code);
                            this.collection.insert(validData)
                                .then(id => {
                                    resolve(id);
                                })
                                .catch(e => {
                                    reject(e);
                                });
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

}
<|endoftext|>


<commit_before>/**
 * @module query
 */

var log = require('./operation/log')
    , cache = require('./cache')
    , util = require('./util');

var Logger = log.loggerWithName('Query');
Logger.setLevel(log.Level.warn);

/**
 * @class  [Query description]
 * @param {Mapping} mapping
 * @param {Object} opts
 */
function Query(mapping, opts) {
    this.mapping = mapping;
    this.query = opts;
    this.ordering = null;
}

function cacheForMapping(mapping) {
    var cacheByType = cache._localCacheByType;
    var mappingName = mapping.type;
    var collectionName = mapping.collection;
    var cacheByMapping = cacheByType[collectionName];
    var cacheByLocalId;
    if (cacheByMapping) {
        cacheByLocalId = cacheByMapping[mappingName] || {};
    }
    return cacheByLocalId;
}
_.extend(Query.prototype, {
    execute: function (callback) {
        var deferred = window.q ? window.q.defer() : null;
        callback = util.constructCallbackAndPromiseHandler(callback, deferred);
        this._executeInMemory(callback);
        return deferred ? deferred.promise : null;
    },
    _dump: function (asJson) {
        return asJson ? '{}' : {};
    },
    _sortResults: function (res) {
        if (res && this.ordering) {
            var splt = this.ordering.split('-'),
                ascending = true,
                field = null;
            if (splt.length > 1) {
                field = splt[1];
                ascending = false;
            }
            else {
                field = splt[0];
            }
            res = _.sortBy(res, function (x) {
                return x[field];
            });
            if (!ascending) res.reverse();
        }
        return res;
    },
    /**
     * Return all model instances in the cache.
     * @private
     */
    _getCacheByLocalId: function () {
        return _.reduce(this.mapping.descendants, function (memo, childMapping) {
            return _.extend(memo, cacheForMapping(childMapping));
        }, _.extend({}, cacheForMapping(this.mapping)));
    },
    _executeInMemory: function (callback) {
        var deferred = window.q ? window.q.defer() : null;
        callback = util.constructCallbackAndPromiseHandler(callback, deferred);
        var cacheByLocalId = this._getCacheByLocalId();
        var keys = Object.keys(cacheByLocalId);
        var self = this;
        var res = [];
        var err;
        for (var i = 0; i < keys.length; i++) {
            var k = keys[i];
            var obj = cacheByLocalId[k];
            var matches = self.objectMatchesQuery(obj);
            if (typeof(matches) == 'string') {
                err = matches;
                break;
            } else {
                if (matches) res.push(obj);
            }
        }
        res = this._sortResults(res);
        callback(err, err ? null : res);
        return deferred ? deferred.promise : null;
    },
    orderBy: function (order) {
        this.ordering = order;
        return this;
    },
    objectMatchesQuery: function (obj) {
        var fields = Object.keys(this.query);
        for (var i = 0; i < fields.length; i++) {
            var origField = fields[i];
            var splt = origField.split('__');
            var op = 'e';
            var field;
            if (splt.length == 2) {
                field = splt[0];
                op = splt[1];
            } else {
                field = origField;
            }
            var isAttribute = this.mapping._attributeNames.indexOf(field) > -1;
            var queryObj = this.query[origField];
            var val = isAttribute ? obj.__values[field] : obj[field];
            var invalid = val === null || val === undefined;
            if (Logger.trace) {
                var stringVal;
                if (val === null) stringVal = 'null';
                else if (val === undefined) stringVal = 'undefined';
                else stringVal = val.toString();
            }
            if (op == 'e') {
                if (Logger.trace)
                    Logger.trace(stringVal + ' == ' + queryObj.toString());
                if (val != queryObj) {
                    return false;
                }
            } else if (op == 'lt') {
                if (Logger.trace) Logger.trace(stringVal + ' < ' + queryObj.toString())
                if (invalid || val >= queryObj) {
                    return false;
                }
            } else if (op == 'lte') {
                if (Logger.trace)
                    Logger.trace(stringVal + ' <= ' + queryObj.toString());
                if (invalid || val > queryObj) {
                    return false;
                }
            } else if (op == 'gt') {
                if (Logger.trace)
                    Logger.trace(stringVal + ' > ' + queryObj.toString());
                if (invalid || val <= queryObj) {
                    return false;
                }
            } else if (op == 'gte') {
                if (Logger.trace)
                    Logger.trace(stringVal + ' >= ' + queryObj.toString());
                if (invalid || val < queryObj) {
                    return false;
                }
            } else {
                return 'Query operator "' + op + '"' + ' does not exist';
            }
        }
        return true;
    }
});

exports.Query = Query;<commit_msg>Register Comparator<commit_after>/**
 * @module query
 */

var log = require('./operation/log')
    , cache = require('./cache')
    , util = require('./util');

var Logger = log.loggerWithName('Query');
Logger.setLevel(log.Level.warn);

/**
 * @class  [Query description]
 * @param {Mapping} mapping
 * @param {Object} opts
 */
function Query(mapping, opts) {
    this.mapping = mapping;
    this.query = opts;
    this.ordering = null;
}

_.extend(Query, {
    comparators: {
        e: function (opts) {
            return opts.object[opts.field] == opts.value;
        },
        lt: function (opts) {
            if (!opts.invalid) return opts.object[opts.field] < opts.value;
            return false;
        },
        gt: function (opts) {
            if (!opts.invalid) return opts.object[opts.field] > opts.value;
            return false;
        },
        lte: function (opts) {
            if (!opts.invalid) return opts.object[opts.field] <= opts.value;
            return false;
        },
        gte: function (opts) {
            if (!opts.invalid) return opts.object[opts.field] >= opts.value;
            return false;
        }
    },
    registerComparator: function (symbol, fn) {
        if (!this.comparators[symbol])
        this.comparators[symbol] = fn;
    }
});

function cacheForMapping(mapping) {
    var cacheByType = cache._localCacheByType;
    var mappingName = mapping.type;
    var collectionName = mapping.collection;
    var cacheByMapping = cacheByType[collectionName];
    var cacheByLocalId;
    if (cacheByMapping) {
        cacheByLocalId = cacheByMapping[mappingName] || {};
    }
    return cacheByLocalId;
}

_.extend(Query.prototype, {
    execute: function (callback) {
        var deferred = window.q ? window.q.defer() : null;
        callback = util.constructCallbackAndPromiseHandler(callback, deferred);
        this._executeInMemory(callback);
        return deferred ? deferred.promise : null;
    },
    _dump: function (asJson) {
        return asJson ? '{}' : {};
    },
    _sortResults: function (res) {
        if (res && this.ordering) {
            var splt = this.ordering.split('-'),
                ascending = true,
                field = null;
            if (splt.length > 1) {
                field = splt[1];
                ascending = false;
            }
            else {
                field = splt[0];
            }
            res = _.sortBy(res, function (x) {
                return x[field];
            });
            if (!ascending) res.reverse();
        }
        return res;
    },
    /**
     * Return all model instances in the cache.
     * @private
     */
    _getCacheByLocalId: function () {
        return _.reduce(this.mapping.descendants, function (memo, childMapping) {
            return _.extend(memo, cacheForMapping(childMapping));
        }, _.extend({}, cacheForMapping(this.mapping)));
    },
    _executeInMemory: function (callback) {
        var deferred = window.q ? window.q.defer() : null;
        callback = util.constructCallbackAndPromiseHandler(callback, deferred);
        var cacheByLocalId = this._getCacheByLocalId();
        var keys = Object.keys(cacheByLocalId);
        var self = this;
        var res = [];
        var err;
        for (var i = 0; i < keys.length; i++) {
            var k = keys[i];
            var obj = cacheByLocalId[k];
            var matches = self.objectMatchesQuery(obj);
            if (typeof(matches) == 'string') {
                err = matches;
                break;
            } else {
                if (matches) res.push(obj);
            }
        }
        res = this._sortResults(res);
        callback(err, err ? null : res);
        return deferred ? deferred.promise : null;
    },
    orderBy: function (order) {
        this.ordering = order;
        return this;
    },
    objectMatchesQuery: function (obj) {
        var fields = Object.keys(this.query);
        for (var i = 0; i < fields.length; i++) {
            var origField = fields[i];
            var splt = origField.split('__');
            var op = 'e';
            var field;
            if (splt.length == 2) {
                field = splt[0];
                op = splt[1];
            } else {
                field = origField;
            }
            var queryObj = this.query[origField];
            var val = obj[field];
            var invalid = val === null || val === undefined;
            if (Logger.trace) {
                var stringVal;
                if (val === null) stringVal = 'null';
                else if (val === undefined) stringVal = 'undefined';
                else stringVal = val.toString();
            }
            var comparator = Query.comparators[op],
                opts = {object: obj, field: field, value: queryObj, invalid: invalid};
            if (!comparator) {
                return 'No comparator registered for query operation "' + op + '"';
            }
            if (!comparator(opts)) return false;
        }
        return true;
    }
});

exports.Query = Query;<|endoftext|>


<commit_before>/**
 *
 *
 */

function Logger (Framework) {

	// If log is specified, use it, otherwise use the console
	if (Framework.logger) {
		Framework.error		= Framework.logger.error;
		Framework.warn		= Framework.logger.warn;
		Framework.log		= Framework.logger.debug || Framework.logger;
		Framework.verbose	= Framework.logger.verbose;
	}
	// In IE, we can't default to the browser console because there IS NO BROWSER CONSOLE
	else if (typeof console !== 'undefined') {
		Framework.error		= console && console.error && console.error.bind(console);
		Framework.warn		= console && console.warn && console.warn.bind(console);
		Framework.log		= console && console.log && console.log.bind(console);
		Framework.verbose	= console && console.debug && console.debug.bind(console);
	}

	// Support for `debug` for backwards compatibility
	Framework.debug = Framework.log;

	// Turn off all logs in production
	if (Framework.production) {
		Framework.logLevel = 'silent';
	}

	// Use log level config if provided
	var noop = function () {};
	switch ( Framework.logLevel ) {

		case 'verbose':	break;

		case 'debug':	Framework.verbose = noop;
						break;

		case 'warn':	Framework.verbose = Framework.log = noop;
						break;

		case 'error':	Framework.verbose = Framework.log =
						Framework.warn = noop;
						break;

		case 'silent':	Framework.verbose = Framework.log =
						Framework.warn = Framework.error = noop;
						break;

		default:		throw new Error ('Unrecognized logging level config ' +
						'(' + Framework.id + '.logLevel = "' + Framework.logLevel + '")');

	}

}
<commit_msg>Logger now displays correctly depending on logLevel<commit_after>/**
 *
 *
 */

function Logger (Framework) {

	// If log is specified, use it, otherwise use the console
	if (Framework.logger) {
		Framework.error		= Framework.logger.error;
		Framework.warn		= Framework.logger.warn;
		Framework.log		= Framework.logger.debug || Framework.logger;
		Framework.verbose	= Framework.logger.verbose;
	}
	// In IE, we can't default to the browser console because there IS NO BROWSER CONSOLE
	else if (typeof console !== 'undefined') {
		Framework.error		= console && console.error && console.error.bind(console);
		Framework.warn		= console && console.warn && console.warn.bind(console);
		Framework.log		= console && console.log && console.log.bind(console);
		Framework.verbose	= console && console.debug && console.debug.bind(console);
	}

	// Support for `debug` for backwards compatibility
	Framework.debug = Framework.log;

	// Turn off all logs in production
	if (Framework.production) {
		Framework.logLevel = 'silent';
	}

	// Use log level config if provided
	var noop = function () {};
	switch ( Framework.logLevel ) {

		case 'verbose':	break;

		case 'debug':	Framework.verbose = noop;
						break;

		case 'warn':	Framework.verbose = Framework.log = Framework.debug = noop;
						break;

		case 'error':	Framework.verbose = Framework.log = Framework.debug =
						Framework.warn = noop;
						break;

		case 'silent':	Framework.verbose = Framework.log = Framework.debug
						Framework.warn = Framework.error = noop;
						break;

		default:		throw new Error ('Unrecognized logging level config ' +
						'(' + Framework.id + '.logLevel = "' + Framework.logLevel + '")');

	}

}
<|endoftext|>


<commit_before>/**
 * @file todo command
 * @author Sankarsan Kampa (a.k.a k3rn31p4nic)
 * @license MIT
 */

exports.exec = async (Bastion, message, args) => {
  try {
    if (args.length < 1) {
      /**
      * The command was ran with invalid parameters.
      * @fires commandUsage
      */
      return Bastion.emit('commandUsage', message, this.help);
    }

    let todo = await Bastion.db.get(`SELECT * FROM todo WHERE ownerID=${message.author.id}`);

    if (!todo) {
      await Bastion.db.run('INSERT OR IGNORE INTO todo (ownerID, list) VALUES (?, ?)', [ message.author.id, `["${args.join(' ')}"]` ]);

      message.channel.send({
        embed: {
          color: Bastion.colors.GREEN,
          title: 'Todo list created',
          description: `${message.author.username}, I've created your todo list and added **${args.join(' ')}** to it.`
        }
      }).catch(e => {
        Bastion.log.error(e);
      });
    }
    else {
      let list = JSON.parse(todo.list);
      list.push(args.join(' '));

      await Bastion.db.run(`UPDATE todo SET list='${JSON.stringify(list)}' WHERE ownerID=${message.author.id}`);

      message.channel.send({
        embed: {
          color: Bastion.colors.GREEN,
          title: 'Todo list updated',
          description: `${message.author.username}, I've added **${args.join(' ')}** to your todo list.`
        }
      }).catch(e => {
        Bastion.log.error(e);
      });
    }
  }
  catch (e) {
    Bastion.log.error(e);
  }
};

exports.config = {
  aliases: [],
  enabled: true,
  ownerOnly: true
};

exports.help = {
  name: 'todo',
  botPermission: '',
  userTextPermission: '',
  userVoicePermission: '',
  usage: 'todo <text>',
  example: [ 'todo Reconfigure my firewall' ]
};
<commit_msg>Removed todo command<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 2012-2013 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * Print component
 * Creates a AttributeList component
 * @author Roy Braam
 */
Ext.define ("viewer.components.Search",{
    extend: "viewer.components.Component",
    form: null,
    searchResult: null,
    results: null,
    margin: "0 5 0 0",
    autosuggestStore:null,
    searchField:null,
    resultPanelId: '',
    defaultFormHeight: MobileManager.isMobile() ? 100 : 90,
    searchRequestId: 0,
    config:{
        title: null,
        iconUrl: null,
        tooltip: null,
        searchconfigs: null,
        formHeight:null,
        label: "",
        typeLabel:null
    },
    constructor: function (conf){
        if (conf.typeLabel===undefined){
            conf.typeLabel={
                Street: 'Straat',
                MunicipalitySubdivision: 'Plaats',
                Municipality: 'Gemeente',
                CountrySubdivision: 'Provincie'
            };
        }
        viewer.components.Search.superclass.constructor.call(this, conf);
        this.initConfig(conf);
        this.renderButton();
        this.loadWindow();
        return this;
    },
    renderButton: function() {
        var me = this;
        viewer.components.Search.superclass.renderButton.call(this,{
            text: me.title,
            icon: me.iconUrl,
            tooltip: me.tooltip,
            label: me.label,
            handler: function() {
                me.popup.show();
            }
        });
    },
    loadWindow : function(){
        var me = this;
        this.form = Ext.create("Ext.form.Panel",{
            frame: false,
            height: this.formHeight || this.defaultFormHeight,
            items: this.getFormItems(),
            border: 0,
            style: {
                padding: '0px 10px 0px 10px'
            }
        });
        this.resultPanelId = Ext.id();
        this.mainContainer = Ext.create('Ext.container.Container', {
            id: this.name + 'Container',
            width: '100%',
            height: '100%',
            layout: {
                type: 'vbox',
                align: 'stretch'
            },
            style: {
                backgroundColor: 'White'
            },
            renderTo: this.getContentDiv(),
            items: [
                this.form, {
                    id: this.name + 'ContentPanel',
                    xtype: "container",
                    autoScroll: true,
                    width: '100%',
                    flex: 1,
                    html: '

'
                }, {
                    id: this.name + 'ClosingPanel',
                    xtype: "container",
                    width: '100%',
                    height: MobileManager.isMobile() ? 45 : 25,
                    style: {
                        marginTop: '10px',
                        marginRight: '5px'
                    },
                    layout: {
                        type:'hbox',
                        pack:'end'
                    },
                    items: [
                        {xtype: 'button', text: 'Sluiten', componentCls: 'mobileLarge', handler: function() {
                            me.popup.hide();
                        }}
                    ]
                }
            ]
        });
        this.form.getChildByElement("cancel"+ this.name).setVisible(false);
    },
    getFormItems: function(){
        var me = this;
        var itemList = new Array();
        if(this.searchconfigs ){
            if(this.searchconfigs.length === 1){
                itemList.push({
                    xtype: 'label',
                    text: 'Zoek op: '+ this.searchconfigs[0].name
                });
            }else if (this.searchconfigs.length > 1 ){
                var configs = Ext.create('Ext.data.Store', {
                    fields: ['id', 'name', 'url'],
                    data : this.searchconfigs
                });
                itemList.push({
                    xtype: "flamingocombobox",
                    fieldLabel: 'Zoek op',
                    store: configs,
                    queryMode: 'local',
                    displayField: 'name',
                    valueField: 'id',
                    anchor: '100%',
                    emptyText:'Maak uw keuze',
                    id: 'searchName' + this.name,
                    listeners:{
                        change:{
                            fn: function(combo, newValue){
                                this.searchConfigChanged(newValue);
                            },
                            scope:this
                        }
                    }
                });
            }
            if (this.searchconfigs.length> 0){
                var queryMode = 'local';
                var extraParams = {};
                if(this.searchconfigs.length === 1 && this.searchconfigs[0].type === "solr" ){
                    queryMode = "remote";

                    extraParams["searchName"]=this.searchconfigs[0].id;
                    extraParams["appId"]=appId;
                    extraParams["componentName"]=this.name;
                }
                this.autosuggestStore = Ext.create(Ext.data.Store,  {
                    autoLoad: false,
                    model: 'Doc',
                    proxy: {
                        type: 'ajax',
                        url: actionBeans["autosuggest"],
                        extraParams: extraParams,
                        reader: {
                            type: 'json',
                            root: 'response.docs'
                        }
                    }
                });

                this.searchField = Ext.create( Ext.form.field.ComboBox,{
                    name: 'searchfield',
                    hideTrigger: true,
                    anchor: '100%',
                    triggerAction: 'query',
                    queryParam: "searchText",
                    displayField: "suggestion",
                    queryMode: queryMode,
                    id: 'searchfield' + this.name,
                    minChars: 2,
                    listeners: {
                        specialkey: function(field, e){
                            if (e.getKey() === e.ENTER) {
                                me.search();
                            }
                        }
                    },
                    store:this.autosuggestStore
                });
                itemList.push(this.searchField);

                itemList.push({
                    xtype: 'button',
                    text: 'Zoeken',
                    componentCls: 'mobileLarge',
                    margin: this.margin,
                    listeners: {
                        click:{
                            scope: this,
                            fn: this.search
                        }
                    }
                });
            }
        }
        itemList.push({
            xtype: 'button',
            text: 'Zoekactie afbreken',
            margin: this.margin,
            componentCls: 'mobileLarge',
            name: 'cancel',
            id: 'cancel'+ this.name,
            listeners: {
                click:{
                    scope: this,
                    fn: this.cancel
                }
            }
        });
        return itemList;
    },
    hideWindow : function(){
        this.popup.hide();
    },
    search : function(){
        this.searchRequestId++;
        if(this.results != null){
            this.results.destroy();
        }
        var searchText = this.form.getChildByElement("searchfield" + this.name).getValue();
        var searchName = '';
        if(this.searchconfigs.length === 1){
            searchName = this.searchconfigs[0].id;
        }else{
            searchName = this.form.getChildByElement("searchName" + this.name).getValue();
        }

        if(searchName !== null && searchText !== ""){
            var requestPath=  contextPath+"/action/search";
            var requestParams = {};

            requestParams["searchText"]= searchText;
            requestParams["searchName"]= searchName;
            requestParams["appId"]= appId;
            requestParams["componentName"]= this.name;
            requestParams["searchRequestId"]= this.searchRequestId;
            this.getExtraRequestParams(requestParams,searchName);
            var me = this;
            me.mainContainer.setLoading({
                msg: 'Bezig met zoeken'
            });
            Ext.Ajax.request({
                url: requestPath,
                params: requestParams,
                success: function ( result, request ) {
                    var response = Ext.JSON.decode(result.responseText);
                    me.searchResult = response.results;
                    if (response.error){
                        Ext.MessageBox.alert("Foutmelding", response.error);
                    }
                    if (me.searchRequestId==response.request.searchRequestId){
                        me.showSearchResults();
                    }
                    me.mainContainer.setLoading(false);
                },
                failure: function(result, request) {
                    var response = Ext.JSON.decode(result.responseText);
                    Ext.MessageBox.alert("Foutmelding", response.error);
                    me.mainContainer.setLoading(false);
                }
            });
            this.form.getChildByElement("cancel"+ this.name).setVisible(true);
        } else {
            Ext.MessageBox.alert("Foutmelding", "Alle velden dienen ingevult te worden.");
            // search request is not complete
        }
    },
    showSearchResults : function(){
        var html = "";
        if(this.searchResult.length <= 0){
            html = "
Er zijn geen resultaten gevonden.
";
        }
        var me = this;
        this.form.getChildByElement("cancel"+ this.name).setVisible(false);
        var buttonList = new Array();
        for ( var i = 0 ; i < this.searchResult.length ; i ++){
            var result = this.searchResult[i];
            var typeLabel = this.typeLabel[result.type];

            buttonList.push({
                text: result.label + (typeLabel!==undefined ? " ("+typeLabel+")" : ""),
                xtype: 'button',
                margin: '10px 10px 0px 10px',
                componentCls: 'mobileLarge',
                tooltip: 'Zoom naar locatie',
                id: "searchButton_"+i,
                listeners: {
                    click:{
                        scope: me,
                        fn: function(button,e,eOpts){
                            var config =this.searchResult[button.id.split("_")[1]];
                            config.x = (config.maxx +config.minx)/2;
                            config.y = (config.maxy +config.miny)/2;
                            me.handleSearchResult(config);
                        }
                    }
                }
            });
        }

        me.results = Ext.create('Ext.form.Panel', {
            title: 'Resultaten:',
            renderTo: this.resultPanelId,
            html: html,
            height: '100%',
            autoScroll: true,
            style: {
                padding: '0px 0px 10px 0px'
            },
            items: buttonList
        });

    },
    cancel : function(){
        this.form.getChildByElement("searchfield"+ this.name).setValue("");
        this.form.getChildByElement("searchName"+ this.name).setValue("");
        this.form.getChildByElement("cancel"+ this.name).setVisible(false);
        this.results.destroy();
    },
    handleSearchResult : function(config){
        this.viewerController.mapComponent.getMap().zoomToExtent(config.location);
        this.viewerController.mapComponent.getMap().removeMarker("searchmarker");
        this.viewerController.mapComponent.getMap().setMarker("searchmarker",config.x,config.y,"marker");

        //var se

        this.popup.hide();
    },
    getExtComponents: function() {
        var c = [ this.mainContainer.getId(), this.form.getId() ];
        if(this.results) c.push(this.results.getId());
        return c;
    },

    searchConfigChanged: function(searchConfig){
        for(var i = 0 ; i < this.searchconfigs.length ;i++){
            var config = this.searchconfigs[i];
            if(config.id === searchConfig){
                if(config.type === "solr"){
                    this.searchField.queryMode = "remote";
                    var proxy = this.searchField.getStore().getProxy();
                    var params = proxy.extraParams;
                    params["searchName"]=searchConfig;
                    params["appId"]=appId;
                    params["componentName"]=this.name;

                }else{
                    this.searchField.queryMode = "local";
                    this.searchField.getStore().removeAll();
                }
                break;
            }
        }
    },
    getCurrentSearchType : function(){
        if(this.searchconfigs.length === 1){
            return this.searchconfigs[0].type;
        }else{
            var value = Ext.getCmp('searchName' + this.name).getValue();
            for(var i = 0 ; i < this.searchconfigs.length ; i++){
                if(this.searchconfigs[i].id === value){
                    return this.searchconfigs[i].type;
                }
            }
            return null;
        }
    },
    getExtraRequestParams:function(params, type){
        if(this.getCurrentSearchType() === "solr"){
            var appLayers = this.viewerController.getVisibleLayers();
            params["visibleLayers"] = appLayers.join(", ");
        }else{
            // Nothing to do here
        }
    }
});

Ext.define('Doc', {
    extend: 'Ext.data.Model',
        fields: [
            {name: 'suggestion', type: 'string'}
        ]
});
Ext.define('Response', {
    extend: 'Ext.data.Model',
    fields: [
        {name: 'docs', type: 'Doc'}
    ]
});
<commit_msg>Implemented functionality to switch layers on when clicking a solr search result<commit_after>/*
 * Copyright (C) 2012-2013 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * Print component
 * Creates a AttributeList component
 * @author Roy Braam
 */
Ext.define ("viewer.components.Search",{
    extend: "viewer.components.Component",
    form: null,
    searchResult: null,
    results: null,
    margin: "0 5 0 0",
    autosuggestStore:null,
    searchField:null,
    resultPanelId: '',
    defaultFormHeight: MobileManager.isMobile() ? 100 : 90,
    searchRequestId: 0,
    config:{
        title: null,
        iconUrl: null,
        tooltip: null,
        searchconfigs: null,
        formHeight:null,
        label: "",
        typeLabel:null
    },
    constructor: function (conf){
        if (conf.typeLabel===undefined){
            conf.typeLabel={
                Street: 'Straat',
                MunicipalitySubdivision: 'Plaats',
                Municipality: 'Gemeente',
                CountrySubdivision: 'Provincie'
            };
        }
        viewer.components.Search.superclass.constructor.call(this, conf);
        this.initConfig(conf);
        this.renderButton();
        this.loadWindow();
        return this;
    },
    renderButton: function() {
        var me = this;
        viewer.components.Search.superclass.renderButton.call(this,{
            text: me.title,
            icon: me.iconUrl,
            tooltip: me.tooltip,
            label: me.label,
            handler: function() {
                me.popup.show();
            }
        });
    },
    loadWindow : function(){
        var me = this;
        this.form = Ext.create("Ext.form.Panel",{
            frame: false,
            height: this.formHeight || this.defaultFormHeight,
            items: this.getFormItems(),
            border: 0,
            style: {
                padding: '0px 10px 0px 10px'
            }
        });
        this.resultPanelId = Ext.id();
        this.mainContainer = Ext.create('Ext.container.Container', {
            id: this.name + 'Container',
            width: '100%',
            height: '100%',
            layout: {
                type: 'vbox',
                align: 'stretch'
            },
            style: {
                backgroundColor: 'White'
            },
            renderTo: this.getContentDiv(),
            items: [
                this.form, {
                    id: this.name + 'ContentPanel',
                    xtype: "container",
                    autoScroll: true,
                    width: '100%',
                    flex: 1,
                    html: '

'
                }, {
                    id: this.name + 'ClosingPanel',
                    xtype: "container",
                    width: '100%',
                    height: MobileManager.isMobile() ? 45 : 25,
                    style: {
                        marginTop: '10px',
                        marginRight: '5px'
                    },
                    layout: {
                        type:'hbox',
                        pack:'end'
                    },
                    items: [
                        {xtype: 'button', text: 'Sluiten', componentCls: 'mobileLarge', handler: function() {
                            me.popup.hide();
                        }}
                    ]
                }
            ]
        });
        this.form.getChildByElement("cancel"+ this.name).setVisible(false);
    },
    getFormItems: function(){
        var me = this;
        var itemList = new Array();
        if(this.searchconfigs ){
            if(this.searchconfigs.length === 1){
                itemList.push({
                    xtype: 'label',
                    text: 'Zoek op: '+ this.searchconfigs[0].name
                });
            }else if (this.searchconfigs.length > 1 ){
                var configs = Ext.create('Ext.data.Store', {
                    fields: ['id', 'name', 'url'],
                    data : this.searchconfigs
                });
                itemList.push({
                    xtype: "flamingocombobox",
                    fieldLabel: 'Zoek op',
                    store: configs,
                    queryMode: 'local',
                    displayField: 'name',
                    valueField: 'id',
                    anchor: '100%',
                    emptyText:'Maak uw keuze',
                    id: 'searchName' + this.name,
                    listeners:{
                        change:{
                            fn: function(combo, newValue){
                                this.searchConfigChanged(newValue);
                            },
                            scope:this
                        }
                    }
                });
            }
            if (this.searchconfigs.length> 0){
                var queryMode = 'local';
                var extraParams = {};
                if(this.searchconfigs.length === 1 && this.searchconfigs[0].type === "solr" ){
                    queryMode = "remote";

                    extraParams["searchName"]=this.searchconfigs[0].id;
                    extraParams["appId"]=appId;
                    extraParams["componentName"]=this.name;
                }
                this.autosuggestStore = Ext.create(Ext.data.Store,  {
                    autoLoad: false,
                    model: 'Doc',
                    proxy: {
                        type: 'ajax',
                        url: actionBeans["autosuggest"],
                        extraParams: extraParams,
                        reader: {
                            type: 'json',
                            root: 'response.docs'
                        }
                    }
                });

                this.searchField = Ext.create( Ext.form.field.ComboBox,{
                    name: 'searchfield',
                    hideTrigger: true,
                    anchor: '100%',
                    triggerAction: 'query',
                    queryParam: "searchText",
                    displayField: "suggestion",
                    queryMode: queryMode,
                    id: 'searchfield' + this.name,
                    minChars: 2,
                    listeners: {
                        specialkey: function(field, e){
                            if (e.getKey() === e.ENTER) {
                                me.search();
                            }
                        }
                    },
                    store:this.autosuggestStore
                });
                itemList.push(this.searchField);

                itemList.push({
                    xtype: 'button',
                    text: 'Zoeken',
                    componentCls: 'mobileLarge',
                    margin: this.margin,
                    listeners: {
                        click:{
                            scope: this,
                            fn: this.search
                        }
                    }
                });
            }
        }
        itemList.push({
            xtype: 'button',
            text: 'Zoekactie afbreken',
            margin: this.margin,
            componentCls: 'mobileLarge',
            name: 'cancel',
            id: 'cancel'+ this.name,
            listeners: {
                click:{
                    scope: this,
                    fn: this.cancel
                }
            }
        });
        return itemList;
    },
    hideWindow : function(){
        this.popup.hide();
    },
    search : function(){
        this.searchRequestId++;
        if(this.results != null){
            this.results.destroy();
        }
        var searchText = this.form.getChildByElement("searchfield" + this.name).getValue();
        var searchName = '';
        if(this.searchconfigs.length === 1){
            searchName = this.searchconfigs[0].id;
        }else{
            searchName = this.form.getChildByElement("searchName" + this.name).getValue();
        }

        if(searchName !== null && searchText !== ""){
            var requestPath=  contextPath+"/action/search";
            var requestParams = {};

            requestParams["searchText"]= searchText;
            requestParams["searchName"]= searchName;
            requestParams["appId"]= appId;
            requestParams["componentName"]= this.name;
            requestParams["searchRequestId"]= this.searchRequestId;
            this.getExtraRequestParams(requestParams,searchName);
            var me = this;
            me.mainContainer.setLoading({
                msg: 'Bezig met zoeken'
            });
            Ext.Ajax.request({
                url: requestPath,
                params: requestParams,
                success: function ( result, request ) {
                    var response = Ext.JSON.decode(result.responseText);
                    me.searchResult = response.results;
                    if (response.error){
                        Ext.MessageBox.alert("Foutmelding", response.error);
                    }
                    if (me.searchRequestId==response.request.searchRequestId){
                        me.showSearchResults();
                    }
                    me.mainContainer.setLoading(false);
                },
                failure: function(result, request) {
                    var response = Ext.JSON.decode(result.responseText);
                    Ext.MessageBox.alert("Foutmelding", response.error);
                    me.mainContainer.setLoading(false);
                }
            });
            this.form.getChildByElement("cancel"+ this.name).setVisible(true);
        } else {
            Ext.MessageBox.alert("Foutmelding", "Alle velden dienen ingevult te worden.");
            // search request is not complete
        }
    },
    showSearchResults : function(){
        var html = "";
        if(this.searchResult.length <= 0){
            html = "
Er zijn geen resultaten gevonden.
";
        }
        var me = this;
        this.form.getChildByElement("cancel"+ this.name).setVisible(false);
        var buttonList = new Array();
        for ( var i = 0 ; i < this.searchResult.length ; i ++){
            var result = this.searchResult[i];
            var typeLabel = this.typeLabel[result.type];

            buttonList.push({
                text: result.label + (typeLabel!==undefined ? " ("+typeLabel+")" : ""),
                xtype: 'button',
                margin: '10px 10px 0px 10px',
                componentCls: 'mobileLarge',
                tooltip: 'Zoom naar locatie',
                id: "searchButton_"+i,
                listeners: {
                    click:{
                        scope: me,
                        fn: function(button,e,eOpts){
                            var config =this.searchResult[button.id.split("_")[1]];
                            config.x = (config.maxx +config.minx)/2;
                            config.y = (config.maxy +config.miny)/2;
                            me.handleSearchResult(config);
                        }
                    }
                }
            });
        }

        me.results = Ext.create('Ext.form.Panel', {
            title: 'Resultaten:',
            renderTo: this.resultPanelId,
            html: html,
            height: '100%',
            autoScroll: true,
            style: {
                padding: '0px 0px 10px 0px'
            },
            items: buttonList
        });

    },
    cancel : function(){
        this.form.getChildByElement("searchfield"+ this.name).setValue("");
        this.form.getChildByElement("searchName"+ this.name).setValue("");
        this.form.getChildByElement("cancel"+ this.name).setVisible(false);
        this.results.destroy();
    },
    handleSearchResult : function(config){
        this.viewerController.mapComponent.getMap().zoomToExtent(config.location);
        this.viewerController.mapComponent.getMap().removeMarker("searchmarker");
        this.viewerController.mapComponent.getMap().setMarker("searchmarker",config.x,config.y,"marker");

        var type = this.getCurrentSearchType();
        if(type === "solr"){

            var searchconfig = this.getCurrentSearchconfig();
            if(searchconfig ){
                var solrConfig = searchconfig.solrConfig[config.searchConfig];
                var switchOnLayers = solrConfig.switchOnLayers;
                if(switchOnLayers){
                    for(var i = 0 ; i <switchOnLayers.length ;i++){
                        var appLayerId = switchOnLayers[i];
                        var applayer = this.viewerController.getAppLayerById(appLayerId);
                        this.viewerController.setLayerVisible(applayer,true);
                    }
                }
            }
        }

        this.popup.hide();
    },
    getExtComponents: function() {
        var c = [ this.mainContainer.getId(), this.form.getId() ];
        if(this.results) c.push(this.results.getId());
        return c;
    },

    searchConfigChanged: function(searchConfig){
        for(var i = 0 ; i < this.searchconfigs.length ;i++){
            var config = this.searchconfigs[i];
            if(config.id === searchConfig){
                if(config.type === "solr"){
                    this.searchField.queryMode = "remote";
                    var proxy = this.searchField.getStore().getProxy();
                    var params = proxy.extraParams;
                    params["searchName"]=searchConfig;
                    params["appId"]=appId;
                    params["componentName"]=this.name;

                }else{
                    this.searchField.queryMode = "local";
                    this.searchField.getStore().removeAll();
                }
                break;
            }
        }
    },
    getCurrentSearchType : function(){
        if(this.searchconfigs.length === 1){
            return this.searchconfigs[0].type;
        }else{
            var value = Ext.getCmp('searchName' + this.name).getValue();
            var config = this.getSearchconfigById(value);
            if(config){
                return config.type;
            }else{
                return null;
            }
        }
    },
    getCurrentSearchconfig :function(){
        var value = Ext.getCmp('searchName' + this.name).getValue();
        var config = this.getSearchconfigById(value);
        return config;
    },
    getSearchconfigById:function(id){
        for (var i = 0; i < this.searchconfigs.length; i++) {
            if (this.searchconfigs[i].id ===  id) {
                return this.searchconfigs[i];
            }
        }
        return null;
    },
    getExtraRequestParams:function(params, type){
        if(this.getCurrentSearchType() === "solr"){
            var appLayers = this.viewerController.getVisibleLayers();
            params["visibleLayers"] = appLayers.join(", ");
        }else{
            // Nothing to do here
        }
    }
});

Ext.define('Doc', {
    extend: 'Ext.data.Model',
        fields: [
            {name: 'suggestion', type: 'string'}
        ]
});
Ext.define('Response', {
    extend: 'Ext.data.Model',
    fields: [
        {name: 'docs', type: 'Doc'}
    ]
});
<|endoftext|>


<commit_before>module.exports = {
  name: "Person",
  prefixes: {
    "": "http://schema.org/",
    "foaf": "http://xmlns.com/foaf/0.1/#",
    "org": "http://www.w3.org/TR/vocab-org#",
  },
  schema: {
    type: 'object',
    properties: {
      name: {
        type: "string",
        context: "foaf:name",
      },
      memberships: {
        type: "array",
        context: "org:hasMembership",
        items: {
          reverse: "member",
          $ref: "Membership",
        },
      },
    },
  },
};
<commit_msg>minor change to foaf prefix<commit_after>module.exports = {
  name: "Person",
  prefixes: {
    "": "http://schema.org/",
    "foaf": "http://xmlns.com/foaf/0.1#",
    "org": "http://www.w3.org/TR/vocab-org#",
  },
  schema: {
    type: 'object',
    properties: {
      name: {
        type: "string",
        context: "foaf:name",
      },
      memberships: {
        type: "array",
        context: "org:hasMembership",
        items: {
          reverse: "member",
          $ref: "Membership",
        },
      },
    },
  },
};
<|endoftext|>


<commit_before>if (window.CanvasRenderingContext2D){
	var defaultOffsets = {
		destX   : 0,
		destY   : 0,
		sourceX : 0,
		sourceY : 0,
		width   : 'auto',
		height  : 'auto'
	};
	CanvasRenderingContext2D.prototype.blendOnto = function(destContext,blendMode,offsetOptions){
		var offsets={};
		for (var key in defaultOffsets){
			if (defaultOffsets.hasOwnProperty(key)){
				offsets[key] = (offsetOptions && offsetOptions[key]) || defaultOffsets[key];
			}
		}
		if (offsets.width =='auto') offsets.width =this.canvas.width;
		if (offsets.height=='auto') offsets.height=this.canvas.height;
		offsets.width  = Math.min(offsets.width, this.canvas.width-offsets.sourceX, destContext.canvas.width-offsets.destX );
		offsets.height = Math.min(offsets.height,this.canvas.height-offsets.sourceY,destContext.canvas.height-offsets.destY);

		var srcD = this.getImageData(offsets.sourceX,offsets.sourceY,offsets.width,offsets.height);
		var dstD = destContext.getImageData(offsets.destX,offsets.destY,offsets.width,offsets.height);
		var src  = srcD.data;
		var dst  = dstD.data;
		var sA, dA, len=dst.length;

		switch(blendMode){
			case 'normal':
				for (var px=0;px<len;px+=4){
					sA = src[px+3]/255;
					dA = dst[px+3]/255;
					dst[px+3] = (sA+dA)*255;
					dst[px  ] = dst[px  ] + (src[px  ] - dst[px  ])*dA;
					dst[px+1] = dst[px+1] + (src[px+1] - dst[px+1])*dA;
					dst[px+2] = dst[px+2] + (src[px+2] - dst[px+2])*dA;
				}
			break;
			case 'screen':
				for (var px=0;px<len;px+=4){
					sA = src[px+3]/255;
					dA = dst[px+3]/255;
					dst[px+3] = (sA + dA*(1-sA))*255;
					sA /= 255; dA /= 255;
					dst[px  ] = Math.ceil((1 - (1-sA*src[px  ])*(1-dA*dst[px  ]) )*255);
					dst[px+1] = Math.ceil((1 - (1-sA*src[px+1])*(1-dA*dst[px+1]) )*255);
					dst[px+2] = Math.ceil((1 - (1-sA*src[px+2])*(1-dA*dst[px+2]) )*255);
				}
			break;
			case 'add':
				for (var px=0;px<len;px+=4){
					sA = src[px+3]/255;
					dA = dst[px+3]/255;
					dst[px+3] = (sA + dA*(1-sA))*255;
					dst[px  ] = src[px  ]*sA+dst[px  ]*dA;
					dst[px+1] = src[px+1]*sA+dst[px+1]*dA;
					dst[px+2] = src[px+2]*sA+dst[px+2]*dA;
				}
			break;
			case 'multiply':
				for (var px=0;px<len;px+=4){
					sA = src[px+3]/255;
					dA = dst[px+3]/255;
					dst[px+3] = (sA + dA*(1-sA))*255;
					dst[px  ] = src[px  ]*sA*dst[px  ]*dA;
					dst[px+1] = src[px+1]*sA+dst[px+1]*dA;
					dst[px+2] = src[px+2]*sA+dst[px+2]*dA;
				}
			break;
			case 'difference':
				for (var px=0;px<len;px+=4){
					sA = src[px+3]/255;
					dA = dst[px+3]/255;
					dst[px+3] = (sA + dA*(1-sA))*255;
					dst[px  ] = (src[px  ]>dst[px  ]) ? (src[px  ]-dst[px  ]) : (dst[px  ]-src[px  ]);
					dst[px+1] = (src[px+1]>dst[px+1]) ? (src[px+1]-dst[px+1]) : (dst[px+1]-src[px+1]);
					dst[px+2] = (src[px+2]>dst[px+2]) ? (src[px+2]-dst[px+2]) : (dst[px+2]-src[px+2]);
				}
			break;
			default:
				// Unsupported blend mode
				for (var px=0;px<len;px+=4){
					dst[px] = dst[px+3] = 255;
					dst[px+1] = px%8==0 ? 255 : 0;
					dst[px+2] = px%8==0 ? 0 : 255;
				}
		}
		dstD.data = dst;
		destContext.putImageData(dstD,offsets.destX,offsets.destY);
	};
}<commit_msg>Screen mode working<commit_after>if (window.CanvasRenderingContext2D){
	var defaultOffsets = {
		destX   : 0,
		destY   : 0,
		sourceX : 0,
		sourceY : 0,
		width   : 'auto',
		height  : 'auto'
	};
	CanvasRenderingContext2D.prototype.blendOnto = function(destContext,blendMode,offsetOptions){
		var offsets={};
		for (var key in defaultOffsets){
			if (defaultOffsets.hasOwnProperty(key)){
				offsets[key] = (offsetOptions && offsetOptions[key]) || defaultOffsets[key];
			}
		}
		if (offsets.width =='auto') offsets.width =this.canvas.width;
		if (offsets.height=='auto') offsets.height=this.canvas.height;
		offsets.width  = Math.min(offsets.width, this.canvas.width-offsets.sourceX, destContext.canvas.width-offsets.destX );
		offsets.height = Math.min(offsets.height,this.canvas.height-offsets.sourceY,destContext.canvas.height-offsets.destY);

		var srcD = this.getImageData(offsets.sourceX,offsets.sourceY,offsets.width,offsets.height);
		var dstD = destContext.getImageData(offsets.destX,offsets.destY,offsets.width,offsets.height);
		var src  = srcD.data;
		var dst  = dstD.data;
		var sA, dA, len=dst.length;
		var sRA, sGA, sBA, dRA, dGA, dBA, dA2;

		switch(blendMode){
			case 'normal':
				for (var px=0;px<len;px+=4){
					sA = src[px+3]/255;
					dA = dst[px+3]/255;
					dst[px+3] = (sA+dA)*255;
					dst[px  ] = (1 - sA)*dst[px  ] + src[px  ];
					dst[px+1] = (1 - sA)*dst[px+1] + src[px+1];
					dst[px+2] = (1 - sA)*dst[px+2] + src[px+2];
				}
			break;
			case 'screen':
				for (var px=0;px<len;px+=4){
					sA  = src[px+3]/255;
					dA  = dst[px+3]/255;
					dA2 = (sA + dA - sA*dA);
					dst[px+3] = dA2*255;

					sA /= 255; dA /= 255;
					sRA = src[px  ]*sA;
					dRA = dst[px  ]*dA;
					sGA = src[px+1]*sA;
					dGA = dst[px+1]*dA;
					sBA = src[px+2]*sA;
					dBA = dst[px+2]*dA;

					dst[px  ] = 255 * (sRA + dRA - sRA*dRA ) / dA2;
					dst[px+1] = 255 * (sGA + dGA - sGA*dGA ) / dA2;
					dst[px+2] = 255 * (sBA + dBA - sBA*dBA ) / dA2;
				}
			break;
			case 'add':
				for (var px=0;px<len;px+=4){
					sA = src[px+3]/255;
					dA = dst[px+3]/255;
					dst[px+3] = (sA + dA*(1-sA))*255;
					dst[px  ] = src[px  ]*sA+dst[px  ]*dA;
					dst[px+1] = src[px+1]*sA+dst[px+1]*dA;
					dst[px+2] = src[px+2]*sA+dst[px+2]*dA;
				}
			break;
			case 'multiply':
				for (var px=0;px<len;px+=4){
					sA = src[px+3]/255;
					dA = dst[px+3]/255;
					dst[px+3] = (sA+dA-sA*dA)*255;
					dst[px  ] = src[px  ]*sA*dst[px  ]*dA;
					dst[px+1] = src[px+1]*sA+dst[px+1]*dA;
					dst[px+2] = src[px+2]*sA+dst[px+2]*dA;
				}
			break;
			case 'difference':
				for (var px=0;px<len;px+=4){
					sA = src[px+3]/255;
					dA = dst[px+3]/255;
					dst[px+3] = (sA + dA*(1-sA))*255;
					dst[px  ] = (src[px  ]>dst[px  ]) ? (src[px  ]-dst[px  ]) : (dst[px  ]-src[px  ]);
					dst[px+1] = (src[px+1]>dst[px+1]) ? (src[px+1]-dst[px+1]) : (dst[px+1]-src[px+1]);
					dst[px+2] = (src[px+2]>dst[px+2]) ? (src[px+2]-dst[px+2]) : (dst[px+2]-src[px+2]);
				}
			break;
			default:
				// Unsupported blend mode
				for (var px=0;px<len;px+=4){
					dst[px] = dst[px+3] = 255;
					dst[px+1] = px%8==0 ? 255 : 0;
					dst[px+2] = px%8==0 ? 0 : 255;
				}
		}
		dstD.data = dst;
		destContext.putImageData(dstD,offsets.destX,offsets.destY);
	};
}<|endoftext|>


<commit_before>
var fs = require('fs');
var path = require('path');
var moment = require('moment');
var utils = require('../utils.js');

var value;

var date = module.exports = function(){

};

date.prototype.getValue = function(){

	return value;

};

date.prototype.setValue = function(str){

	value = null;
	str = utils.trim(str).toLowerCase();

	var possibleDateDividers = [' ','-','/'];

	if (!utils.isSet(str)){
		value = null;
	} else if (str === 'today'){
		value = moment();
	} else if (str === 'yesterday'){
		value = moment().subtract(1, 'days');
	} else if (str === 'tomorrow'){
		value = moment().add(1, 'days');
	} else {
		// Failed to parse
		return new Error('Unable to interpret "'+str+'" as a date');
	}
};

date.prototype.isEmpty = function(){
	return value === null;
};

date.prototype.readable = function(){

	return value === null ? '' : value.format('dddd MMMM Do YYYY');

};

date.prototype.inputHelp = function(){

	return 'Enter a date. Eg "today", "yesterday", "23/12", "5/5/99"';

};

<commit_msg>Flexible date entry<commit_after>
var fs = require('fs');
var path = require('path');
var moment = require('moment');
var utils = require('../utils.js');

var value;
var MONTHS = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];
var DAY_SUFFIXES = ['st','nd','rd','th'];

var _date = module.exports = function(){

};

_date.prototype.getValue = function(){

	return value;

};

_date.prototype.setValue = function(str){

	value = null;
	str = utils.trim(str).toLowerCase();

	if (!utils.isSet(str)){
		value = null;
	} else if (str === 'today'){
		value = moment();
	} else if (str === 'yesterday'){
		value = moment().subtract(1, 'days');
	} else if (str === 'tomorrow'){
		value = moment().add(1, 'days');
	} else {

		var possibleDateDividers = [' ','-','/','.'];

		for (var i = 0; i < possibleDateDividers.length; i++){
			str = str.split(possibleDateDividers[i]).join('~');
		}
		str = str.replace(/~{2}?/g, '~');
		str = str.replace(/^~*|~*$/g, '');

		var eles = str.split('~');

		var date = {'d':0, 'm':0, 'y':0};

		if (eles.length === 1){

			var chunk = eles[0];

			var stillLooking = true;
			// Split by month name
			for (var m = 0; m < MONTHS.length; m++){
				var monthSplit = chunk.split(MONTHS[m]);
				if (monthSplit.length === 2){
					stillLooking = false;
					eles = [monthSplit[0], MONTHS[m]];
					var potentialYear = utils.removeNonNumericChars(monthSplit[1]);
					if (potentialYear.length > 0){
						eles.push(potentialYear);
					}
				}
			}

			// An 8 digit number is assumed as being YMD
			if (stillLooking && chunk.match(/^([0-9]{8})$/)){
				stillLooking = false;
				eles = [chunk.substr(6,2), chunk.substr(4,2), chunk.substr(0,4)];
			}

			// A 4 digit is DM
			if (stillLooking && chunk.match(/^([0-9]{4})$/)){
				stillLooking = false;
				eles = [chunk.substr(0,2),chunk.substr(2,2)];
			}

		}

		if (eles.length === 2){
			// Current year is 3rd ele
			eles.push(String(moment().year()));
		}

		if (eles.length !== 3){
			return new Error('Unable to interpret "'+str+'" as a date');
		}

		// Loop 3 times, getting more prescriptive each iteration
		for (var k = 0; k < 3; k++){

			while (true){
				var anyResolved = false;
				for (var j = 0; j < eles.length; j++){

					if (eles[j]){

						var pos = {d:date.d===0,m:date.m===0,y:date.y===0};

						if (k === 1){
							// Guess based on element order

							if (j === 2){
								pos.d = false;
								pos.m = false;
							} else {
								pos.y = false;
							}

						} else if (k === 2){
							if (j === 0){
								pos.m = false;
								pos.y = false;
							} else if (j === 1){
								pos.d = false;
								pos.y = false;
							} else if (j === 2){
								pos.d = false;
								pos.m = false;
							}
						}

						var result = _date.interpretDateElement(eles[j],pos.d,pos.m, pos.y);
						if (result.resolved){
							anyResolved = true;
							date[result.type] = result.value;
							eles[j] = null;
						}
					}
				}
				if (!anyResolved){
					break;
				}
			}
			if (date.d > 0 && date.m > 0 && date.y > 0){
				break;
			}
		}

		console.log(date);

		// Loop through each ele - seeing if each can be determined as a day, month or year

		// Failed to parse
		return new Error('Unable to interpret "'+str+'" as a date');
	}
};

_date.prototype.isEmpty = function(){
	return value === null;
};

_date.prototype.readable = function(){

	return value === null ? '' : value.format('dddd MMMM Do YYYY');

};

_date.prototype.inputHelp = function(){

	return 'Enter a date. Eg "today", "yesterday", "23/12", "20141225", "4May10", "2312", "5/5/99", 31February1918", "3jun", "24 June 2015", "5th Sep", "2014-12-32", "2014 12 32", "31/12/1999"';

};

// Note: Month values are 1 indexed
_date.interpretDateElement = function(str, possibleDay, possibleMonth, possibleYear){

	// 'd','m','y'

	var i, num;
	if (possibleMonth){
		// Check for a month name
		for (i = 0; i < MONTHS.length; i++){
			if (str.substr(0, MONTHS[i].length) === MONTHS[i]){
				return {type:'m', resolved:true, value:i+1};
			}
		}
	}

	if (possibleDay){
		for (i = 0 ; i < DAY_SUFFIXES.length; i++){
			if (str.substr(-DAY_SUFFIXES[i].length) === DAY_SUFFIXES[i]){
				str = str.substr(0, str.length - DAY_SUFFIXES[i].length);
				num = Number(str);
				if (!isNaN(num) && num > 0 && num <= 31){
					num = Math.round(num);
					return {type:'d', resolved:true, value:num};
				}
			}
		}
	}

	// 4 digit year
	if (possibleYear){
		num = Number(str);
		if (!isNaN(num) && num > 1900 && num <= 9999){
			num = Math.round(num);
			return {type:'y', resolved:true, value:num};
		}
	}

	// Day specific range
	if (possibleDay && !possibleYear){
		num = Number(str);
		if (!isNaN(num) && num > 12 && num <= 31){
			num = Math.round(num);
			return {type:'d', resolved:true, value:num};
		}
	}

	// Year only (2 digits)
	if (possibleYear && !possibleDay && !possibleMonth){
		num = Number(str);
		if (!isNaN(num) && num >= 0 && num <= 99){
			num = Math.round(num);
			if (num > 50){
				num += 1900;
			} else {
				num += 2000;
			}
			return {type:'y', resolved:true, value:num};
		}
	}

	// Month only
	if (possibleMonth && !possibleDay && !possibleYear){
		num = Number(str);
		if (!isNaN(num) && num >= 1 && num <= 12){
			num = Math.round(num);
			return {type:'m', resolved:true, value:num};
		}
	}

	// Day only
	if (possibleDay && !possibleMonth && !possibleYear){
		num = Number(str);
		if (!isNaN(num) && num >= 1 && num <= 31){
			num = Math.round(num);
			return {type:'d', resolved:true, value:num};
		}
	}

	return {resolved:false};

};

<|endoftext|>