<commit_before>'use strict';

var theToolServices = angular.module('theTool.services', ['ngResource']);

theToolServices
  .factory('CompanyFactory', function($resource) {
    return $resource('/api/company/:id', null, {
      'getAll': {method: 'GET', isArray:true},
      'update': {method: 'PUT'},
      'create': {method: 'POST'},
      'delete': {method: 'DELETE'}
    });
  })

  .factory('SpeakerFactory', function($resource) {
    return $resource('/api/speaker/:id', null, {
      'getAll': {method: 'GET', isArray:true},
      'update': {method: 'PUT'},
      'create': {method: 'POST'},
      'delete': {method: 'DELETE'}
    });
  })

  .factory('MemberFactory', function($resource) {
    return {
      Member: $resource('/api/member/:id', null, {
        'getAll': {method: 'GET', isArray:true},
        'update': {method: 'PUT'},
        'create': {method: 'POST'},
        'delete': {method: 'DELETE'}
      }),
      Companies: $resource('/api/member/:id/companies', null, {
        'getAll': {method: 'GET', isArray:true}
      }),
      Speakers: $resource('/api/member/:id/speakers', null, {
        'getAll': {method: 'GET', isArray:true}
      }),
      Topics: $resource('/api/member/:id/topics', null, {
        'getAll': { method: 'GET', isArray: true }
      })
    }
  })

  .factory('CommentFactory', function($resource) {
    return {
      Comment: $resource('/api/comment/:id', null, {
        'getAll': {method: 'GET', isArray:true},
        'update': {method: 'PUT'},
        'create': {method: 'POST'},
        'delete': {method: 'DELETE'}
      }),
      Company: $resource('/api/company/:id/comments', null, {
        'getAll': {method: 'GET', isArray:true}
      }),
      Speaker: $resource('/api/speaker/:id/comments', null, {
        'getAll': {method: 'GET', isArray:true}
      }),
      Topic: $resource('/api/topic/:id/comments', null, {
        'getAll': {method: 'GET', isArray:true}
      })
    }
  })

  .factory('EmailFactory', function($resource) {
    return {
      Company: $resource('/api/company/:id/sendInitialEmail', null, {
        'send': {method: 'POST'}
      }),
      Speaker: $resource('/api/speaker/:id/sendInitialEmail', null, {
        'send': {method: 'POST'}
      })
    }
  })

  .factory('NotificationFactory', function($resource) {
    return {
      Notification: $resource('/api/notification/:id', null, {
        'getAll': {method: 'GET', isArray:true},
      }),
      Company: $resource('/api/company/:id/notifications', null, {
        'getAll': {method: 'GET', isArray:true}
      }),
      Speaker: $resource('/api/speaker/:id/notifications', null, {
        'getAll': {method: 'GET', isArray:true}
      }),
      Topic: $resource('/api/topic/:id/notifications', null, {
        'getAll': {method: 'GET', isArray:true}
      })
    }
  })

  .factory('TopicFactory', function($resource) {
    return {
      Topic: $resource('/api/topic/:id', null, {
        'getAll': {method: 'GET', isArray:true},
        'create': {method: 'POST'},
        'update': {method: 'PUT'},
        'delete': {method: 'DELETE'}
      })
    }
  })

  .factory('MeetingFactory', function($resource) {
    return $resource('/api/meeting/:id', null, {
      'getAll': {method: 'GET', isArray:true},
      'create': {method: 'POST'},
      'update': {method: 'PUT'},
      'delete': {method: 'DELETE'}
    })
  })

  .factory('ChatFactory', function($resource) {
    return {
      Chat: $resource('/api/chat/:id', null, {
        'update': {method: 'POST'},
        'get':    {method: 'GET'}
      }),
      Chats: $resource('/api/chats', null, {
        'getAll': {method: 'GET', isArray:true}
      }),
      Messages: $resource('/api/chat/:id/messages', null, {
        'get': {method: 'GET',isArray:true}
      })
    }
  })

  .factory('MessageFactory', function($resource) {
    return $resource('/api/message/:id', null, {
        get:    {method: 'GET'},
        create: {method: 'POST'}
      })
  });
<commit_msg>factoriessssss<commit_after>'use strict';

var theToolServices = angular.module('theTool.services', ['ngResource']);

theToolServices
  .factory('CompanyFactory', function ($resource) {
    return {
      Company: $resource('/api/company/:id', null, {
        'getAll': {method: 'GET', isArray:true},
        'update': {method: 'PUT'},
        'create': {method: 'POST'},
        'delete': {method: 'DELETE'}
      }),
      Member: $resource('/api/member/:id/companies', null, {
        'getAll': {method: 'GET', isArray:true}
      })
    };
  })

  .factory('SpeakerFactory', function ($resource) {
    return {
      Speaker: $resource('/api/speaker/:id', null, {
        'getAll': {method: 'GET', isArray:true},
        'update': {method: 'PUT'},
        'create': {method: 'POST'},
        'delete': {method: 'DELETE'}
      }),
      Member: $resource('/api/member/:id/speakers', null, {
        'getAll': {method: 'GET', isArray:true}
      })
    };
  })

  .factory('MemberFactory', function ($resource) {
    return {
      Member: $resource('/api/member/:id', null, {
        'getAll': {method: 'GET', isArray:true},
        'update': {method: 'PUT'},
        'create': {method: 'POST'},
        'delete': {method: 'DELETE'}
      }),
      Role: $resource('/api/role/:id/members', null, {
        'getAll': {method: 'GET', isArray: true}
      })
    };
  })

  .factory('CommentFactory', function ($resource) {
    return {
      Comment: $resource('/api/comment/:id', null, {
        'getAll': {method: 'GET', isArray: true},
        'update': {method: 'PUT'},
        'create': {method: 'POST'},
        'delete': {method: 'DELETE'}
      }),
      Company: $resource('/api/company/:id/comments', null, {
        'getAll': {method: 'GET', isArray: true}
      }),
      Speaker: $resource('/api/speaker/:id/comments', null, {
        'getAll': {method: 'GET', isArray: true}
      }),
      Topic: $resource('/api/topic/:id/comments', null, {
        'getAll': {method: 'GET', isArray: true}
      })
    }
  })

  .factory('EmailFactory', function ($resource) {
    return {
      Company: $resource('/api/company/:id/sendInitialEmail', null, {
        'send': {method: 'POST'}
      }),
      Speaker: $resource('/api/speaker/:id/sendInitialEmail', null, {
        'send': {method: 'POST'}
      })
    }
  })

  .factory('NotificationFactory', function ($resource) {
    return {
      Notification: $resource('/api/notification/:id', null, {
        'getAll': {method: 'GET', isArray: true},
      }),
      Company: $resource('/api/company/:id/notifications', null, {
        'getAll': {method: 'GET', isArray: true}
      }),
      Speaker: $resource('/api/speaker/:id/notifications', null, {
        'getAll': {method: 'GET', isArray: true}
      }),
      Topic: $resource('/api/topic/:id/notifications', null, {
        'getAll': {method: 'GET', isArray: true}
      })
    }
  })

  .factory('TopicFactory', function ($resource) {
    return {
      Topic: $resource('/api/topic/:id', null, {
        'getAll': {method: 'GET', isArray: true},
        'create': {method: 'POST'},
        'update': {method: 'PUT'},
        'delete': {method: 'DELETE'}
      }),
      Member: $resource('/api/member/:id/topics', null, {
        'getAll': { method: 'GET', isArray: true }
      })
    }
  })

  .factory('MeetingFactory', function ($resource) {
    return $resource('/api/meeting/:id', null, {
      'getAll': {method: 'GET', isArray: true},
      'create': {method: 'POST'},
      'update': {method: 'PUT'},
      'delete': {method: 'DELETE'}
    })
  })

  .factory('ChatFactory', function ($resource) {
    return {
      Chat: $resource('/api/chat/:id', null, {
        'update': {method: 'POST'},
        'get':    {method: 'GET'}
      }),
      Chats: $resource('/api/chats', null, {
        'getAll': {method: 'GET', isArray:true}
      }),
      Messages: $resource('/api/chat/:id/messages', null, {
        'get': {method: 'GET',isArray:true}
      })
    }
  })

  .factory('MessageFactory', function ($resource) {
    return $resource('/api/message/:id', null, {
        get:    {method: 'GET'},
        create: {method: 'POST'}
      })
  })

  .factory('RoleFactory', function ($resource) {
    return {

    };
  });
<|endoftext|>


<commit_before>

function textAreaPop(text,textAreaName,htmlFormAction,textAreaLabel){
  url=window.location.href
  pathname=window.location.pathname
  idx1=url.indexOf(pathname);
  idx2=url.indexOf("/",idx1+1);
  extractUrl=url.substr(0,idx2)
  text=text.replace(/\n/g,'
');
  window.open(extractUrl+"/TextArea.jsp?" + text+"&textAreaFieldName="+textAreaName+"&htmlFormAction="+htmlFormAction+"&textAreaFieldLabel="+textAreaLabel, "_blank", "width=640, height=600, scrollbars=yes");
}

var textAreaFieldName
function setTextArea() {
  passData=document.location.search.substring(1);
  var idx=passData.indexOf("&textAreaFieldName=")
  var idx2=passData.indexOf("&htmlFormAction=")
  textAreaFieldName=passData.substring(idx+19,idx2)
  text=passData.substr(0,idx)
  text=text.replace(/
/g,"\n")
  document.getElementById(textAreaFieldName).value =unescape(text)
//  alert (escape(text))
//  alert (unescape(text))

}

function postValueToParentWindow() {
  opener.document.getElementById(textAreaFieldName).value = document.getElementById(textAreaFieldName).value;
  self.close();
}
<commit_msg>KRACOEUS-102 : Javascript icon for popping up an expanded text-area page   . to make it work for firefox too.<commit_after>

function textAreaPop(text,textAreaName,htmlFormAction,textAreaLabel){
  url=window.location.href
  pathname=window.location.pathname
  idx1=url.indexOf(pathname);
  idx2=url.indexOf("/",idx1+1);
  extractUrl=url.substr(0,idx2)
  text=text.replace(/\n/g,'
');
  window.open(extractUrl+"/TextArea.jsp?" + text+"&textAreaFieldName="+textAreaName+"&htmlFormAction="+htmlFormAction+"&textAreaFieldLabel="+textAreaLabel, "_blank", "width=640, height=600, scrollbars=yes");
}

var textAreaFieldName
function setTextArea() {
  passData=document.location.search.substring(1);
  var idx=passData.indexOf("&textAreaFieldName=")
  var idx2=passData.indexOf("&htmlFormAction=")
  textAreaFieldName=passData.substring(idx+19,idx2)
  text=passData.substr(0,idx)
  text=unescape(text).replace(/
/g,"\n")
  document.getElementById(textAreaFieldName).value =unescape(text)
//  alert (escape(text))
//  alert (unescape(text))

}

function postValueToParentWindow() {
  opener.document.getElementById(textAreaFieldName).value = document.getElementById(textAreaFieldName).value;
  self.close();
}
<|endoftext|>


<commit_before>let city;
let filter;

function init() {
  authReload();
  addCityAutocomplete();
  addFilterHandler();
}

function addCityAutocomplete() {
  const cityInputField = document.getElementById('city-input')
  const options = {
    types: ['(cities)'],
  }
  const autocomplete = new google.maps.places.Autocomplete(cityInputField, options);
  google.maps.event.addListener(autocomplete, 'place_changed', () => {
    city = autocomplete.getPlace();
    if(typeof filter !== 'undefined') {
      findPlacesInCity(city, filter);
    }
  });
}

function addFilterHandler() {
  const filterForm = document.getElementById('filters');
  filterForm.addEventListener('change', () => {
    filter = filterForm.value;
    if(typeof city !== 'undefined') {
      findPlacesInCity(city, filter);
    }
  });
}

function findPlacesInCity(city, filter) {
  if (city.hasOwnProperty('place_id') === false) {
    M.Toast.dismissAll();
    M.toast({
      html: "Your city wasn't selected with autocomplete",
    });
    return;
  }

  console.log(city);
  console.log(filter);
}

<commit_msg>Make conditionals in place-suggestions.js more concise<commit_after>let city;
let filter;

function init() {
  authReload();
  addCityAutocomplete();
  addFilterHandler();
}

function addCityAutocomplete() {
  const cityInputField = document.getElementById('city-input')
  const options = {
    types: ['(cities)'],
  }
  const autocomplete = new google.maps.places.Autocomplete(cityInputField, options);
  google.maps.event.addListener(autocomplete, 'place_changed', () => {
    city = autocomplete.getPlace();
    if(filter) {
      findPlacesInCity(city, filter);
    }
  });
}

function addFilterHandler() {
  const filterForm = document.getElementById('filters');
  filterForm.addEventListener('change', () => {
    filter = filterForm.value;
    if(city) {
      findPlacesInCity(city, filter);
    }
  });
}

function findPlacesInCity(city, filter) {
  if (!city.hasOwnProperty('place_id')) {
    M.Toast.dismissAll();
    M.toast({
      html: "Your city wasn't selected with autocomplete",
    });
    return;
  }

  console.log(city);
  console.log(filter);
}

<|endoftext|>


<commit_before>'use strict';
//require('js-toolkit').Promise.ext;

// external deps
var ObjectId = require('mongodb').ObjectId;

// internal deps
require('mongodb-toolkit');
var BateeqModels = require('bateeq-models');
var map = BateeqModels.map;

var ExpeditionDoc = BateeqModels.inventory.ExpeditionDoc;
var TransferOutDoc = BateeqModels.inventory.TransferOutDoc;
var TransferOutItem = BateeqModels.inventory.TransferOutItem;
var SPK = BateeqModels.merchandiser.SPK;
var generateCode = require('../../utils/code-generator');

const moduleId = "EFR-KB/EXP";
module.exports = class PusatBarangBaruKirimBarangJadiAksesorisManager {
    constructor(db, user) {
        this.db = db;
        this.user = user;
        this.expeditionDocCollection = this.db.use(map.inventory.ExpeditionDoc);

        var StorageManager = require('../master/storage-manager');
        this.storageManager = new StorageManager(db, user);

        var TransferOutDocManager = require('./transfer-out-doc-manager');
        this.transferOutDocManager = new TransferOutDocManager(db, user);

        var SpkManager = require('../merchandiser/efr-pk-manager');
        this.spkManager = new SpkManager(db, user);

        var ModuleManager = require('../master/module-manager');
        this.moduleManager = new ModuleManager(db, user);
    }

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

        return new Promise((resolve, reject) => {
            var regexModuleId = new RegExp(moduleId, "i");
            var filter = {
                _deleted: false,
                _createdBy : this.user.username,
                'code': {
                    '$regex': regexModuleId
                }
            };
            var query = _paging.keyword ? {
                '$and': [filter]
            } : filter;

            if (_paging.keyword) {
                var regex = new RegExp(_paging.keyword, "i");
                var filterCode = {
                    'code': {
                        '$regex': regex
                    }
                };
                var $or = {
                    '$or': [filterCode]
                };

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

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

    getSingleById(id) {
        return new Promise((resolve, reject) => {
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(expeditionDoc => {
                    resolve(expeditionDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getSingleByIdOrDefault(id) {
        return new Promise((resolve, reject) => {
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleByQueryOrDefault(query)
                .then(expeditionDoc => {
                    resolve(expeditionDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getSingleByQuery(query) {
        return new Promise((resolve, reject) => {
            this.expeditionDocCollection
                .single(query)
                .then(expeditionDoc => {
                    resolve(expeditionDoc);
                })
                .catch(e => {
                    reject(e);
                });
        })
    }

    getSingleByQueryOrDefault(query) {
        return new Promise((resolve, reject) => {
            this.expeditionDocCollection
                .singleOrDefault(query)
                .then(expeditionDoc => {
                    resolve(expeditionDoc);
                })
                .catch(e => {
                    reject(e);
                });
        })
    }

    getBySpk(code) {
        var query = { "spkDocuments.code": code };
        return new Promise((resolve, reject) => {
            this.expeditionDocCollection
                .where(query)
                .execute()
                .then(expeditionDocs => {
                    resolve(expeditionDocs);
                })
                .catch(e => {
                    reject(e);
                });
        })
    }

    create(expeditionDoc) {
        return new Promise((resolve, reject) => {
            //Validate Input Model
            this._validate(expeditionDoc)
                .then(validatedExpeditionDoc => {
                    var getTransferOuts = [];
                    //Create Promise to Create Transfer Out
                    for (var spkDocument of validatedExpeditionDoc.spkDocuments) {
                        //getTransferOuts.push(this.transferOutDocManager.create(validTransferOutDoc));
                        var f = (spkDoc, outManager) => {
                            return () => {
                                var code = generateCode(moduleId);
                                var validTransferOutDoc = {};
                                validTransferOutDoc.code = code;
                                validTransferOutDoc.reference = spkDoc.packingList;
                                validTransferOutDoc.sourceId = spkDoc.sourceId;
                                validTransferOutDoc.destinationId = spkDoc.destinationId;
                                validTransferOutDoc.items = [];
                                for (var item of spkDoc.items) {
                                    var newitem = {};
                                    newitem.itemId = item.itemId;
                                    newitem.quantity = item.quantity;
                                    validTransferOutDoc.items.push(newitem);
                                }
                                return outManager.create(validTransferOutDoc)
                            }
                        };
                        getTransferOuts.push(f(spkDocument, this.transferOutDocManager));
                    }
                    //Create Transfer Out
                    //Promise.all(getTransferOuts)
                    require('js-toolkit').Promise.ext;
                    Promise.chain(getTransferOuts)
                        .then(results => {
                            getTransferOuts = [];
                            //Create Promise Get Transfer Out using ID
                            for (var transferOutResultId of results) {
                                getTransferOuts.push(this.transferOutDocManager.getSingleByIdOrDefault(transferOutResultId));
                            }
                            //Get Transfer Out
                            Promise.all(getTransferOuts)
                                .then(transferOutResults => {
                                    //Create Expedition Model
                                    var validExpeditionDoc = {};
                                    validExpeditionDoc.code = generateCode(moduleId);
                                    validExpeditionDoc.expedition = validatedExpeditionDoc.expedition;
                                    validExpeditionDoc.weight = validatedExpeditionDoc.weight;
                                    validExpeditionDoc.transferOutDocuments = [];
                                    validExpeditionDoc.spkDocuments = validatedExpeditionDoc.spkDocuments
                                    for (var transferOut of transferOutResults) {
                                        validExpeditionDoc.transferOutDocuments.push(transferOut);
                                    }
                                    validExpeditionDoc = new ExpeditionDoc(validExpeditionDoc);
                                    validExpeditionDoc._createdDate = new Date();
                                    validExpeditionDoc.stamp(this.user.username, 'manager');
                                    //Create Promise Expedition
                                    this.expeditionDocCollection.insert(validExpeditionDoc)
                                        .then(resultExpeditionId => {
                                            //Get Expedition Data
                                            this.getSingleByIdOrDefault(resultExpeditionId)
                                                .then(resultExpedition => {
                                                    var getSPKData = [];
                                                    //Create Promise get SPK Data for update
                                                    for (var spkDocument of validExpeditionDoc.spkDocuments) {
                                                        getSPKData.push(this.spkManager.getSingleByIdOrDefault(spkDocument._id));
                                                    }
                                                    //Get SPK Data
                                                    Promise.all(getSPKData)
                                                        .then(resultSPKs => {
                                                            //Create Promise Update SPK Data
                                                            var getUpdateSPKData = [];
                                                            for (var resultSPK of resultSPKs) {
                                                                resultSPK.expeditionDocumentId = resultExpeditionId;
                                                                resultSPK.expeditionDocument = resultExpedition;
                                                                resultSPK = new SPK(resultSPK);
                                                                getUpdateSPKData.push(this.spkManager.update(resultSPK));
                                                            }
                                                            //Update SPK Data
                                                            Promise.all(getUpdateSPKData)
                                                                .then(resultUpdateSPKs => {
                                                                    resolve(resultExpeditionId);
                                                                })
                                                                .catch(e => {
                                                                    reject(e);
                                                                });
                                                        })
                                                        .catch(e => {
                                                            reject(e);
                                                        });
                                                })
                                                .catch(e => {
                                                    reject(e);
                                                });
                                        })
                                        .catch(e => {
                                            reject(e);
                                        });
                                })
                                .catch(e => {
                                    reject(e);
                                });
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    update(expeditionDoc) {
        return new Promise((resolve, reject) => {
            resolve(null);
        });
    }

    delete(expeditionDoc) {
        return new Promise((resolve, reject) => {
            resolve(null);
        });
    }

    _validate(expeditionDoc) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = expeditionDoc;
            this.moduleManager.getByCode(moduleId)
                .then(module => {
                    var config = module.config;
                    var getPromise = [];
                    var validateSPKisExist = [];

                    if (!valid.expedition || valid.expedition == '')
                        errors["expedition"] = "expedition is required";

                    if (!valid.spkDocuments || valid.spkDocuments.length == 0) {
                        errors["spkDocuments"] = "spkDocuments is required";
                    }
                    else {
                        var spkDocumentErrors = [];
                        var spkDocumentDestinationId = "";
                        expeditionDoc.weight = 0;
                        for (var spkDocument of valid.spkDocuments) {
                            expeditionDoc.weight += parseInt(spkDocument.weight || 0);
                            var spkDocumentError = {};
                            if (!spkDocument._id || spkDocument._id == "") {
                                spkDocumentError["spkDocumentId"] = "packing list is required";
                                getPromise.push(Promise.resolve(null));
                            }
                            else {
                                for (var i = valid.spkDocuments.indexOf(spkDocument) + 1; i < valid.spkDocuments.length; i++) {
                                    var otherItem = valid.spkDocuments[i];
                                    if (spkDocument._id == otherItem._id) {
                                        spkDocumentError["spkDocumentId"] = "spkDocumentId already exists on another detail";
                                    }
                                }

                                getPromise.push(this.spkManager.getSingleByIdOrDefault(spkDocument._id));
                            }

                            validateSPKisExist.push(this.getBySpk(spkDocument.code));

                            if (spkDocumentDestinationId == "")
                                spkDocumentDestinationId = spkDocument.destinationId;
                            if (spkDocument.destinationId != spkDocumentDestinationId)
                                spkDocumentError["spkDocumentId"] = "packing list harus memiliki tujuan yang sama";

                            spkDocumentErrors.push(spkDocumentError);
                        }
                        for (var spkDocumentError of spkDocumentErrors) {
                            for (var prop in spkDocumentError) {
                                errors.spkDocuments = spkDocumentErrors;
                                break;
                            }
                            if (errors.spkDocuments)
                                break;
                        }
                    }

                    Promise.all(validateSPKisExist).then(
                        validateSPKisExistResult => {
                            var spkDocumentErrors = [];

                            Promise.all(getPromise)
                                .then(spkDocuments => {
                                    var index = 0;
                                    for (var spkDocument of valid.spkDocuments) {
                                        var spkDocumentError = {};

                                        if (spkDocuments[index]) {
                                            var spkspkDocumentError = {};
                                            if (spkDocument) {
                                                if (!spkDocument.items || spkDocument.items.length == 0) {
                                                    spkspkDocumentError["items"] = "items is required";
                                                }
                                                else {
                                                    var itemErrors = [];
                                                    for (var item of spkDocument.items) {
                                                        var itemError = {};
                                                        if (item.quantity == undefined || (item.quantity && item.quantity == '')) {
                                                            itemError["quantity"] = "quantity is required";
                                                        }
                                                        else if (parseInt(item.quantity) <= 0) {
                                                            itemError["quantity"] = "quantity must be greater than 0";
                                                        }
                                                        if (item.quantitySend == undefined || (item.quantitySend && item.quantitySend == '')) {
                                                            itemError["quantitySend"] = "quantitySend is required";
                                                        }
                                                        else if (parseInt(item.quantitySend) <= 0) {
                                                            itemError["quantitySend"] = "quantitySend must be greater than 0";
                                                        }

                                                        if (item.quantitySend > item.quantity) {
                                                            itemError["quantitySend"] = "quantitySend must not be greater then quantity";
                                                        }
                                                        if (item.quantitySend != item.quantity && (!item.remark || item.remark == '')) {
                                                            itemError["remark"] = "notes is required";
                                                        }
                                                        item.quantity = item.quantitySend;

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

                                                if ((spkDocument.weight || 0) == 0)
                                                    spkspkDocumentError["weight"] = "weight is required";
                                            }

                                            for (var prop in spkspkDocumentError) {
                                                spkDocumentError = spkspkDocumentError;
                                                break;
                                            }

                                            if (validateSPKisExistResult[index].count > 0)
                                                spkDocumentError.code = "spk document sudah memiliki ekspedisi";

                                            spkDocument = spkDocuments[index];
                                        }
                                        // else {
                                        //     spkDocumentError["spkDocument"] = "SPK Document not found";
                                        // }
                                        index++;
                                        spkDocumentErrors.push(spkDocumentError);
                                    }
                                    for (var spkDocumentError of spkDocumentErrors) {
                                        for (var prop in spkDocumentError) {
                                            errors.spkDocuments = spkDocumentErrors;
                                            break;
                                        }
                                    }

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

                                    resolve(valid)
                                })
                                .catch(e => {
                                    reject(e);
                                });
                        }
                    )
                })
                .catch(e => {
                    reject(new Error(`Unable to load module:${moduleId}`));
                });
        });
    }

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

            this.getSingleById(id)
                .then(docs => {
                    var getDefinition = require('../../pdf/definitions/efr-kb-exp');
                    var definition = getDefinition(docs);

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

        });
    }
};<commit_msg>update expedition validation<commit_after>'use strict';
//require('js-toolkit').Promise.ext;

// external deps
var ObjectId = require('mongodb').ObjectId;

// internal deps
require('mongodb-toolkit');
var BateeqModels = require('bateeq-models');
var map = BateeqModels.map;

var ExpeditionDoc = BateeqModels.inventory.ExpeditionDoc;
var TransferOutDoc = BateeqModels.inventory.TransferOutDoc;
var TransferOutItem = BateeqModels.inventory.TransferOutItem;
var SPK = BateeqModels.merchandiser.SPK;
var generateCode = require('../../utils/code-generator');

const moduleId = "EFR-KB/EXP";
module.exports = class PusatBarangBaruKirimBarangJadiAksesorisManager {
    constructor(db, user) {
        this.db = db;
        this.user = user;
        this.expeditionDocCollection = this.db.use(map.inventory.ExpeditionDoc);

        var StorageManager = require('../master/storage-manager');
        this.storageManager = new StorageManager(db, user);

        var TransferOutDocManager = require('./transfer-out-doc-manager');
        this.transferOutDocManager = new TransferOutDocManager(db, user);

        var SpkManager = require('../merchandiser/efr-pk-manager');
        this.spkManager = new SpkManager(db, user);

        var ModuleManager = require('../master/module-manager');
        this.moduleManager = new ModuleManager(db, user);
    }

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

        return new Promise((resolve, reject) => {
            var regexModuleId = new RegExp(moduleId, "i");
            var filter = {
                _deleted: false,
                _createdBy : this.user.username,
                'code': {
                    '$regex': regexModuleId
                }
            };
            var query = _paging.keyword ? {
                '$and': [filter]
            } : filter;

            if (_paging.keyword) {
                var regex = new RegExp(_paging.keyword, "i");
                var filterCode = {
                    'code': {
                        '$regex': regex
                    }
                };
                var $or = {
                    '$or': [filterCode]
                };

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

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

    getSingleById(id) {
        return new Promise((resolve, reject) => {
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleByQuery(query)
                .then(expeditionDoc => {
                    resolve(expeditionDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getSingleByIdOrDefault(id) {
        return new Promise((resolve, reject) => {
            var query = {
                _id: new ObjectId(id),
                _deleted: false
            };
            this.getSingleByQueryOrDefault(query)
                .then(expeditionDoc => {
                    resolve(expeditionDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    getSingleByQuery(query) {
        return new Promise((resolve, reject) => {
            this.expeditionDocCollection
                .single(query)
                .then(expeditionDoc => {
                    resolve(expeditionDoc);
                })
                .catch(e => {
                    reject(e);
                });
        })
    }

    getSingleByQueryOrDefault(query) {
        return new Promise((resolve, reject) => {
            this.expeditionDocCollection
                .singleOrDefault(query)
                .then(expeditionDoc => {
                    resolve(expeditionDoc);
                })
                .catch(e => {
                    reject(e);
                });
        })
    }

    getBySpk(code) {
        var query = { "spkDocuments.code": code };
        return new Promise((resolve, reject) => {
            this.expeditionDocCollection
                .where(query)
                .execute()
                .then(expeditionDocs => {
                    resolve(expeditionDocs);
                })
                .catch(e => {
                    reject(e);
                });
        })
    }

    create(expeditionDoc) {
        return new Promise((resolve, reject) => {
            //Validate Input Model
            this._validate(expeditionDoc)
                .then(validatedExpeditionDoc => {
                    var getTransferOuts = [];
                    //Create Promise to Create Transfer Out
                    for (var spkDocument of validatedExpeditionDoc.spkDocuments) {
                        //getTransferOuts.push(this.transferOutDocManager.create(validTransferOutDoc));
                        var f = (spkDoc, outManager) => {
                            return () => {
                                var code = generateCode(moduleId);
                                var validTransferOutDoc = {};
                                validTransferOutDoc.code = code;
                                validTransferOutDoc.reference = spkDoc.packingList;
                                validTransferOutDoc.sourceId = spkDoc.sourceId;
                                validTransferOutDoc.destinationId = spkDoc.destinationId;
                                validTransferOutDoc.items = [];
                                for (var item of spkDoc.items) {
                                    var newitem = {};
                                    newitem.itemId = item.itemId;
                                    newitem.quantity = item.quantity;
                                    validTransferOutDoc.items.push(newitem);
                                }
                                return outManager.create(validTransferOutDoc)
                            }
                        };
                        getTransferOuts.push(f(spkDocument, this.transferOutDocManager));
                    }
                    //Create Transfer Out
                    //Promise.all(getTransferOuts)
                    require('js-toolkit').Promise.ext;
                    Promise.chain(getTransferOuts)
                        .then(results => {
                            getTransferOuts = [];
                            //Create Promise Get Transfer Out using ID
                            for (var transferOutResultId of results) {
                                getTransferOuts.push(this.transferOutDocManager.getSingleByIdOrDefault(transferOutResultId));
                            }
                            //Get Transfer Out
                            Promise.all(getTransferOuts)
                                .then(transferOutResults => {
                                    //Create Expedition Model
                                    var validExpeditionDoc = {};
                                    validExpeditionDoc.code = generateCode(moduleId);
                                    validExpeditionDoc.expedition = validatedExpeditionDoc.expedition;
                                    validExpeditionDoc.weight = validatedExpeditionDoc.weight;
                                    validExpeditionDoc.transferOutDocuments = [];
                                    validExpeditionDoc.spkDocuments = validatedExpeditionDoc.spkDocuments
                                    for (var transferOut of transferOutResults) {
                                        validExpeditionDoc.transferOutDocuments.push(transferOut);
                                    }
                                    validExpeditionDoc = new ExpeditionDoc(validExpeditionDoc);
                                    validExpeditionDoc._createdDate = new Date();
                                    validExpeditionDoc.stamp(this.user.username, 'manager');
                                    //Create Promise Expedition
                                    this.expeditionDocCollection.insert(validExpeditionDoc)
                                        .then(resultExpeditionId => {
                                            //Get Expedition Data
                                            this.getSingleByIdOrDefault(resultExpeditionId)
                                                .then(resultExpedition => {
                                                    var getSPKData = [];
                                                    //Create Promise get SPK Data for update
                                                    for (var spkDocument of validExpeditionDoc.spkDocuments) {
                                                        getSPKData.push(this.spkManager.getSingleByIdOrDefault(spkDocument._id));
                                                    }
                                                    //Get SPK Data
                                                    Promise.all(getSPKData)
                                                        .then(resultSPKs => {
                                                            //Create Promise Update SPK Data
                                                            var getUpdateSPKData = [];
                                                            for (var resultSPK of resultSPKs) {
                                                                resultSPK.expeditionDocumentId = resultExpeditionId;
                                                                resultSPK.expeditionDocument = resultExpedition;
                                                                resultSPK = new SPK(resultSPK);
                                                                getUpdateSPKData.push(this.spkManager.update(resultSPK));
                                                            }
                                                            //Update SPK Data
                                                            Promise.all(getUpdateSPKData)
                                                                .then(resultUpdateSPKs => {
                                                                    resolve(resultExpeditionId);
                                                                })
                                                                .catch(e => {
                                                                    reject(e);
                                                                });
                                                        })
                                                        .catch(e => {
                                                            reject(e);
                                                        });
                                                })
                                                .catch(e => {
                                                    reject(e);
                                                });
                                        })
                                        .catch(e => {
                                            reject(e);
                                        });
                                })
                                .catch(e => {
                                    reject(e);
                                });
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    update(expeditionDoc) {
        return new Promise((resolve, reject) => {
            resolve(null);
        });
    }

    delete(expeditionDoc) {
        return new Promise((resolve, reject) => {
            resolve(null);
        });
    }

    _validate(expeditionDoc) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var valid = expeditionDoc;
            this.moduleManager.getByCode(moduleId)
                .then(module => {
                    var config = module.config;
                    var getPromise = [];
                    var validateSPKisExist = [];

                    if (!valid.expedition || valid.expedition == '')
                        errors["expedition"] = "expedition is required";

                    if (!valid.spkDocuments || valid.spkDocuments.length == 0) {
                        errors["spkDocuments"] = "spkDocuments is required";
                    }
                    else {
                        var spkDocumentErrors = [];
                        var spkDocumentDestinationId = "";
                        expeditionDoc.weight = 0;
                        for (var spkDocument of valid.spkDocuments) {
                            expeditionDoc.weight += parseInt(spkDocument.weight || 0);
                            var spkDocumentError = {};
                            if (!spkDocument._id || spkDocument._id == "") {
                                spkDocumentError["code"] = "packing list harus diisi";
                                getPromise.push(Promise.resolve(null));
                            }
                            else {
                                for (var i = valid.spkDocuments.indexOf(spkDocument) + 1; i < valid.spkDocuments.length; i++) {
                                    var otherItem = valid.spkDocuments[i];
                                    if (spkDocument._id == otherItem._id) {
                                        spkDocumentError["code"] = "duplikat packing list";
                                    }
                                }

                                getPromise.push(this.spkManager.getSingleByIdOrDefault(spkDocument._id));
                            }

                            validateSPKisExist.push(this.getBySpk(spkDocument.code));

                            if (spkDocumentDestinationId == "")
                                spkDocumentDestinationId = spkDocument.destinationId;
                            else if (spkDocument.destinationId != spkDocumentDestinationId)
                                spkDocumentError["code"] = "packing list harus memiliki tujuan yang sama";

                            spkDocumentErrors.push(spkDocumentError);
                        }
                        for (var spkDocumentError of spkDocumentErrors) {
                            for (var prop in spkDocumentError) {
                                errors.spkDocuments = spkDocumentErrors;
                                break;
                            }
                            if (errors.spkDocuments)
                                break;
                        }
                    }

                    Promise.all(validateSPKisExist).then(
                        validateSPKisExistResult => {
                            Promise.all(getPromise)
                                .then(spkDocuments => {
                                    var index = 0;
                                    for (var spkDocument of valid.spkDocuments) {
                                        var spkDocumentError = spkDocumentErrors[index];

                                        if (spkDocuments[index]) {
                                            var spkspkDocumentError = spkDocumentError;
                                            if (spkDocument) {
                                                if (!spkDocument.items || spkDocument.items.length == 0) {
                                                    spkspkDocumentError["items"] = "items is required";
                                                }
                                                else {
                                                    var itemErrors = [];
                                                    for (var item of spkDocument.items) {
                                                        var itemError = {};
                                                        if (item.quantity == undefined || (item.quantity && item.quantity == '')) {
                                                            itemError["quantity"] = "kuantitas harus diisi";
                                                        }
                                                        else if (parseInt(item.quantity) <= 0) {
                                                            itemError["quantity"] = "kuantitas harus lebih besar dari 0";
                                                        }
                                                        if (item.quantitySend == undefined || (item.quantitySend && item.quantitySend == '')) {
                                                            itemError["quantitySend"] = "kuantitas pengiriman harus diisi";
                                                        }
                                                        else if (parseInt(item.quantitySend) <= 0) {
                                                            itemError["quantitySend"] = "kuantitas pengiriman harus lebih besar dari 0";
                                                        }

                                                        if (item.quantitySend > item.quantity) {
                                                            itemError["quantitySend"] = "kuantitas pengiriman tidak boleh lebih besar dari kuantitas packing list";
                                                        }
                                                        if (item.quantitySend != item.quantity && (!item.remark || item.remark == '')) {
                                                            itemError["remark"] = "catatan harus diisi";
                                                        }
                                                        item.quantity = item.quantitySend;

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

                                                if ((spkDocument.weight || 0) == 0)
                                                    spkspkDocumentError["weight"] = "berat harus diisi";
                                            }

                                            for (var prop in spkspkDocumentError) {
                                                spkDocumentError = spkspkDocumentError;
                                                break;
                                            }

                                            if (validateSPKisExistResult[index].count > 0)
                                                spkDocumentError.code = "packing list sudah memiliki ekspedisi";

                                            spkDocument = spkDocuments[index];
                                        }
                                        // else {
                                        //     spkDocumentError["spkDocument"] = "SPK Document not found";
                                        // }
                                        index++;
                                    }
                                    for (var spkDocumentError of spkDocumentErrors) {
                                        for (var prop in spkDocumentError) {
                                            errors.spkDocuments = spkDocumentErrors;
                                            break;
                                        }
                                    }

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

                                    resolve(valid)
                                })
                                .catch(e => {
                                    reject(e);
                                });
                        }
                    )
                })
                .catch(e => {
                    reject(new Error(`Unable to load module:${moduleId}`));
                });
        });
    }

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

            this.getSingleById(id)
                .then(docs => {
                    var getDefinition = require('../../pdf/definitions/efr-kb-exp');
                    var definition = getDefinition(docs);

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

        });
    }
};<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * The examples provided by Facebook are for non-commercial testing and
 * evaluation purposes only.
 *
 * Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @providesModule AnExScroll
 * @flow
 */
'use strict';

var React = require('react');
var ReactNative = require('react-native');
var {
  Animated,
  Image,
  ScrollView,
  StyleSheet,
  Text,
  View,
} = ReactNative;

class AnExScroll extends React.Component {
  state: any = { scrollX: new Animated.Value(0) };

  render() {
    var width = this.props.panelWidth;
    return (
      <View style={styles.container}>
        <ScrollView
          automaticallyAdjustContentInsets={false}
          scrollEventThrottle={16 /* get all events */ }
          onScroll={Animated.event(
            [{nativeEvent: {contentOffset: {x: this.state.scrollX}}}]  // nested event mapping
          )}
          contentContainerStyle={{flex: 1, padding: 10}}
          pagingEnabled={true}
          horizontal={true}>
          <View style={[styles.page, {width}]}>
            <Image
              style={{width: 180, height: 180}}
              source={HAWK_PIC}
            />
            <Text style={styles.text}>
              {'I\'ll find something to put here.'}
            </Text>
          </View>
          <View style={[styles.page, {width}]}>
            <Text style={styles.text}>{'And here.'}</Text>
          </View>
          <View style={[styles.page, {width}]}>
            <Text>{'But not here.'}</Text>
          </View>
        </ScrollView>
        <Animated.Image
          pointerEvents="none"
          style={[styles.bunny, {transform: [
            {translateX: this.state.scrollX.interpolate({
              inputRange: [0, width, 2 * width],
              outputRange: [0, 0, width / 3]}),          //  multi-part ranges
              extrapolate: 'clamp'},                     //  default is 'extend'
            {translateY: this.state.scrollX.interpolate({
              inputRange: [0, width, 2 * width],
              outputRange: [0, -200, -260]}),
              extrapolate: 'clamp'},
            {scale: this.state.scrollX.interpolate({
              inputRange: [0, width, 2 * width],
              outputRange: [0.5, 0.5, 2]}),
              extrapolate: 'clamp'},
          ]}]}
          source={BUNNY_PIC}
        />
      </View>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    backgroundColor: 'transparent',
    flex: 1,
  },
  text: {
    padding: 4,
    paddingBottom: 10,
    fontWeight: 'bold',
    fontSize: 18,
    backgroundColor: 'transparent',
  },
  bunny: {
    backgroundColor: 'transparent',
    position: 'absolute',
    height: 160,
    width: 160,
  },
  page: {
    alignItems: 'center',
    justifyContent: 'flex-end',
  },
});

var HAWK_PIC = {uri: 'https://scontent-sea1-1.xx.fbcdn.net/hphotos-xfa1/t39.1997-6/10734304_1562225620659674_837511701_n.png'};
var BUNNY_PIC = {uri: 'https://scontent-sea1-1.xx.fbcdn.net/hphotos-xaf1/t39.1997-6/851564_531111380292237_1898871086_n.png'};

module.exports = AnExScroll;
<commit_msg>fix gratuitous app crash<commit_after>/**
 * Copyright (c) 2013-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * The examples provided by Facebook are for non-commercial testing and
 * evaluation purposes only.
 *
 * Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @providesModule AnExScroll
 * @flow
 */
'use strict';

var React = require('react');
var ReactNative = require('react-native');
var {
  Animated,
  Image,
  ScrollView,
  StyleSheet,
  Text,
  View,
} = ReactNative;

class AnExScroll extends React.Component {
  state: any = { scrollX: new Animated.Value(0) };

  render() {
    var width = this.props.panelWidth;
    return (
      <View style={styles.container}>
        <ScrollView
          automaticallyAdjustContentInsets={false}
          scrollEventThrottle={16 /* get all events */ }
          onScroll={Animated.event(
            [{nativeEvent: {contentOffset: {x: this.state.scrollX}}}]  // nested event mapping
          )}
          contentContainerStyle={{flex: 1, padding: 10}}
          pagingEnabled={true}
          horizontal={true}>
          <View style={[styles.page, {width}]}>
            <Image
              style={{width: 180, height: 180}}
              source={HAWK_PIC}
            />
            <Text style={styles.text}>
              {'I\'ll find something to put here.'}
            </Text>
          </View>
          <View style={[styles.page, {width}]}>
            <Text style={styles.text}>{'And here.'}</Text>
          </View>
          <View style={[styles.page, {width}]}>
            <Text>{'But not here.'}</Text>
          </View>
        </ScrollView>
        <Animated.Image
          pointerEvents="none"
          style={[styles.bunny, {transform: [
            {
              translateX: this.state.scrollX.interpolate({
                inputRange: [0, width, 2 * width],
                outputRange: [0, 0, width / 3],
                extrapolate: 'clamp',
              }),
            },
            {
              translateY: this.state.scrollX.interpolate({
                inputRange: [0, width, 2 * width],
                outputRange: [0, -200, -260],
                extrapolate: 'clamp',
              }),
            },
            {
              scale: this.state.scrollX.interpolate({
                inputRange: [0, width, 2 * width],
                outputRange: [0.5, 0.5, 2],
                extrapolate: 'clamp',
              }),
            },
          ]}]}
          source={BUNNY_PIC}
        />
      </View>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    backgroundColor: 'transparent',
    flex: 1,
  },
  text: {
    padding: 4,
    paddingBottom: 10,
    fontWeight: 'bold',
    fontSize: 18,
    backgroundColor: 'transparent',
  },
  bunny: {
    backgroundColor: 'transparent',
    position: 'absolute',
    height: 160,
    width: 160,
  },
  page: {
    alignItems: 'center',
    justifyContent: 'flex-end',
  },
});

var HAWK_PIC = {uri: 'https://scontent-sea1-1.xx.fbcdn.net/hphotos-xfa1/t39.1997-6/10734304_1562225620659674_837511701_n.png'};
var BUNNY_PIC = {uri: 'https://scontent-sea1-1.xx.fbcdn.net/hphotos-xaf1/t39.1997-6/851564_531111380292237_1898871086_n.png'};

module.exports = AnExScroll;
<|endoftext|>


<commit_before>'use strict';

// external deps
var ObjectId = require('mongodb').ObjectId;

// internal deps
require('mongodb-toolkit');
var BaseManager = require('module-toolkit').BaseManager;
var BateeqModels = require('bateeq-models');
var map = BateeqModels.map;
var generateCode = require('../../utils/code-generator');
var TransferInManager = require('./transfer-in-doc-manager');
var TransferInDoc = BateeqModels.inventory.TransferInDoc;
var TransferInItem = BateeqModels.inventory.TransferInItem;

const moduleId = "EFR-TB/BBT";

module.exports = class TokoTerimaBarangBaruManager extends TransferInManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.inventory.TransferInDoc);
        this.spkDocCollection = this.db.use(map.merchandiser.SPKDoc);

        var StorageManager = require('../master/storage-manager');
        this.storageManager = new StorageManager(db, user);

        var ItemManager = require('../master/item-manager');
        this.itemManager = new ItemManager(db, user);

        var InventoryManager = require('./inventory-manager');
        this.inventoryManager = new InventoryManager(db, user);

        var TransferInDocManager = require('./transfer-in-doc-manager');
        this.transferInDocManager = new TransferInDocManager(db, user);

        var ModuleManager = require('../master/module-manager');
        this.moduleManager = new ModuleManager(db, user);

        var SPKManager = require('../merchandiser/efr-pk-manager');
        this.spkManager = new SPKManager(db, user);

        var ExpeditionManager = require('./efr-kb-exp-manager');
        this.expeditionManager = new ExpeditionManager(db, user);
    }

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

        return new Promise((resolve, reject) => {
            var deleted = {
                _deleted: false,
                isDraft: false
            }, keywordFilter = {};

            var regex = new RegExp("EFR\-PK/\PBJ|EFR\-PK/\PBR", "i");
            var filterCode = {
                'code': {
                    '$regex': regex
                },
                // 'expeditionDocumentId': { "$ne": {} }
            };
            var destination;
            if (Object.getOwnPropertyNames(paging.filter).length != 0) {
                destination =
                    {
                        "destination.code":
                        {
                            $in: paging.filter
                        }
                    }
            }

            var isReceived = {
                isReceived: false
            };

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

                var filterPackingList = {
                    'packingList': {
                        '$regex': regex
                    }
                };
                keywordFilter = {
                    '$or': [filterPackingList]
                };
            }

            var query = {
                $and: [
                    deleted,
                    filterCode,
                    isReceived,
                    destination,
                    keywordFilter
                ]
            }

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

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

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

            var filterCode = {
                'code': {
                    '$regex': regex
                }
            };
            keywordFilter = {
                '$or': [filterCode]
            };
        }
        query = { '$and': [deletedFilter, paging.filter, keywordFilter] }
        return query;
    }
    // getById(id) {
    //     return new Promise((resolve, reject) => {
    //         var query = {
    //             _id: new ObjectId(id),
    //             _deleted: false
    //         };
    //         this.getSingleByQuery(query)
    //             .then(transferInDoc => {
    //                 resolve(transferInDoc);
    //             })
    //             .catch(e => {
    //                 reject(e);
    //             });
    //     });
    // }

    // getByIdOrDefault(id) {
    //     return new Promise((resolve, reject) => {
    //         var query = {
    //             _id: new ObjectId(id),
    //             _deleted: false
    //         };
    //         this.getSingleOrDefaultByQuery(query)
    //             .then(transferInDoc => {
    //                 resolve(transferInDoc);
    //             })
    //             .catch(e => {
    //                 reject(e);
    //             });
    //     });
    // }

    // getSingleByQuery(query) {
    //     return new Promise((resolve, reject) => {
    //         this.collection
    //             .single(query)
    //             .then(transferInDoc => {
    //                 resolve(transferInDoc);
    //             })
    //             .catch(e => {
    //                 reject(e);
    //             });
    //     })
    // }

    // getSingleOrDefaultByQuery(query) {
    //     return new Promise((resolve, reject) => {
    //         this.collection
    //             .singleOrDefault(query)
    //             .then(transferInDoc => {
    //                 resolve(transferInDoc);
    //             })
    //             .catch(e => {
    //                 reject(e);
    //             });
    //     })
    // }

    getPendingSPKById(id) {
        return new Promise((resolve, reject) => {
            var query = {
                _id: new ObjectId(id),
                _deleted: false,
                isReceived: false,
                isDraft: false
            };
            this.spkDocCollection.singleOrDefault(query)
                .then(SPKDoc => {
                    SPKDoc.password = '';
                    SPKDoc._id = undefined;
                    resolve(SPKDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    // create(transferInDoc) {
    //     return new Promise((resolve, reject) => {
    //         this._validate(transferInDoc)
    //             .then(validTransferInDoc => {
    //                 validTransferInDoc.code = generateCode(moduleId);

    //                 //kaga transfer in yang qty 0
    //                 var length = validTransferInDoc.items.length;
    //                 for (var i = 0; i < length;) {
    //                     var item = validTransferInDoc.items[i];
    //                     if (item.quantity == 0) {
    //                         validTransferInDoc.items.splice(i, 1);
    //                     }
    //                     else {
    //                         i++
    //                     }
    //                     length = validTransferInDoc.items.length;
    //                 }

    //                 this.transferInDocManager.create(validTransferInDoc)
    //                     .then(id => {
    //                         var reference = transferInDoc.reference;
    //                         var updateSPK = this.spkManager.updateReceivedByPackingList(reference);
    //                         var updateExpedition = this.expeditionManager.updateReceivedByPackingList(reference);

    //                         Promise.all([updateSPK, updateExpedition]).then
    //                             .then(result => {
    //                                 resolve(id);
    //                             }).catch(e => {
    //                                 reject(e);
    //                             });
    //                     })
    //                     .catch(e => {
    //                         reject(e);
    //                     })
    //             })
    //             .catch(e => {
    //                 reject(e);
    //             })
    //     });
    // }

    _beforeInsert(validTransferInDoc) {
        return super._beforeInsert(validTransferInDoc)
            .then(validTransferInDoc => {
                validTransferInDoc.code = generateCode(moduleId);
                //kaga transfer in yang qty 0
                var length = validTransferInDoc.items.length;
                for (var i = 0; i < length;) {
                    var item = validTransferInDoc.items[i];
                    if (item.quantity == 0) {
                        validTransferInDoc.items.splice(i, 1);
                    }
                    else {
                        i++;
                    }
                    length = validTransferInDoc.items.length;
                }
                return Promise.resolve(validTransferInDoc);
            }).catch(e => {
                throw e;
            })
    }

    _afterInsert(id) {
        return super._afterInsert(id)
            .then(id => {
                return this.getSingleById(id)
                    .then(transferInDoc => {
                        var reference = transferInDoc.reference;
                        var updateSPK = this.spkManager.updateReceivedByPackingList(reference);
                        var updateExpedition = this.expeditionManager.updateReceivedByPackingList(reference);

                        return Promise.all([updateSPK, updateExpedition])
                            .then(result => {
                                return id;
                            });
                    });
            })
            .catch(e => {
                throw e;
            })
    }

    update(transferInDoc) {
        return new Promise((resolve, reject) => {
            this._validate(transferInDoc)
                .then(validTransferInDoc => {
                    this.transferInDocManager.update(validTransferInDoc)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    delete(transferInDoc) {
        return new Promise((resolve, reject) => {
            this._validate(transferInDoc)
                .then(validTransferInDoc => {
                    validTransferInDoc._deleted = true;
                    this.transferInDocManager.update(validTransferInDoc)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    _validate(transferInDoc) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var getSpk = this.spkManager.getByPL(transferInDoc.reference);
            var getExpedition = this.expeditionManager.getByPackingList(transferInDoc.reference);

            Promise.all([getSpk, getExpedition]).
                then(results => {
                    var spkDoc = results[0];
                    var expeditionDoc = results[1];
                    if (spkDoc) {
                        if (expeditionDoc.data.length == 0) {
                            errors["reference"] = "Packing List belum ada di Ekspedisi";
                        }
                        if (transferInDoc.password != spkDoc.password) {
                            errors["password"] = "invalid password";
                        }
                        if (transferInDoc.reference == "") {
                            errors["reference"] = "reference is required";
                        }
                        if (transferInDoc.items.length <= 0) {
                            errors["items"] = "no item(s) to transfer in";
                        }
                        if (spkDoc.sourceId.toString() != transferInDoc.sourceId.toString()) {
                            errors["sourceId"] = "invalid sourceId";
                        }
                        if (spkDoc.destinationId.toString() != transferInDoc.destinationId.toString()) {
                            errors["destinationId"] = "invalid destinationId";
                        }
                        if (spkDoc.isReceived) {
                            errors["isReceived"] = "this reference already received";
                        }
                        var index = 0;
                        var itemErrors = [];
                        for (var item of transferInDoc.items) {
                            var itemError = {};
                            item.quantity = item.sendQuantity;
                            if (item.sendQuantity < 0)
                                itemError["sendQuantity"] = "items should not less than 0 quantity";
                            else
                                if (item.sendQuantity != spkDoc.items[index].sendQuantity)
                                    if (item.remark == "")
                                        itemError["remark"] = "Masukkan no referensi berita acara";
                            index++;
                            itemErrors.push(itemError);
                        }
                        for (var itemError of itemErrors) {
                            for (var prop in itemError) {
                                errors.items = itemErrors;
                                break;
                            }
                            if (errors.items)
                                break;
                        }
                        for (var prop in errors) {
                            var ValidationError = require('module-toolkit').ValidationError;
                            reject(new ValidationError('data does not pass validation', errors));
                        }
                    }
                    else {
                        errors["reference"] = "reference not found";
                        var ValidationError = require('module-toolkit').ValidationError;
                        reject(new ValidationError('data does not pass validation', errors));
                    }
                    transferInDoc = new TransferInDoc(transferInDoc);
                    transferInDoc.stamp(this.user.username, 'manager');
                    resolve(transferInDoc);

                })
                .catch(e => {
                    reject(e);
                })
        });
    }
};<commit_msg>update, from sendQuantity to quantity<commit_after>'use strict';

// external deps
var ObjectId = require('mongodb').ObjectId;

// internal deps
require('mongodb-toolkit');
var BaseManager = require('module-toolkit').BaseManager;
var BateeqModels = require('bateeq-models');
var map = BateeqModels.map;
var generateCode = require('../../utils/code-generator');
var TransferInManager = require('./transfer-in-doc-manager');
var TransferInDoc = BateeqModels.inventory.TransferInDoc;
var TransferInItem = BateeqModels.inventory.TransferInItem;

const moduleId = "EFR-TB/BBT";

module.exports = class TokoTerimaBarangBaruManager extends TransferInManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.inventory.TransferInDoc);
        this.spkDocCollection = this.db.use(map.merchandiser.SPKDoc);

        var StorageManager = require('../master/storage-manager');
        this.storageManager = new StorageManager(db, user);

        var ItemManager = require('../master/item-manager');
        this.itemManager = new ItemManager(db, user);

        var InventoryManager = require('./inventory-manager');
        this.inventoryManager = new InventoryManager(db, user);

        var TransferInDocManager = require('./transfer-in-doc-manager');
        this.transferInDocManager = new TransferInDocManager(db, user);

        var ModuleManager = require('../master/module-manager');
        this.moduleManager = new ModuleManager(db, user);

        var SPKManager = require('../merchandiser/efr-pk-manager');
        this.spkManager = new SPKManager(db, user);

        var ExpeditionManager = require('./efr-kb-exp-manager');
        this.expeditionManager = new ExpeditionManager(db, user);
    }

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

        return new Promise((resolve, reject) => {
            var deleted = {
                _deleted: false,
                isDraft: false
            }, keywordFilter = {};

            var regex = new RegExp("EFR\-PK/\PBJ|EFR\-PK/\PBR", "i");
            var filterCode = {
                'code': {
                    '$regex': regex
                },
                // 'expeditionDocumentId': { "$ne": {} }
            };
            var destination;
            if (Object.getOwnPropertyNames(paging.filter).length != 0) {
                destination =
                    {
                        "destination.code":
                        {
                            $in: paging.filter
                        }
                    }
            }

            var isReceived = {
                isReceived: false
            };

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

                var filterPackingList = {
                    'packingList': {
                        '$regex': regex
                    }
                };
                keywordFilter = {
                    '$or': [filterPackingList]
                };
            }

            var query = {
                $and: [
                    deleted,
                    filterCode,
                    isReceived,
                    destination,
                    keywordFilter
                ]
            }

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

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

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

            var filterCode = {
                'code': {
                    '$regex': regex
                }
            };
            keywordFilter = {
                '$or': [filterCode]
            };
        }
        query = { '$and': [deletedFilter, paging.filter, keywordFilter] }
        return query;
    }
    // getById(id) {
    //     return new Promise((resolve, reject) => {
    //         var query = {
    //             _id: new ObjectId(id),
    //             _deleted: false
    //         };
    //         this.getSingleByQuery(query)
    //             .then(transferInDoc => {
    //                 resolve(transferInDoc);
    //             })
    //             .catch(e => {
    //                 reject(e);
    //             });
    //     });
    // }

    // getByIdOrDefault(id) {
    //     return new Promise((resolve, reject) => {
    //         var query = {
    //             _id: new ObjectId(id),
    //             _deleted: false
    //         };
    //         this.getSingleOrDefaultByQuery(query)
    //             .then(transferInDoc => {
    //                 resolve(transferInDoc);
    //             })
    //             .catch(e => {
    //                 reject(e);
    //             });
    //     });
    // }

    // getSingleByQuery(query) {
    //     return new Promise((resolve, reject) => {
    //         this.collection
    //             .single(query)
    //             .then(transferInDoc => {
    //                 resolve(transferInDoc);
    //             })
    //             .catch(e => {
    //                 reject(e);
    //             });
    //     })
    // }

    // getSingleOrDefaultByQuery(query) {
    //     return new Promise((resolve, reject) => {
    //         this.collection
    //             .singleOrDefault(query)
    //             .then(transferInDoc => {
    //                 resolve(transferInDoc);
    //             })
    //             .catch(e => {
    //                 reject(e);
    //             });
    //     })
    // }

    getPendingSPKById(id) {
        return new Promise((resolve, reject) => {
            var query = {
                _id: new ObjectId(id),
                _deleted: false,
                isReceived: false,
                isDraft: false
            };
            this.spkDocCollection.singleOrDefault(query)
                .then(SPKDoc => {
                    SPKDoc.password = '';
                    SPKDoc._id = undefined;
                    resolve(SPKDoc);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

    // create(transferInDoc) {
    //     return new Promise((resolve, reject) => {
    //         this._validate(transferInDoc)
    //             .then(validTransferInDoc => {
    //                 validTransferInDoc.code = generateCode(moduleId);

    //                 //kaga transfer in yang qty 0
    //                 var length = validTransferInDoc.items.length;
    //                 for (var i = 0; i < length;) {
    //                     var item = validTransferInDoc.items[i];
    //                     if (item.quantity == 0) {
    //                         validTransferInDoc.items.splice(i, 1);
    //                     }
    //                     else {
    //                         i++
    //                     }
    //                     length = validTransferInDoc.items.length;
    //                 }

    //                 this.transferInDocManager.create(validTransferInDoc)
    //                     .then(id => {
    //                         var reference = transferInDoc.reference;
    //                         var updateSPK = this.spkManager.updateReceivedByPackingList(reference);
    //                         var updateExpedition = this.expeditionManager.updateReceivedByPackingList(reference);

    //                         Promise.all([updateSPK, updateExpedition]).then
    //                             .then(result => {
    //                                 resolve(id);
    //                             }).catch(e => {
    //                                 reject(e);
    //                             });
    //                     })
    //                     .catch(e => {
    //                         reject(e);
    //                     })
    //             })
    //             .catch(e => {
    //                 reject(e);
    //             })
    //     });
    // }

    _beforeInsert(validTransferInDoc) {
        return super._beforeInsert(validTransferInDoc)
            .then(validTransferInDoc => {
                validTransferInDoc.code = generateCode(moduleId);
                //kaga transfer in yang qty 0
                var length = validTransferInDoc.items.length;
                for (var i = 0; i < length;) {
                    var item = validTransferInDoc.items[i];
                    if (item.quantity == 0) {
                        validTransferInDoc.items.splice(i, 1);
                    }
                    else {
                        i++;
                    }
                    length = validTransferInDoc.items.length;
                }
                return Promise.resolve(validTransferInDoc);
            }).catch(e => {
                throw e;
            })
    }

    _afterInsert(id) {
        return super._afterInsert(id)
            .then(id => {
                return this.getSingleById(id)
                    .then(transferInDoc => {
                        var reference = transferInDoc.reference;
                        var updateSPK = this.spkManager.updateReceivedByPackingList(reference);
                        var updateExpedition = this.expeditionManager.updateReceivedByPackingList(reference);

                        return Promise.all([updateSPK, updateExpedition])
                            .then(result => {
                                return id;
                            });
                    });
            })
            .catch(e => {
                throw e;
            })
    }

    update(transferInDoc) {
        return new Promise((resolve, reject) => {
            this._validate(transferInDoc)
                .then(validTransferInDoc => {
                    this.transferInDocManager.update(validTransferInDoc)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    delete(transferInDoc) {
        return new Promise((resolve, reject) => {
            this._validate(transferInDoc)
                .then(validTransferInDoc => {
                    validTransferInDoc._deleted = true;
                    this.transferInDocManager.update(validTransferInDoc)
                        .then(id => {
                            resolve(id);
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    _validate(transferInDoc) {
        var errors = {};
        return new Promise((resolve, reject) => {
            var getSpk = this.spkManager.getByPL(transferInDoc.reference);
            var getExpedition = this.expeditionManager.getByPackingList(transferInDoc.reference);

            Promise.all([getSpk, getExpedition]).
                then(results => {
                    var spkDoc = results[0];
                    var expeditionDoc = results[1];
                    if (spkDoc) {
                        // if (expeditionDoc.data.length == 0) {
                        //     errors["reference"] = "Packing List belum ada di Ekspedisi";
                        // }
                        if (transferInDoc.password != spkDoc.password) {
                            errors["password"] = "invalid password";
                        }
                        if (transferInDoc.reference == "") {
                            errors["reference"] = "reference is required";
                        }
                        if (transferInDoc.items.length <= 0) {
                            errors["items"] = "no item(s) to transfer in";
                        }
                        if (spkDoc.sourceId.toString() != transferInDoc.sourceId.toString()) {
                            errors["sourceId"] = "invalid sourceId";
                        }
                        if (spkDoc.destinationId.toString() != transferInDoc.destinationId.toString()) {
                            errors["destinationId"] = "invalid destinationId";
                        }
                        if (spkDoc.isReceived) {
                            errors["isReceived"] = "this reference already received";
                        }
                        var index = 0;
                        var itemErrors = [];
                        for (var item of transferInDoc.items) {
                            var itemError = {};
                            item.quantity = item.quantity;
                            if (item.quantity < 0)
                                itemError["quantity"] = "items should not less than 0 quantity";
                            else
                                if (item.quantity != spkDoc.items[index].quantity)
                                    if (item.remark == "")
                                        itemError["remark"] = "Masukkan no referensi berita acara";
                            index++;
                            itemErrors.push(itemError);
                        }
                        for (var itemError of itemErrors) {
                            for (var prop in itemError) {
                                errors.items = itemErrors;
                                break;
                            }
                            if (errors.items)
                                break;
                        }
                        for (var prop in errors) {
                            var ValidationError = require('module-toolkit').ValidationError;
                            reject(new ValidationError('data does not pass validation', errors));
                        }
                    }
                    else {
                        errors["reference"] = "reference not found";
                        var ValidationError = require('module-toolkit').ValidationError;
                        reject(new ValidationError('data does not pass validation', errors));
                    }
                    transferInDoc = new TransferInDoc(transferInDoc);
                    transferInDoc.stamp(this.user.username, 'manager');
                    resolve(transferInDoc);

                })
                .catch(e => {
                    reject(e);
                })
        });
    }
};<|endoftext|>