<commit_before>'use strict'

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

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

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

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

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

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

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

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

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

            var getDeliveryderPromise = this.collection.singleOrDefault({
                "$and": [{
                    _id: {
                        '$ne': new ObjectId(valid._id)
                    }
                }, {
                        "no": valid.no
                    }]
            });
            Promise.all([getDeliveryderPromise])
                .then(results => {
                    var _module = results[0];
                    if (!valid.no || valid.no == '')
                        errors["no"] = i18n.__("DeliveryOrder.no.isRequired:%s is required", i18n.__("DeliveryOrder.no._:No"));//"Nomor surat jalan tidak boleh kosong";
                    else if (_module)
                        errors["no"] = i18n.__("DeliveryOrder.no.isExists:%s is already exists", i18n.__("DeliveryOrder.no._:No"));//"Nomor surat jalan sudah terdaftar";

                    if (!valid.date || valid.date == '')
                        errors["date"] = i18n.__("DeliveryOrder.date.isRequired:%s is required", i18n.__("DeliveryOrder.date._:Date"));//"Tanggal surat jalan tidak boleh kosong";
                    else if (valid.date > now)
                        errors["date"] = i18n.__("DeliveryOrder.date.isGreater:%s is greater than today", i18n.__("DeliveryOrder.date._:Date"));//"Tanggal surat jalan tidak boleh lebih besar dari tanggal hari ini";
                    if (!valid.supplierDoDate || valid.supplierDoDate == '')
                        errors["supplierDoDate"] = i18n.__("DeliveryOrder.supplierDoDate.isRequired:%s is required", i18n.__("DeliveryOrder.supplierDoDate._:SupplierDoDate"));//"Tanggal surat jalan supplier tidak boleh kosong";

                    if (!valid.supplierId || valid.supplierId.toString() == '')
                        errors["supplier"] = i18n.__("DeliveryOrder.supplier.name.isRequired:%s is required", i18n.__("DeliveryOrder.supplier.name._:NameSupplier")); //"Nama supplier tidak boleh kosong";

                    if (valid.items && valid.items.length < 1) {
                        errors["items"] = i18n.__("DeliveryOrder.items.isRequired:%s is required", i18n.__("DeliveryOrder.items.name._:Items")); //"Harus ada minimal 1 nomor po eksternal";
                    } else {
                        var deliveryOrderItemErrors = [];
                        var deliveryOrderItemHasError = false;
                        for (var doItem of valid.items || []) {
                            var purchaseOrderExternalItemErrors = [];
                            var purchaseOrderExternalItemHasErrors = false;
                            var purchaseOrderExternalError = {};

                            if (!doItem.purchaseOrderExternal) {
                                purchaseOrderExternalItemHasErrors = true;
                                purchaseOrderExternalError["purchaseOrderExternal"] = i18n.__("DeliveryOrder.items.purchaseOrderExternal.isRequired:%s is required", i18n.__("DeliveryOrder.items.purchaseOrderExternal._:PurchaseOrderExternal")); //"Purchase order external tidak boleh kosong";
                            }

                            for (var doFulfillment of doItem.fulfillments || []) {
                                var fulfillmentError = {};
                                if (!doFulfillment.deliveredQuantity || doFulfillment.deliveredQuantity == 0) {
                                    purchaseOrderExternalItemHasErrors = true;
                                    fulfillmentError["deliveredQuantity"] = i18n.__("DeliveryOrder.items.fulfillments.deliveredQuantity.isRequired:%s is required or not 0", i18n.__("DeliveryOrder.items.fulfillments.deliveredQuantity._:DeliveredQuantity")); //"Jumlah barang diterima tidak boleh kosong";
                                }
                                else if (doFulfillment.deliveredQuantity > doFulfillment.purchaseOrderQuantity) {
                                    purchaseOrderExternalItemHasErrors = true;
                                    fulfillmentError["deliveredQuantity"] = i18n.__("DeliveryOrder.items.fulfillments.deliveredQuantity.isGreater:%s is greater than purchaseOrderQuantity", i18n.__("DeliveryOrder.items.fulfillments.deliveredQuantity._:DeliveredQuantity")); //"Jumlah barang diterima tidak boleh lebih besar dari jumlah barang di po eksternal";
                                }
                                purchaseOrderExternalItemErrors.push(fulfillmentError);
                            }
                            if (purchaseOrderExternalItemHasErrors) {
                                deliveryOrderItemHasError = true;
                                purchaseOrderExternalError["fulfillments"] = purchaseOrderExternalItemErrors;
                            }
                            deliveryOrderItemErrors.push(purchaseOrderExternalError);
                        }
                        if (purchaseOrderExternalItemHasErrors)
                            errors["items"] = deliveryOrderItemErrors;
                    }

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

                    valid.supplierId = new ObjectId(valid.supplierId);
                    valid.supplier._id = new ObjectId(valid.supplier._id);
                    for (var item of valid.items) {
                        item.purchaseOrderExternalId = new ObjectId(item.purchaseOrderExternalId);
                        item.purchaseOrderExternal._id = new ObjectId(item.purchaseOrderExternal._id);
                        for (var fulfillment of item.fulfillments) {
                            fulfillment.purchaseOrderId = new ObjectId(fulfillment.purchaseOrderId);
                            fulfillment.purchaseOrder._id = new ObjectId(fulfillment.purchaseOrder._id);
                            fulfillment.productId = new ObjectId(fulfillment.productId);
                            fulfillment.product._id = new ObjectId(fulfillment.product._id);
                        }
                    }
                    if (!valid.stamp)
                        valid = new DeliveryOrder(valid);

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

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

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

                                                        var totalRealize = 0;
                                                        for (var poItemFulfillment of poItem.fulfillments) {
                                                            totalRealize += poItemFulfillment.deliveredQuantity;
                                                        }
                                                        poItem.realizationQuantity = totalRealize;
                                                        if (poItem.realizationQuantity == poItem.dealQuantity)
                                                            poItem.isClosed = true;
                                                        else
                                                            poItem.isClosed = false;
                                                        break;
                                                    }
                                                }
                                            }
                                            for (var poItem of purchaseOrder.items) {
                                                if (poItem.isClosed == true)
                                                    purchaseOrder.isClosed = true;
                                                else {
                                                    purchaseOrder.isClosed = false;
                                                    break;
                                                }
                                            }
                                            tasks.push(this.purchaseOrderManager.update(purchaseOrder));
                                        }

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

                                                }

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

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

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

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

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

    getQueryBySupplierAndUnit(_paging) {
        var supplierId = _paging.filter.supplierId;
        var unitId = _paging.filter.unitId;

        var filter = {
            "_deleted": false,
            "supplierId": new ObjectId(supplierId),
            "items": {
                $elemMatch: {
                    "fulfillments": {
                        $elemMatch: {
                            "purchaseOrder.unitId": new ObjectId(unitId)
                        }
                    }
                }
            }
        };

        var query = _paging.keyword ? {
            '$and': [filter]
        } : filter;

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

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

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

            var filterUnitDivision = {
                "unit.division": {
                    '$regex': regex
                }
            };
            var filterUnitSubDivision = {
                "unit.subDivision": {
                    '$regex': regex
                }
            };

            var filterDeliveryOrder = {
                "deliveryOrder.no": {
                    '$regex': regex
                }
            };

            var $or = {
                '$or': [filterNo, filterSupplierName, filterUnitDivision, filterUnitSubDivision, filterDeliveryOrder]
            };

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

        return query;
    }

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

        return new Promise((resolve, reject) => {
            var query = this.getQueryBySupplierAndUnit(_paging);
            this.collection.find(query).toArray()
                .then(DeliveryOrders => {
                    resolve(DeliveryOrders);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

}<commit_msg>make _id when create become objectId in delivery-order-manager<commit_after>'use strict'

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

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

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

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

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

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

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

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

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

            var getDeliveryderPromise = this.collection.singleOrDefault({
                "$and": [{
                    _id: {
                        '$ne': new ObjectId(valid._id)
                    }
                }, {
                        "no": valid.no
                    }]
            });
            Promise.all([getDeliveryderPromise])
                .then(results => {
                    var _module = results[0];
                    if (!valid.no || valid.no == '')
                        errors["no"] = i18n.__("DeliveryOrder.no.isRequired:%s is required", i18n.__("DeliveryOrder.no._:No"));//"Nomor surat jalan tidak boleh kosong";
                    else if (_module)
                        errors["no"] = i18n.__("DeliveryOrder.no.isExists:%s is already exists", i18n.__("DeliveryOrder.no._:No"));//"Nomor surat jalan sudah terdaftar";

                    if (!valid.date || valid.date == '')
                        errors["date"] = i18n.__("DeliveryOrder.date.isRequired:%s is required", i18n.__("DeliveryOrder.date._:Date"));//"Tanggal surat jalan tidak boleh kosong";
                    else if (valid.date > now)
                        errors["date"] = i18n.__("DeliveryOrder.date.isGreater:%s is greater than today", i18n.__("DeliveryOrder.date._:Date"));//"Tanggal surat jalan tidak boleh lebih besar dari tanggal hari ini";
                    if (!valid.supplierDoDate || valid.supplierDoDate == '')
                        errors["supplierDoDate"] = i18n.__("DeliveryOrder.supplierDoDate.isRequired:%s is required", i18n.__("DeliveryOrder.supplierDoDate._:SupplierDoDate"));//"Tanggal surat jalan supplier tidak boleh kosong";

                    if (!valid.supplierId || valid.supplierId.toString() == '')
                        errors["supplier"] = i18n.__("DeliveryOrder.supplier.name.isRequired:%s is required", i18n.__("DeliveryOrder.supplier.name._:NameSupplier")); //"Nama supplier tidak boleh kosong";

                    if (valid.items && valid.items.length < 1) {
                        errors["items"] = i18n.__("DeliveryOrder.items.isRequired:%s is required", i18n.__("DeliveryOrder.items.name._:Items")); //"Harus ada minimal 1 nomor po eksternal";
                    } else {
                        var deliveryOrderItemErrors = [];
                        var deliveryOrderItemHasError = false;
                        for (var doItem of valid.items || []) {
                            var purchaseOrderExternalItemErrors = [];
                            var purchaseOrderExternalItemHasErrors = false;
                            var purchaseOrderExternalError = {};

                            if (!doItem.purchaseOrderExternal) {
                                purchaseOrderExternalItemHasErrors = true;
                                purchaseOrderExternalError["purchaseOrderExternal"] = i18n.__("DeliveryOrder.items.purchaseOrderExternal.isRequired:%s is required", i18n.__("DeliveryOrder.items.purchaseOrderExternal._:PurchaseOrderExternal")); //"Purchase order external tidak boleh kosong";
                            }

                            for (var doFulfillment of doItem.fulfillments || []) {
                                var fulfillmentError = {};
                                if (!doFulfillment.deliveredQuantity || doFulfillment.deliveredQuantity == 0) {
                                    purchaseOrderExternalItemHasErrors = true;
                                    fulfillmentError["deliveredQuantity"] = i18n.__("DeliveryOrder.items.fulfillments.deliveredQuantity.isRequired:%s is required or not 0", i18n.__("DeliveryOrder.items.fulfillments.deliveredQuantity._:DeliveredQuantity")); //"Jumlah barang diterima tidak boleh kosong";
                                }
                                else if (doFulfillment.deliveredQuantity > doFulfillment.purchaseOrderQuantity) {
                                    purchaseOrderExternalItemHasErrors = true;
                                    fulfillmentError["deliveredQuantity"] = i18n.__("DeliveryOrder.items.fulfillments.deliveredQuantity.isGreater:%s is greater than purchaseOrderQuantity", i18n.__("DeliveryOrder.items.fulfillments.deliveredQuantity._:DeliveredQuantity")); //"Jumlah barang diterima tidak boleh lebih besar dari jumlah barang di po eksternal";
                                }
                                purchaseOrderExternalItemErrors.push(fulfillmentError);
                            }
                            if (purchaseOrderExternalItemHasErrors) {
                                deliveryOrderItemHasError = true;
                                purchaseOrderExternalError["fulfillments"] = purchaseOrderExternalItemErrors;
                            }
                            deliveryOrderItemErrors.push(purchaseOrderExternalError);
                        }
                        if (purchaseOrderExternalItemHasErrors)
                            errors["items"] = deliveryOrderItemErrors;
                    }

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

                    valid.supplierId = new ObjectId(valid.supplierId);
                    valid.supplier._id = new ObjectId(valid.supplier._id);
                    for (var item of valid.items) {
                        item.purchaseOrderExternalId = new ObjectId(item.purchaseOrderExternalId);
                        item.purchaseOrderExternal._id = new ObjectId(item.purchaseOrderExternal._id);
                        item.purchaseOrderExternal.supplier._id = new ObjectId(item.purchaseOrderExternal.supplier._id);
                        item.purchaseOrderExternal.currency._id = new ObjectId(item.purchaseOrderExternal.currency._id);
                        if (item.purchaseOrderExternal.vat) {
                            item.purchaseOrderExternal.vat._id = new ObjectId(item.purchaseOrderExternal.vat._id);
                        }
                        for (var exItem of item.purchaseOrderExternal.items) {
                            exItem.purchaseRequest.unit._id = new ObjectId(exItem.purchaseRequest.unit._id);
                            exItem.purchaseRequest.category._id = new ObjectId(exItem.purchaseRequest.category._id);
                            exItem.purchaseRequest.unitId = new ObjectId(exItem.purchaseRequest.unitId);
                            exItem.purchaseRequest.categoryId = new ObjectId(exItem.purchaseRequest.categoryId);
                            if (exItem.sourcePurchaseOrder) {
                                exItem.sourcePurchaseOrder._id = new ObjectId(exItem.sourcePurchaseOrder._id);
                                exItem.sourcePurchaseOrder.purchaseRequest.unit._id = new ObjectId(exItem.sourcePurchaseOrder.purchaseRequest.unit._id);
                                exItem.sourcePurchaseOrder.purchaseRequest.category._id = new ObjectId(exItem.sourcePurchaseOrder.purchaseRequest.category._id);
                                exItem.sourcePurchaseOrder.purchaseRequest.unitId = new ObjectId(exItem.sourcePurchaseOrder.purchaseRequest.unitId);
                                exItem.sourcePurchaseOrder.purchaseRequest.categoryId = new ObjectId(exItem.sourcePurchaseOrder.purchaseRequest.categoryId);
                                exItem.sourcePurchaseOrder.unit._id = new ObjectId(exItem.sourcePurchaseOrder.unit._id);
                                exItem.sourcePurchaseOrder.category._id = new ObjectId(exItem.sourcePurchaseOrder.category._id);
                                exItem.sourcePurchaseOrder.unitId = new ObjectId(exItem.sourcePurchaseOrder.unitId);
                                exItem.sourcePurchaseOrder.categoryId = new ObjectId(exItem.sourcePurchaseOrder.categoryId);

                                for (var soItem of exItem.sourcePurchaseOrder.items) {
                                    soItem.product._id = new ObjectId(soItem.product._id);
                                    soItem.product.uom._id = new ObjectId(soItem.product.uom._id);
                                    soItem.defaultUom._id = new ObjectId(soItem.defaultUom._id);
                                }
                            }
                            exItem.unitId = new ObjectId(exItem.unitId);
                            exItem.unit._id = new ObjectId(exItem.unit._id);
                            exItem.categoryId = new ObjectId(exItem.categoryId);
                            exItem.category._id = new ObjectId(exItem.category._id);
                            for (var poItem of exItem.items) {
                                poItem.product._id = new ObjectId(poItem.product._id);
                                poItem.product.uom._id = new ObjectId(poItem.product.uom._id);
                                poItem.defaultUom._id = new ObjectId(poItem.defaultUom._id);
                                poItem.dealUom._id = new ObjectId(poItem.dealUom._id);
                            }
                        }

                        for (var fulfillment of item.fulfillments) {
                            fulfillment.purchaseOrderId = new ObjectId(fulfillment.purchaseOrderId);
                            fulfillment.purchaseOrder._id = new ObjectId(fulfillment.purchaseOrder._id);
                            fulfillment.productId = new ObjectId(fulfillment.productId);
                            fulfillment.product._id = new ObjectId(fulfillment.product._id);
                        }
                    }
                    if (!valid.stamp)
                        valid = new DeliveryOrder(valid);

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

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

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

                                                        var totalRealize = 0;
                                                        for (var poItemFulfillment of poItem.fulfillments) {
                                                            totalRealize += poItemFulfillment.deliveredQuantity;
                                                        }
                                                        poItem.realizationQuantity = totalRealize;
                                                        if (poItem.realizationQuantity == poItem.dealQuantity)
                                                            poItem.isClosed = true;
                                                        else
                                                            poItem.isClosed = false;
                                                        break;
                                                    }
                                                }
                                            }
                                            for (var poItem of purchaseOrder.items) {
                                                if (poItem.isClosed == true)
                                                    purchaseOrder.isClosed = true;
                                                else {
                                                    purchaseOrder.isClosed = false;
                                                    break;
                                                }
                                            }
                                            tasks.push(this.purchaseOrderManager.update(purchaseOrder));
                                        }

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

                                                }

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

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

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

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

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

    getQueryBySupplierAndUnit(_paging) {
        var supplierId = _paging.filter.supplierId;
        var unitId = _paging.filter.unitId;

        var filter = {
            "_deleted": false,
            "supplierId": new ObjectId(supplierId),
            "items": {
                $elemMatch: {
                    "fulfillments": {
                        $elemMatch: {
                            "purchaseOrder.unitId": new ObjectId(unitId)
                        }
                    }
                }
            }
        };

        var query = _paging.keyword ? {
            '$and': [filter]
        } : filter;

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

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

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

            var filterUnitDivision = {
                "unit.division": {
                    '$regex': regex
                }
            };
            var filterUnitSubDivision = {
                "unit.subDivision": {
                    '$regex': regex
                }
            };

            var filterDeliveryOrder = {
                "deliveryOrder.no": {
                    '$regex': regex
                }
            };

            var $or = {
                '$or': [filterNo, filterSupplierName, filterUnitDivision, filterUnitSubDivision, filterDeliveryOrder]
            };

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

        return query;
    }

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

        return new Promise((resolve, reject) => {
            var query = this.getQueryBySupplierAndUnit(_paging);
            this.collection.find(query).toArray()
                .then(DeliveryOrders => {
                    resolve(DeliveryOrders);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

}<|endoftext|>


<commit_before>import _ from "lodash";
import fsPath from "path";
import Promise from "bluebird";
import express from "express";
import webpack from "webpack";
import webpackMiddleware from "webpack-dev-middleware";
import webpackHotMiddleware from "webpack-hot-middleware";
import * as config from "../webpack-config";
import * as serverMethods from "./serverMethods";
import bdd from "../shared/bdd";

const parseSpecs = (paths) => {
    bdd.register();
    paths.forEach(path => { require(path); });
    bdd.unregister();
};

/**
 * Starts the UIHarness within a development server.
 * @param {object} options: Configuration settings.
 *                          If a {string/array} is passed, that value is set as the `entry`
 *
 *                          - entry: A string or array of strings to entry points of files
 *                                   to pass to WebPack to build for the client.
 *                          - port: The port to run on (default:8080).
 *                          - env:  The environment to run in ("development" / "production").
 * @param callback: Invokd when the server has started.
 */
export const start = (options = {}, callback) => {
  console.log("Starting...");

  const PORT = options.port || 8080;
  const ENV = options.env || process.env.NODE_ENV || "development"
  const IS_PRODUCTION = ENV === "production";
  const webpackConfig = config.browser({ port: PORT, env: ENV });

  // Prepare the server.
  const app = express();
  const startListening = () => {
      app.listen(PORT, () => {
            console.log("Started.");
            console.log("");
            console.log("UIHarness");
            console.log(" - port:", PORT);
            console.log(" - env: ", ENV);
            console.log("");
            if (_.isFunction(callback)) { callback(); }
      });
    };

  // Setup routing.
  const get = (route, file) => {
      file = fsPath.join(__dirname, `../../public/${ file || route }`);
      app.get(route, (req, res) => { res.sendFile(file); });
  };
  get("/", "index.html");
  get("/normalize.css");
  get("/favicon.ico");
  if (IS_PRODUCTION) {
    get("/public/bundle.js", "bundle.js");
  }

  // Ensure the options is an object.
  if (_.isString(options) || _.isArray(options)) {
    // A string or object was given, convert it to the "entry" option.
    options = { entry: options };
  }

  // Prepare entry paths for the WebPack compiler.
  let entry = options.entry || [];
  if (!_.isArray(entry)) { entry = [entry]; }
  entry = entry.map(path => { return _.startsWith(path, ".") ? fsPath.resolve(path) : path; });
  entry.forEach(path => { webpackConfig.entry.push(path); });

  // Iniitalize the [describe/it] statements.
  parseSpecs(entry);

  // Configure the server methods (REST API).
  // serverMethods.init({ connect:app });

  // Prepare webpack JS.
  if (IS_PRODUCTION) {
    // Compile and minify webpack JS for production.
    console.log("webpack bundling...");
    webpack(webpackConfig, (err, stats) => {
      if (err) { throw err; }
      startListening();
    });

  } else {
    // Create the WebPack compiler and "hot-reloading" dev server.
    const compiler = webpack(webpackConfig);
    app.use(webpackMiddleware(compiler, config.devServer({ port: PORT })));
    app.use(webpackHotMiddleware(compiler));
    startListening();
  }
};
<commit_msg>console<commit_after>import _ from "lodash";
import fsPath from "path";
import Promise from "bluebird";
import express from "express";
import webpack from "webpack";
import webpackMiddleware from "webpack-dev-middleware";
import webpackHotMiddleware from "webpack-hot-middleware";
import * as config from "../webpack-config";
import * as serverMethods from "./serverMethods";
import bdd from "../shared/bdd";

const parseSpecs = (paths) => {
    bdd.register();
    paths.forEach(path => { require(path); });
    bdd.unregister();
};

/**
 * Starts the UIHarness within a development server.
 * @param {object} options: Configuration settings.
 *                          If a {string/array} is passed, that value is set as the `entry`
 *
 *                          - entry: A string or array of strings to entry points of files
 *                                   to pass to WebPack to build for the client.
 *                          - port: The port to run on (default:8080).
 *                          - env:  The environment to run in ("development" / "production").
 * @param callback: Invokd when the server has started.
 */
export const start = (options = {}, callback) => {
  console.log("Starting...");

  const PORT = options.port || 8080;
  const ENV = options.env || process.env.NODE_ENV || "development"
  const IS_PRODUCTION = ENV === "production";
  const webpackConfig = config.browser({ port: PORT, env: ENV });

  // Prepare the server.
  const app = express();
  const startListening = () => {
      app.listen(PORT, () => {
            console.log("Started.");
            console.log("");
            console.log("UIHarness");
            console.log(" - port:", PORT);
            console.log(" - env: ", ENV);
            console.log("");
            if (_.isFunction(callback)) { callback(); }
      });
    };

  // Setup routing.
  const get = (route, file) => {
      file = fsPath.join(__dirname, `../../public/${ file || route }`);
      app.get(route, (req, res) => { res.sendFile(file); });
  };
  get("/", "index.html");
  get("/normalize.css");
  get("/favicon.ico");
  if (IS_PRODUCTION) {
    get("/public/bundle.js", "bundle.js");
  }

  // Ensure the options is an object.
  if (_.isString(options) || _.isArray(options)) {
    // A string or object was given, convert it to the "entry" option.
    options = { entry: options };
  }

  // Prepare entry paths for the WebPack compiler.
  let entry = options.entry || [];
  if (!_.isArray(entry)) { entry = [entry]; }
  entry = entry.map(path => { return _.startsWith(path, ".") ? fsPath.resolve(path) : path; });
  entry.forEach(path => { webpackConfig.entry.push(path); });

  // Iniitalize the [describe/it] statements.
  parseSpecs(entry);

  // Configure the server methods (REST API).
  // serverMethods.init({ connect:app });

  // Prepare webpack JS.
  if (IS_PRODUCTION) {
    // Compile and minify webpack JS for production.
    console.log("webpack bundling...");
    console.log("-------------------------------------------");
    console.log(webpackConfig);
    console.log("");
    webpack(webpackConfig, (err, stats) => {
      if (err) { throw err; }
      startListening();
    });

  } else {
    // Create the WebPack compiler and "hot-reloading" dev server.
    const compiler = webpack(webpackConfig);
    app.use(webpackMiddleware(compiler, config.devServer({ port: PORT })));
    app.use(webpackHotMiddleware(compiler));
    startListening();
  }
};
<|endoftext|>


<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 PurchaseOrder = DLModels.purchasing.PurchaseOrder;
var generateCode = require('../../utils/code-generator');
var BaseManager = require('../base-manager');

module.exports = class PurchaseOrderManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.moduleId = 'PO';
        this.year = (new Date()).getFullYear().toString().substring(2, 4);
        this.collection = this.db.use(map.purchasing.collection.PurchaseOrder);
    }

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

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

            Promise.all([getPurchaseOrderPromise])
                .then(results => {
                    var _module = results[0];
                    var now = new Date();

                    if (valid.purchaseRequest) {
                        var itemError = {};
                        if (!valid.purchaseRequest.unit)
                            itemError["unit"] = "Nama unit yang mengajukan tidak boleh kosong";

                        if (!valid.purchaseRequest.category)
                            itemError["category"] = "Kategori tidak boleh kosong";

                        if (!valid.purchaseRequest.no)
                            itemError["no"] = "No. PR tidak boleh kosong";
                        else if (_module && _module.sourcePurchaseOrder == null && valid.sourcePurchaseOrder == null)
                            itemError["no"] = "No. PR sudah terdaftar";
                        //pending
                        // if (!valid.purchaseRequest.date)
                        //     itemError["date"] = "Tanggal PR tidak boleh kosong";
                        // else {
                        //     var _prDate = new Date(valid.purchaseRequest.date);
                        //     if (_prDate > now)
                        //         itemError["date"] = "Tanggal PR tidak boleh lebih besar dari tanggal hari ini";
                        // }

                        // if (valid.purchaseRequest.expectedDeliveryDate && valid.purchaseRequest.date) {
                        //     var _prDate = new Date(valid.purchaseRequest.date);
                        //     var _expectedDate = new Date(valid.purchaseRequest.expectedDeliveryDate);
                        //     if (_prDate > _expectedDate)
                        //         itemError["expectedDeliveryDate"] = "Tanggal PR tidak boleh lebih besar dari tanggal tersedia";
                        // }

                        for (var prop in itemError) {
                            errors["purchaseRequest"] = itemError;
                            break;
                        }
                    }

                    if (valid.items.length > 0) {
                        var itemErrors = [];
                        for (var item of valid.items) {
                            var itemError = {};

                            if (!item.product || !item.product._id)
                                itemError["product"] = "Nama barang tidak boleh kosong";
                            if (!item.defaultQuantity || item.defaultQuantity == 0)
                                itemError["defaultQuantity"] = "Jumlah default tidak boleh kosong";

                            if (valid.sourcePurchaseOrder != null) {
                                for (var sourcePoItem of valid.sourcePurchaseOrder.items) {
                                    if (item.product._id && item.defaultQuantity) {
                                        if (item.product._id == sourcePoItem.product._id) {
                                            if (item.defaultQuantity > sourcePoItem.defaultQuantity) {
                                                itemError["defaultQuantity"] = "Jumlah default tidak boleh lebih besar dari PO asal";
                                                break;
                                            } else if (item.defaultQuantity == sourcePoItem.defaultQuantity) {
                                                itemError["defaultQuantity"] = "Jumlah default tidak boleh sama dengan PO asal";
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            itemErrors.push(itemError);
                        }
                        for (var itemError of itemErrors) {
                            for (var prop in itemError) {
                                errors.items = itemErrors;
                                break;
                            }
                            if (errors.items)
                                break;
                        }

                    }
                    else {
                        errors["items"] = "Harus ada minimal 1 barang";
                    }

                    for (var prop in errors) {
                        var ValidationError = require('../../validation-error');
                        reject(new ValidationError('data does not pass validation', errors));
                    }

                    if (valid.purchaseRequest) {
                        valid.refNo = valid.purchaseRequest.no;
                        valid.unit = valid.purchaseRequest.unit;
                        valid.unitId = valid.purchaseRequest.unit._id;
                        valid.category = valid.purchaseRequest.category;
                        valid.categoryId = valid.purchaseRequest.category._id;
                        valid.date = valid.purchaseRequest.date;
                        valid.expectedDeliveryDate = valid.purchaseRequest.expectedDeliveryDate;
                    }
                    if (!valid.stamp)
                        valid = new PurchaseOrder(valid);

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

        });
    }

    _getQuery(paging) {
        var filter = {
            _deleted: false
        };

        var query = paging.keyword ? {
            '$and': [filter]
        } : filter;

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

            var filterRefPONo = {
                'refNo': {
                    '$regex': regex
                }
            };
            var filterPONo = {
                'no': {
                    '$regex': regex
                }
            };
            var filterBuyerName = {
                'buyer.name': {
                    '$regex': regex
                }
            };

            var $or = {
                '$or': [filterRefPONo, filterPONo, filterBuyerName]
            };

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

    _getQueryUnposted(_paging) {
        var filter = {
            _deleted: false,
            purchaseOrderExternalId: {}
        };

        var query = _paging.keyword ? {
            '$and': [filter]
        } : filter;

        if (_paging.keyword) {
            var regex = new RegExp(_paging.keyword, "i");
            var filterRefPONo = {
                'refNo': {
                    '$regex': regex
                }
            };
            var filterPONo = {
                'no': {
                    '$regex': regex
                }
            };

            var $or = {
                '$or': [filterRefPONo, filterPONo]
            };

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

        return query;
    }

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

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

            var query = this._getQueryUnposted(_paging);

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

    create(purchaseOrder) {
        purchaseOrder = new PurchaseOrder(purchaseOrder);

        return new Promise((resolve, reject) => {
            purchaseOrder.no = `${this.moduleId}${this.year}${generateCode()}`;
            this._validate(purchaseOrder)
                .then(validPurchaseOrderc => {
                    this.collection.insert(validPurchaseOrderc)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                })

        });
    }

    split(purchaseOrder) {
        return new Promise((resolve, reject) => {
            this.getSingleById(purchaseOrder.sourcePurchaseOrderId)
                .then(_purchaseOrder => {
                    purchaseOrder.sourcePurchaseOrder = _purchaseOrder;
                    purchaseOrder.sourcePurchaseOrderId = _purchaseOrder._id;
                    this._validate(purchaseOrder)
                        .then(validPurchaseOrder => {
                            delete validPurchaseOrder._id;
                            this.create(validPurchaseOrder)
                                .then(id => {
                                    this.getSingleById(validPurchaseOrder.sourcePurchaseOrderId)
                                        .then(sourcePo => {
                                            for (var item of validPurchaseOrder.items) {
                                                for (var sourceItem of sourcePo.items) {
                                                    if (item.product.code == sourceItem.product.code) {
                                                        sourceItem.defaultQuantity = sourceItem.defaultQuantity - item.defaultQuantity
                                                        break;
                                                    }
                                                }
                                            }

                                            sourcePo.items = sourcePo.items.filter((item, index) => {
                                                return item.defaultQuantity > 0;
                                            })

                                            this.update(sourcePo)
                                                .then(results => {
                                                    resolve(id);
                                                })
                                                .catch(e => {
                                                    reject(e);
                                                });
                                        })
                                        .catch(e => {
                                            reject(e);
                                        });
                                })
                                .catch(e => {
                                    reject(e);
                                });
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                });

        });
    }

    _getByPR(_purchaseRequestNo) {
        return new Promise((resolve, reject) => {
            if (_purchaseRequestNo === '')
                resolve(null);
            var query = {
                "purchaseRequest.no": _purchaseRequestNo,
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(module => {
                    resolve(module);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getDataPOMonitoringPembelian(unitId, categoryId, PODLNo, PRNo, supplierId, dateFrom, dateTo) {
        return new Promise((resolve, reject) => {
            var query;
            if (unitId != "undefined" && unitId != "" && categoryId != "undefined" && categoryId != "" && PODLNo != "undefined" && PODLNo != "" && PRNo != "undefined" && PRNo != "" && supplierId != "undefined" && supplierId != "" && dateFrom != "undefined" && dateFrom != "" && dateTo != "undefined" && dateTo != "") {
                query = {
                    unitId: unitId,
                    categoryId: categoryId,
                    PODLNo: PODLNo,
                    PRNo: PRNo,
                    supplierId: supplierId,
                    date:
                    {
                        $gte: dateFrom,
                        $lte: dateTo
                    },
                    _deleted: false
                };
            } else if (unitId != "undefined" && unitId != "" && categoryId != "undefined" && categoryId != "" && PODLNo != "undefined" && PODLNo != "" && PRNo != "undefined" && PRNo != "" && supplierId != "undefined" && supplierId != "") {
                query = {
                    unitId: unitId,
                    categoryId: categoryId,
                    PODLNo: PODLNo,
                    PRNo: PRNo,
                    supplierId: supplierId,
                    _deleted: false
                };
            } else if (unitId != "undefined" && unitId != "" && categoryId != "undefined" && categoryId != "" && PODLNo != "undefined" && PODLNo != "" && PRNo != "undefined" && PRNo != "") {
                query = {
                    unitId: unitId,
                    categoryId: categoryId,
                    PODLNo: PODLNo,
                    PRNo: PRNo,
                    _deleted: false
                };
            } else if (unitId != "undefined" && unitId != "" && categoryId != "undefined" && categoryId != "" && PODLNo != "undefined") {
                query = {
                    unitId: unitId,
                    categoryId: categoryId,
                    PODLNo: PODLNo,
                    _deleted: false
                };
            } else if (unitId != "undefined" && unitId != "" && categoryId != "undefined" && categoryId != "") {
                query = {
                    unitId: unitId,
                    categoryId: categoryId,
                    _deleted: false
                };
            } else
                if (unitId != "undefined" && unitId != "") {
                    query = {
                        unitId: unitId,
                        _deleted: false
                    };
                }
                else if (categoryId != "undefined" && categoryId != "") {
                    query = {
                        categoryId: categoryId,
                        _deleted: false
                    };
                } else if (PODLNo != "undefined" && PODLNo != "") {
                    query = {
                        PODLNo: PODLNo,
                        _deleted: false
                    };
                } else if (PRNo != "undefined" && PRNo != "") {
                    query = {
                        PRNo: PRNo,
                        _deleted: false
                    };
                } else if (supplierId != "undefined" && supplierId != "") {
                    query = {
                        supplierId: supplierId,
                        _deleted: false
                    };
                } else if (dateFrom != "undefined" && dateFrom != "" && dateTo != "undefined" && dateTo != "") {
                    query = {
                        date:
                        {
                            $gte: dateFrom,
                            $lte: dateTo
                        },
                        _deleted: false
                    };
                }
            this.collection
                .where(query)
                .execute()
                .then(PurchaseOrder => {
                    resolve(PurchaseOrder);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getDataPOUnit(startdate,enddate){
        return new Promise((resolve, reject) => {
             if (startdate != "undefined" && enddate != "undefined") {

                   this.collection.aggregate(
                       [{
                                $match: {
                                    $and: [
                                       {
                                           $and: [
                                            {
                                                "date": {
                                                $gte: startdate ,
                                                $lte: enddate   }
                                            },
                                            {
                                                "_deleted":false
                                            }

                                            ]
                                       },
                                       {
                                           "isPosted":true
                                       }
                                    ]

                                }
                            },
                            {
                                $unwind: "$purchaseOrderExternal.items"
                            },
                           {
                               $group:{
                                   _id: "$unit.division" ,
                                   "pricetotal":{$sum:{$multiply:["$purchaseOrderExternal.items.pricePerDealUnit","$purchaseOrderExternal.items.dealQuantity","$purchaseOrderExternal.currencyRate"]}}
                               }
                           }
                       ]
                       )
                        .toArray(function(err, result) {
                            assert.equal(err, null);
                            console.log(result);
                            resolve(result);
                        });

             }
         });

    }
}<commit_msg>updating report PO<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 PurchaseOrder = DLModels.purchasing.PurchaseOrder;
var generateCode = require('../../utils/code-generator');
var BaseManager = require('../base-manager');

module.exports = class PurchaseOrderManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.moduleId = 'PO';
        this.year = (new Date()).getFullYear().toString().substring(2, 4);
        this.collection = this.db.use(map.purchasing.collection.PurchaseOrder);
    }

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

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

            Promise.all([getPurchaseOrderPromise])
                .then(results => {
                    var _module = results[0];
                    var now = new Date();

                    if (valid.purchaseRequest) {
                        var itemError = {};
                        if (!valid.purchaseRequest.unit)
                            itemError["unit"] = "Nama unit yang mengajukan tidak boleh kosong";

                        if (!valid.purchaseRequest.category)
                            itemError["category"] = "Kategori tidak boleh kosong";

                        if (!valid.purchaseRequest.no)
                            itemError["no"] = "No. PR tidak boleh kosong";
                        else if (_module && _module.sourcePurchaseOrder == null && valid.sourcePurchaseOrder == null)
                            itemError["no"] = "No. PR sudah terdaftar";
                        //pending
                        // if (!valid.purchaseRequest.date)
                        //     itemError["date"] = "Tanggal PR tidak boleh kosong";
                        // else {
                        //     var _prDate = new Date(valid.purchaseRequest.date);
                        //     if (_prDate > now)
                        //         itemError["date"] = "Tanggal PR tidak boleh lebih besar dari tanggal hari ini";
                        // }

                        // if (valid.purchaseRequest.expectedDeliveryDate && valid.purchaseRequest.date) {
                        //     var _prDate = new Date(valid.purchaseRequest.date);
                        //     var _expectedDate = new Date(valid.purchaseRequest.expectedDeliveryDate);
                        //     if (_prDate > _expectedDate)
                        //         itemError["expectedDeliveryDate"] = "Tanggal PR tidak boleh lebih besar dari tanggal tersedia";
                        // }

                        for (var prop in itemError) {
                            errors["purchaseRequest"] = itemError;
                            break;
                        }
                    }

                    if (valid.items.length > 0) {
                        var itemErrors = [];
                        for (var item of valid.items) {
                            var itemError = {};

                            if (!item.product || !item.product._id)
                                itemError["product"] = "Nama barang tidak boleh kosong";
                            if (!item.defaultQuantity || item.defaultQuantity == 0)
                                itemError["defaultQuantity"] = "Jumlah default tidak boleh kosong";

                            if (valid.sourcePurchaseOrder != null) {
                                for (var sourcePoItem of valid.sourcePurchaseOrder.items) {
                                    if (item.product._id && item.defaultQuantity) {
                                        if (item.product._id == sourcePoItem.product._id) {
                                            if (item.defaultQuantity > sourcePoItem.defaultQuantity) {
                                                itemError["defaultQuantity"] = "Jumlah default tidak boleh lebih besar dari PO asal";
                                                break;
                                            } else if (item.defaultQuantity == sourcePoItem.defaultQuantity) {
                                                itemError["defaultQuantity"] = "Jumlah default tidak boleh sama dengan PO asal";
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            itemErrors.push(itemError);
                        }
                        for (var itemError of itemErrors) {
                            for (var prop in itemError) {
                                errors.items = itemErrors;
                                break;
                            }
                            if (errors.items)
                                break;
                        }

                    }
                    else {
                        errors["items"] = "Harus ada minimal 1 barang";
                    }

                    for (var prop in errors) {
                        var ValidationError = require('../../validation-error');
                        reject(new ValidationError('data does not pass validation', errors));
                    }

                    if (valid.purchaseRequest) {
                        valid.refNo = valid.purchaseRequest.no;
                        valid.unit = valid.purchaseRequest.unit;
                        valid.unitId = valid.purchaseRequest.unit._id;
                        valid.category = valid.purchaseRequest.category;
                        valid.categoryId = valid.purchaseRequest.category._id;
                        valid.date = valid.purchaseRequest.date;
                        valid.expectedDeliveryDate = valid.purchaseRequest.expectedDeliveryDate;
                    }
                    if (!valid.stamp)
                        valid = new PurchaseOrder(valid);

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

        });
    }

    _getQuery(paging) {
        var filter = {
            _deleted: false
        };

        var query = paging.keyword ? {
            '$and': [filter]
        } : filter;

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

            var filterRefPONo = {
                'refNo': {
                    '$regex': regex
                }
            };
            var filterPONo = {
                'no': {
                    '$regex': regex
                }
            };
            var filterBuyerName = {
                'buyer.name': {
                    '$regex': regex
                }
            };

            var $or = {
                '$or': [filterRefPONo, filterPONo, filterBuyerName]
            };

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

    _getQueryUnposted(_paging) {
        var filter = {
            _deleted: false,
            purchaseOrderExternalId: {}
        };

        var query = _paging.keyword ? {
            '$and': [filter]
        } : filter;

        if (_paging.keyword) {
            var regex = new RegExp(_paging.keyword, "i");
            var filterRefPONo = {
                'refNo': {
                    '$regex': regex
                }
            };
            var filterPONo = {
                'no': {
                    '$regex': regex
                }
            };

            var $or = {
                '$or': [filterRefPONo, filterPONo]
            };

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

        return query;
    }

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

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

            var query = this._getQueryUnposted(_paging);

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

    create(purchaseOrder) {
        purchaseOrder = new PurchaseOrder(purchaseOrder);

        return new Promise((resolve, reject) => {
            purchaseOrder.no = `${this.moduleId}${this.year}${generateCode()}`;
            this._validate(purchaseOrder)
                .then(validPurchaseOrderc => {
                    this.collection.insert(validPurchaseOrderc)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                })

        });
    }

    split(purchaseOrder) {
        return new Promise((resolve, reject) => {
            this.getSingleById(purchaseOrder.sourcePurchaseOrderId)
                .then(_purchaseOrder => {
                    purchaseOrder.sourcePurchaseOrder = _purchaseOrder;
                    purchaseOrder.sourcePurchaseOrderId = _purchaseOrder._id;
                    this._validate(purchaseOrder)
                        .then(validPurchaseOrder => {
                            delete validPurchaseOrder._id;
                            this.create(validPurchaseOrder)
                                .then(id => {
                                    this.getSingleById(validPurchaseOrder.sourcePurchaseOrderId)
                                        .then(sourcePo => {
                                            for (var item of validPurchaseOrder.items) {
                                                for (var sourceItem of sourcePo.items) {
                                                    if (item.product.code == sourceItem.product.code) {
                                                        sourceItem.defaultQuantity = sourceItem.defaultQuantity - item.defaultQuantity
                                                        break;
                                                    }
                                                }
                                            }

                                            sourcePo.items = sourcePo.items.filter((item, index) => {
                                                return item.defaultQuantity > 0;
                                            })

                                            this.update(sourcePo)
                                                .then(results => {
                                                    resolve(id);
                                                })
                                                .catch(e => {
                                                    reject(e);
                                                });
                                        })
                                        .catch(e => {
                                            reject(e);
                                        });
                                })
                                .catch(e => {
                                    reject(e);
                                });
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                });

        });
    }

    _getByPR(_purchaseRequestNo) {
        return new Promise((resolve, reject) => {
            if (_purchaseRequestNo === '')
                resolve(null);
            var query = {
                "purchaseRequest.no": _purchaseRequestNo,
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(module => {
                    resolve(module);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getDataPOMonitoringPembelian(unitId, categoryId, PODLNo, PRNo, supplierId, dateFrom, dateTo) {
        return new Promise((resolve, reject) => {
            var query;
            if (unitId != "undefined" && unitId != "" && categoryId != "undefined" && categoryId != "" && PODLNo != "undefined" && PODLNo != "" && PRNo != "undefined" && PRNo != "" && supplierId != "undefined" && supplierId != "" && dateFrom != "undefined" && dateFrom != "" && dateTo != "undefined" && dateTo != "") {
                query = {
                    unitId: unitId,
                    categoryId: categoryId,
                    PODLNo: PODLNo,
                    PRNo: PRNo,
                    supplierId: supplierId,
                    date:
                    {
                        $gte: dateFrom,
                        $lte: dateTo
                    },
                    _deleted: false
                };
            } else if (unitId != "undefined" && unitId != "" && categoryId != "undefined" && categoryId != "" && PODLNo != "undefined" && PODLNo != "" && PRNo != "undefined" && PRNo != "" && supplierId != "undefined" && supplierId != "") {
                query = {
                    unitId: unitId,
                    categoryId: categoryId,
                    PODLNo: PODLNo,
                    PRNo: PRNo,
                    supplierId: supplierId,
                    _deleted: false
                };
            } else if (unitId != "undefined" && unitId != "" && categoryId != "undefined" && categoryId != "" && PODLNo != "undefined" && PODLNo != "" && PRNo != "undefined" && PRNo != "") {
                query = {
                    unitId: unitId,
                    categoryId: categoryId,
                    PODLNo: PODLNo,
                    PRNo: PRNo,
                    _deleted: false
                };
            } else if (unitId != "undefined" && unitId != "" && categoryId != "undefined" && categoryId != "" && PODLNo != "undefined") {
                query = {
                    unitId: unitId,
                    categoryId: categoryId,
                    PODLNo: PODLNo,
                    _deleted: false
                };
            } else if (unitId != "undefined" && unitId != "" && categoryId != "undefined" && categoryId != "") {
                query = {
                    unitId: unitId,
                    categoryId: categoryId,
                    _deleted: false
                };
            } else
                if (unitId != "undefined" && unitId != "") {
                    query = {
                        unitId: unitId,
                        _deleted: false
                    };
                }
                else if (categoryId != "undefined" && categoryId != "") {
                    query = {
                        categoryId: categoryId,
                        _deleted: false
                    };
                } else if (PODLNo != "undefined" && PODLNo != "") {
                    query = {
                        PODLNo: PODLNo,
                        _deleted: false
                    };
                } else if (PRNo != "undefined" && PRNo != "") {
                    query = {
                        PRNo: PRNo,
                        _deleted: false
                    };
                } else if (supplierId != "undefined" && supplierId != "") {
                    query = {
                        supplierId: supplierId,
                        _deleted: false
                    };
                } else if (dateFrom != "undefined" && dateFrom != "" && dateTo != "undefined" && dateTo != "") {
                    query = {
                        date:
                        {
                            $gte: dateFrom,
                            $lte: dateTo
                        },
                        _deleted: false
                    };
                }
            this.collection
                .where(query)
                .execute()
                .then(PurchaseOrder => {
                    resolve(PurchaseOrder);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getDataPOUnit(startdate,enddate){
        return new Promise((resolve, reject) => {
             if (startdate != "undefined" && enddate != "undefined" && startdate != "" && enddate != "") {

                   this.collection.aggregate(
                       [{
                                $match: {
                                    $and: [
                                       {
                                           $and: [
                                            {
                                                "date": {
                                                $gte: startdate ,
                                                $lte: enddate   }
                                            },
                                            {
                                                "_deleted":false
                                            }

                                            ]
                                       },
                                       {
                                           "isPosted":true
                                       }
                                    ]

                                }
                            },
                            {
                                $unwind: "$items"
                            },
                           {
                               $group:{
                                   _id: "$unit.division" ,
                                   "pricetotal":{$sum:{$multiply:["$items.pricePerDealUnit","$items.dealQuantity","$currencyRate"]}}
                               }
                           }
                       ]
                       )
                        .toArray(function(err, result) {
                            assert.equal(err, null);
                            console.log(result);
                            resolve(result);
                        });

             }
             else{
                 this.collection.aggregate(
                       [{
                            $match: {

                                $and: [
                                        {
                                            "isPosted":true
                                        } ,
                                        {
                                            "_deleted":false
                                        }
                                        ]
                                        },
                                },
                                {
                                    $unwind: "$items"
                                },
                            {
                                $group:{
                                    _id: "$unit.division" ,
                                    "pricetotal":{$sum:{$multiply:["$items.pricePerDealUnit","$items.dealQuantity","$currencyRate"]}}
                                }
                            }
                        ]
                        )
                            .toArray(function(err, result) {
                                assert.equal(err, null);
                                console.log(result);
                                resolve(result);
                            });

             }
         });

    }
}<|endoftext|>


<commit_before>/* @flow */
/* eslint-disable no-console */

// This grants us source map support, which combined with our webpack source
// maps will give us nice stack traces.
import 'source-map-support/register';

import express from 'express';
import compression from 'compression';
import { resolve as pathResolve } from 'path';
import appRootDir from 'app-root-dir';
import reactApplication from './middleware/reactApplication';
import security from './middleware/security';
import clientBundle from './middleware/clientBundle';
import serviceWorker from './middleware/serviceWorker';
import errorHandlers from './middleware/errorHandlers';
import projConfig from '../../config/private/project';
import envConfig from '../../config/private/environment';

// Create our express based server.
const app = express();

// Don't expose any software information to potential hackers.
app.disable('x-powered-by');

// Security middlewares.
app.use(...security);

// Gzip compress the responses.
app.use(compression());

// When in production mode, we will serve our service worker which was generated
// by the offline-plugin webpack plugin. See the webpack plugins section for
// more information.
// Note: the service worker needs to be served from the http root of your
// application for it to work correctly.
if (process.env.NODE_ENV === 'production') {
  app.get(`/${projConfig.serviceWorker.fileName}`, serviceWorker);
}

// Configure serving of our client bundle.
app.use(projConfig.bundles.client.webPath, clientBundle);

// Configure static serving of our "public" root http path static files.
// Note: these will be served off the root (i.e. '/') of our application.
app.use(express.static(pathResolve(appRootDir.get(), projConfig.publicAssetsPath)));

// The React application middleware.
app.get('*', reactApplication);

// Error Handler middlewares.
app.use(...errorHandlers);

// Create an http listener for our express app.
const listener = app.listen(envConfig.port, () =>
  console.log(`Server listening on port ${envConfig.port}`),
);

// We export the listener as it will be handy for our development hot reloader,
// or for exposing a general extension layer for application customisations.
export default listener;
<commit_msg>Fixes host configuration for server.<commit_after>/* @flow */
/* eslint-disable no-console */

// This grants us source map support, which combined with our webpack source
// maps will give us nice stack traces.
import 'source-map-support/register';

import express from 'express';
import compression from 'compression';
import { resolve as pathResolve } from 'path';
import appRootDir from 'app-root-dir';
import reactApplication from './middleware/reactApplication';
import security from './middleware/security';
import clientBundle from './middleware/clientBundle';
import serviceWorker from './middleware/serviceWorker';
import errorHandlers from './middleware/errorHandlers';
import projConfig from '../../config/private/project';
import envConfig from '../../config/private/environment';

// Create our express based server.
const app = express();

// Don't expose any software information to potential hackers.
app.disable('x-powered-by');

// Security middlewares.
app.use(...security);

// Gzip compress the responses.
app.use(compression());

// When in production mode, we will serve our service worker which was generated
// by the offline-plugin webpack plugin. See the webpack plugins section for
// more information.
// Note: the service worker needs to be served from the http root of your
// application for it to work correctly.
if (process.env.NODE_ENV === 'production') {
  app.get(`/${projConfig.serviceWorker.fileName}`, serviceWorker);
}

// Configure serving of our client bundle.
app.use(projConfig.bundles.client.webPath, clientBundle);

// Configure static serving of our "public" root http path static files.
// Note: these will be served off the root (i.e. '/') of our application.
app.use(express.static(pathResolve(appRootDir.get(), projConfig.publicAssetsPath)));

// The React application middleware.
app.get('*', reactApplication);

// Error Handler middlewares.
app.use(...errorHandlers);

// Create an http listener for our express app.
const listener = app.listen(envConfig.port, envConfig.host, () =>
  console.log(`Server listening on port ${envConfig.port}`),
);

// We export the listener as it will be handy for our development hot reloader,
// or for exposing a general extension layer for application customisations.
export default listener;
<|endoftext|>


<commit_before>const bodyParser = require('body-parser');
const express = require('express');
const path = require('path');

const config = require('./config.json');
const pocket = require('./pocket.js');

const errorHandler = (res, err) => {
    res.status(500).send(err);
};

const url = `http://${config.address}:${config.port}`;

const app = express();

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '/www/html'));
app.use(express.static(path.join(__dirname, '/www')));
app.use(bodyParser.json());

app.post('/api/get', (req, res) => {
    pocket.get(req.body.accessToken, (data) => {
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify(data));
    }, (err) => {
        errorHandler(res, err);
    });
});

app.get('/', (req, res) => {
    res.render('index', {
        'requestToken': pocket.getRequestToken(),
        'redirectURI': `${url}/app`
    });
});

app.get('/app', (req, res) => {
    pocket.authorize((data) => {
        res.render('app', {
            'accessToken': data.access_token,
            'username': data.username
        });
    }, (err) => {
        errorHandler(res, err);
    });
});

const start = () => {
    const server = app.listen(config.port, config.address, () => {
        const host = server.address().address;
        const port = server.address().port;
        console.log('[Server] Listening at: http://%s:%s', host, port);
    });
};

// init pocket (i.e., get request token) and start the server afterwards
pocket.init(url, start, console.log.bind(console));
<commit_msg>server: redirect /app to / if not logged in<commit_after>const bodyParser = require('body-parser');
const express = require('express');
const path = require('path');

const config = require('./config.json');
const pocket = require('./pocket.js');

const errorHandler = (res, err) => {
    res.status(500).send(err);
};

const url = `http://${config.address}:${config.port}`;

const app = express();

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '/www/html'));
app.use(express.static(path.join(__dirname, '/www')));
app.use(bodyParser.json());

app.post('/api/get', (req, res) => {
    pocket.get(req.body.accessToken, (data) => {
        res.setHeader('Content-Type', 'application/json');
        res.send(JSON.stringify(data));
    }, (err) => {
        errorHandler(res, err);
    });
});

app.get('/', (req, res) => {
    res.render('index', {
        'requestToken': pocket.getRequestToken(),
        'redirectURI': `${url}/app`
    });
});

app.get('/app', (req, res) => {
    pocket.authorize((data) => {
        res.render('app', {
            'accessToken': data.access_token,
            'username': data.username
        });
    }, () => {
        res.redirect('/');
    });
});

const start = () => {
    const server = app.listen(config.port, config.address, () => {
        const host = server.address().address;
        const port = server.address().port;
        console.log('[Server] Listening at: http://%s:%s', host, port);
    });
};

// init pocket (i.e., get request token) and start the server afterwards
pocket.init(url, start, console.log.bind(console));
<|endoftext|>