Skip to content

Instantly share code, notes, and snippets.

@Jon-Biz
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jon-Biz/5e1b5e1afdbb4a17c360 to your computer and use it in GitHub Desktop.
Save Jon-Biz/5e1b5e1afdbb4a17c360 to your computer and use it in GitHub Desktop.
var UniversalCollection = require('../universal-collection')
, _ = require('lodash')
, stateHelper = require('../../models/item/state-helpers.js')
, getStateObject = require('../../models/item/getStateObject.js')
, ItemSupplierStateCollection
, checkStateHelper = function(where, doc){
return stateHelper[where](getStateObject(doc))
}
/**
* Only two options for this collection:
* opts.supplier - A string, the branch ID of the supplier this collection is for
* opts.where - An string that is the name of a method on `item.state-helpers`
*/
ItemSupplierStateCollection = UniversalCollection.extend({
_id: 'ItemSupplierByState'
, afterInit: function (opts) {
if(typeof opts.supplier !== 'string' || opts.supplier.indexOf('branch:') < 0) throw new Error('opts.supplier must be a branch id')
if(!_.isString(opts.where)) throw new Error('opts.where must be a string')
if(!_.has(stateHelper,opts.where)) throw new Error('opts.where is not the name of an existing stateHelper method')
// convenience method to check for the specific state that was passed in
this.checkState = _.curry(checkStateHelper)(opts.where)
this.options = opts
this.options.type = opts.supplier.replace(/branch:/,'branch-') + '-' + opts.where
//TODO - create a view that returns active/offrent items bySupplier
this.options.keys = [
opts.supplier + '-state-scheduled'
, opts.supplier + '-state-onrent'
, opts.supplier + '-state-transferring'
, opts.supplier + '-state-service'
, opts.supplier + '-state-offrentpending'
]
}
, _fetch: function (db, ctx, cb) {
var self = this
//TODO - as pointed out above, this is wat
db.design('items').view('bySupplierByState').query({keys: this.options.keys, include_docs:true}, function (e, results) {
if(e) return cb(e)
var docs = _(results.rows)
.pluck('doc')
.map(function (doc) {
// if(true){
if(self.checkState(doc)){
doc.type = self.options.type
return doc
}
else{
return false
}
})
.compact()
.value()
cb(null, docs)
})
}
, belongs: function (doc) {
return doc.type === this.options.type
}
, onChange: function (doc, db, ctx, cb) {
if(doc.type === 'item'
&& doc.supplier === this.options.supplier
&& this.checkState(doc)
){
doc.type = this.options.type
cb(null, doc)
}
}
})
module.exports = ItemSupplierStateCollection
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment