<commit_before>/*
 * Some portions extracted from:
 * Parse JavaScript SDK
 * Version: 1.4.2
 */

import Ember from 'ember';
import DS from 'ember-data';

var get = Ember.get,
    forEach = Ember.ArrayPolyfills.forEach;

export default DS.RESTAdapter.extend({
  PARSE_APPLICATION_ID: null,
  PARSE_JAVASCRIPT_KEY: null,

  host: 'https://api.parse.com',
  namespace: '1',
  classesPath: 'classes',
  parseClientVersion: 'js1.4.2',

  init() {
    this._super();

    this.set('applicationId', this.get('PARSE_APPLICATION_ID'));
    this.set('javascriptKey', this.get('PARSE_JAVASCRIPT_KEY'));
    this.set('installationId', this._getInstallationId());
    this.set('sessionToken', null);
    this.set('userId', null);

    /*
     * avoid pre-flight.
     * Parse._ajax
     */
    this.set('headers', {'Content-Type': 'text/plain'});
  },

  _getInstallationId() {
    /*
     * Parse._getInstallationId
     */
    var hexOctet = function() {
      return (
        Math.floor((1+Math.random())*0x10000).toString(16).substring(1)
      );
    };

    return (
      hexOctet() + hexOctet() + "-" +
      hexOctet() + "-" +
      hexOctet() + "-" +
      hexOctet() + "-" +
      hexOctet() + hexOctet() + hexOctet());
  },

  ajaxOptions(url, type, options) {
    var hash = options || {};
    hash.url = url;
    hash.type = type;
    hash.dataType = 'json';
    hash.context = this;

    if ((hash.data && type !== 'GET')) {
      hash.contentType = 'application/json; charset=utf-8';

      // Parse auth stuff
      hash.data._ClientVersion = this.get('parseClientVersion');
      hash.data._ApplicationId = this.get('applicationId');
      hash.data._JavaScriptKey = this.get('javascriptKey');
      hash.data._InstallationId = this.get('installationId');

      var _sessionToken = this.get('sessionToken');
      if (_sessionToken) {
        hash.data._SessionToken = _sessionToken;
      }

      hash.data = JSON.stringify(hash.data);
    }

    var headers = get(this, 'headers');
    if (headers !== undefined) {
      hash.beforeSend = function (xhr) {
        forEach.call(Ember.keys(headers), function(key) {
          xhr.setRequestHeader(key, headers[key]);
        });
      };
    }

    return hash;
  },

  ajaxError: function(jqXHR, responseText, errorThrown) {
    if (jqXHR.responseJSON.error === 'invalid session token') {
      // If user is not authenticated invalidate session
      this.container.lookup('service:session').invalidate();
    }

    return this._super(jqXHR, responseText, errorThrown);
  },

  pathForType(type) {
    if ('user' === type) {
      return 'users';

    } else if ('login' === type) {
      return type;

    } else if ('requestPasswordReset' === type) {
      return type;

    } else {
      return this.classesPath + '/' + this.parsePathForType(type);
    }
  },

  // Using TitleStyle is recommended by Parse
  parsePathForType(type) {
    return Ember.String.capitalize(Ember.String.camelize(type));
  },

  parseClassName: function (key) {
    return Ember.String.capitalize(key);
  },

  /**
  * Because Parse doesn't return a full set of properties on the
  * responses to updates, we want to perform a merge of the response
  * properties onto existing data so that the record maintains
  * latest data.
  */
  createRecord(store, type, record) {
    var serializer = store.serializerFor(type.typeKey),
      data = {},
      adapter = this,
      ParseACL = record.record.ParseACL;

    if (ParseACL && ParseACL.owner) {
      data.ACL = {
        [ParseACL.owner]: {
          read: true,
          write: true
        }
      };
    }

    serializer.serializeIntoHash(data, type, record, {includeId: true});

    var promise = new Ember.RSVP.Promise(function(resolve, reject) {
      adapter.ajax(adapter.buildURL(type.typeKey), 'POST', {data: data})
        .then(function(json) {
          var completed = Ember.merge(data, json);
          resolve(completed);
        }, function(reason) {
          var err = `Code ${reason.responseJSON.code}: ${reason.responseJSON.error}`;
          reject(new Error(err));
        });
    });

    return promise;
  },

  /**
  * Because Parse doesn't return a full set of properties on the
  * responses to updates, we want to perform a merge of the response
  * properties onto existing data so that the record maintains
  * latest data.
  */
  updateRecord(store, type, record) {
    var serializer = store.serializerFor(type.typeKey),
      id = record.id,
      sendDeletes = false,
      deleteds = {},
      data = {},
      adapter = this;

    serializer.serializeIntoHash(data, type, record);

    type.eachRelationship(function(key) {
      if (data[key] && data[key].deleteds) {
        deleteds[key] = data[key].deleteds;
        delete data[key].deleteds;
        sendDeletes = true;
      }
    });

    var promise = new Ember.RSVP.Promise(function(resolve, reject) {
      if (sendDeletes) {
        adapter.ajax(adapter.buildURL(type.typeKey, id), 'PUT', {data: deleteds})
          .then(function() {
            adapter.ajax(adapter.buildURL(type.typeKey, id), 'PUT', {data: data})
              .then(function(updates) {
                // This is the essential bit - merge response data onto existing data.
                resolve(Ember.merge(data, updates));
              }, function(reason) {
                reject('Failed to save parent in relation: ' + reason.response.JSON);
              });
          });
      } else {
        adapter.ajax(adapter.buildURL(type.typeKey, id), 'PUT', {data: data})
          .then(function(json) {
            // This is the essential bit - merge response data onto existing data.
            resolve( Ember.merge(data, json));
          }, function(reason) {
            reject(reason.responseJSON);
          });
      }
    });

    return promise;
  },

  deleteRecord: function(store, type, snapshot) {
    var id = snapshot.id,
        data = {_method: 'DELETE'};

    return this.ajax(this.buildURL(type.typeKey, id, snapshot), 'POST', {data: data});
  },

  find(store, type, id, snapshot) {
    var data = {_method: 'GET'};
    return this.ajax(this.buildURL(type.typeKey, id, snapshot), 'POST', {data: data});
  },

  findAll(store, type, sinceToken) {
    var query = {};

    if (sinceToken) {
      query.since = sinceToken;
    }

    query.where = {};
    query._method = 'GET';

    return this.ajax(this.buildURL(type.typeKey), 'POST', {data: query});
  },

  // findBelongsTo: function(store, snapshot, url, relationship) {
  //   debugger;
  //   var id   = snapshot.id;
  //   var type = snapshot.typeKey;

  //   return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET');
  // },

  /**
  * Implementation of a hasMany that provides a Relation query for Parse
  * objects.
  */
  findHasMany(store, record, relatedInfo) {
    var query = {
      where: {
        '$realtedTo': {
          'object': {
            '__type': 'Pointer',
            'className': this.parseClassName(record.typeKey),
            'objectId': this.record.id
          },
          key: relatedInfo.key
        }
      }
    };

    // the request is to the related type and not the type for the record.
    // the query is where there is a pointer to this record.
    return this.ajax(
              this.buildURL(relatedInfo.type.typeKey), 'GET', {data: query});
  },

  /**
  * Implementation of findQuery that automatically wraps query in a
  * JSON string.
  *
  * @example
  *     this.store.find('comment', {
  *       where: {
  *         post: {
  *             "__type":  "Pointer",
  *             "className": "Post",
  *             "objectId": post.get('id')
  *         }
  *       }
  *     });
  */
  findQuery(store, type, query) {
    if (query.where && 'string' !== Ember.typeOf(query.where)) {
      query.where = JSON.stringify(query.where);
    }

    // Pass to _super()
    return this._super(store, type, query);
  }
});
<commit_msg>Remove default findBelongsTo<commit_after>/*
 * Some portions extracted from:
 * Parse JavaScript SDK
 * Version: 1.4.2
 */

import Ember from 'ember';
import DS from 'ember-data';

var get = Ember.get,
    forEach = Ember.ArrayPolyfills.forEach;

export default DS.RESTAdapter.extend({
  PARSE_APPLICATION_ID: null,
  PARSE_JAVASCRIPT_KEY: null,

  host: 'https://api.parse.com',
  namespace: '1',
  classesPath: 'classes',
  parseClientVersion: 'js1.4.2',

  init() {
    this._super();

    this.set('applicationId', this.get('PARSE_APPLICATION_ID'));
    this.set('javascriptKey', this.get('PARSE_JAVASCRIPT_KEY'));
    this.set('installationId', this._getInstallationId());
    this.set('sessionToken', null);
    this.set('userId', null);

    /*
     * avoid pre-flight.
     * Parse._ajax
     */
    this.set('headers', {'Content-Type': 'text/plain'});
  },

  _getInstallationId() {
    /*
     * Parse._getInstallationId
     */
    var hexOctet = function() {
      return (
        Math.floor((1+Math.random())*0x10000).toString(16).substring(1)
      );
    };

    return (
      hexOctet() + hexOctet() + "-" +
      hexOctet() + "-" +
      hexOctet() + "-" +
      hexOctet() + "-" +
      hexOctet() + hexOctet() + hexOctet());
  },

  ajaxOptions(url, type, options) {
    var hash = options || {};
    hash.url = url;
    hash.type = type;
    hash.dataType = 'json';
    hash.context = this;

    if ((hash.data && type !== 'GET')) {
      hash.contentType = 'application/json; charset=utf-8';

      // Parse auth stuff
      hash.data._ClientVersion = this.get('parseClientVersion');
      hash.data._ApplicationId = this.get('applicationId');
      hash.data._JavaScriptKey = this.get('javascriptKey');
      hash.data._InstallationId = this.get('installationId');

      var _sessionToken = this.get('sessionToken');
      if (_sessionToken) {
        hash.data._SessionToken = _sessionToken;
      }

      hash.data = JSON.stringify(hash.data);
    }

    var headers = get(this, 'headers');
    if (headers !== undefined) {
      hash.beforeSend = function (xhr) {
        forEach.call(Ember.keys(headers), function(key) {
          xhr.setRequestHeader(key, headers[key]);
        });
      };
    }

    return hash;
  },

  ajaxError: function(jqXHR, responseText, errorThrown) {
    if (jqXHR.responseJSON.error === 'invalid session token') {
      // If user is not authenticated invalidate session
      this.container.lookup('service:session').invalidate();
    }

    return this._super(jqXHR, responseText, errorThrown);
  },

  pathForType(type) {
    if ('user' === type) {
      return 'users';

    } else if ('login' === type) {
      return type;

    } else if ('requestPasswordReset' === type) {
      return type;

    } else {
      return this.classesPath + '/' + this.parsePathForType(type);
    }
  },

  // Using TitleStyle is recommended by Parse
  parsePathForType(type) {
    return Ember.String.capitalize(Ember.String.camelize(type));
  },

  parseClassName: function (key) {
    return Ember.String.capitalize(key);
  },

  /**
  * Because Parse doesn't return a full set of properties on the
  * responses to updates, we want to perform a merge of the response
  * properties onto existing data so that the record maintains
  * latest data.
  */
  createRecord(store, type, record) {
    var serializer = store.serializerFor(type.typeKey),
      data = {},
      adapter = this,
      ParseACL = record.record.ParseACL;

    if (ParseACL && ParseACL.owner) {
      data.ACL = {
        [ParseACL.owner]: {
          read: true,
          write: true
        }
      };
    }

    serializer.serializeIntoHash(data, type, record, {includeId: true});

    var promise = new Ember.RSVP.Promise(function(resolve, reject) {
      adapter.ajax(adapter.buildURL(type.typeKey), 'POST', {data: data})
        .then(function(json) {
          var completed = Ember.merge(data, json);
          resolve(completed);
        }, function(reason) {
          var err = `Code ${reason.responseJSON.code}: ${reason.responseJSON.error}`;
          reject(new Error(err));
        });
    });

    return promise;
  },

  /**
  * Because Parse doesn't return a full set of properties on the
  * responses to updates, we want to perform a merge of the response
  * properties onto existing data so that the record maintains
  * latest data.
  */
  updateRecord(store, type, record) {
    var serializer = store.serializerFor(type.typeKey),
      id = record.id,
      sendDeletes = false,
      deleteds = {},
      data = {},
      adapter = this;

    serializer.serializeIntoHash(data, type, record);

    type.eachRelationship(function(key) {
      if (data[key] && data[key].deleteds) {
        deleteds[key] = data[key].deleteds;
        delete data[key].deleteds;
        sendDeletes = true;
      }
    });

    var promise = new Ember.RSVP.Promise(function(resolve, reject) {
      if (sendDeletes) {
        adapter.ajax(adapter.buildURL(type.typeKey, id), 'PUT', {data: deleteds})
          .then(function() {
            adapter.ajax(adapter.buildURL(type.typeKey, id), 'PUT', {data: data})
              .then(function(updates) {
                // This is the essential bit - merge response data onto existing data.
                resolve(Ember.merge(data, updates));
              }, function(reason) {
                reject('Failed to save parent in relation: ' + reason.response.JSON);
              });
          });
      } else {
        adapter.ajax(adapter.buildURL(type.typeKey, id), 'PUT', {data: data})
          .then(function(json) {
            // This is the essential bit - merge response data onto existing data.
            resolve( Ember.merge(data, json));
          }, function(reason) {
            reject(reason.responseJSON);
          });
      }
    });

    return promise;
  },

  deleteRecord: function(store, type, snapshot) {
    var id = snapshot.id,
        data = {_method: 'DELETE'};

    return this.ajax(this.buildURL(type.typeKey, id, snapshot), 'POST', {data: data});
  },

  find(store, type, id, snapshot) {
    var data = {_method: 'GET'};
    return this.ajax(this.buildURL(type.typeKey, id, snapshot), 'POST', {data: data});
  },

  findAll(store, type, sinceToken) {
    var query = {};

    if (sinceToken) {
      query.since = sinceToken;
    }

    query.where = {};
    query._method = 'GET';

    return this.ajax(this.buildURL(type.typeKey), 'POST', {data: query});
  },

  /**
  * Implementation of a hasMany that provides a Relation query for Parse
  * objects.
  */
  findHasMany(store, record, relatedInfo) {
    var query = {
      where: {
        '$realtedTo': {
          'object': {
            '__type': 'Pointer',
            'className': this.parseClassName(record.typeKey),
            'objectId': this.record.id
          },
          key: relatedInfo.key
        }
      }
    };

    // the request is to the related type and not the type for the record.
    // the query is where there is a pointer to this record.
    return this.ajax(
              this.buildURL(relatedInfo.type.typeKey), 'GET', {data: query});
  },

  /**
  * Implementation of findQuery that automatically wraps query in a
  * JSON string.
  *
  * @example
  *     this.store.find('comment', {
  *       where: {
  *         post: {
  *             "__type":  "Pointer",
  *             "className": "Post",
  *             "objectId": post.get('id')
  *         }
  *       }
  *     });
  */
  findQuery(store, type, query) {
    if (query.where && 'string' !== Ember.typeOf(query.where)) {
      query.where = JSON.stringify(query.where);
    }

    // Pass to _super()
    return this._super(store, type, query);
  }
});
<|endoftext|>


<commit_before>/**
 * Provides Form and input features.
 *
 * @module furnace
 * @submodule furnace-forms
 */
import Control from './abstract';
import Ember from 'ember';

import DS from 'ember-data';
import getName from 'furnace-forms/utils/get-name';
import ControlSupport from 'furnace-forms/mixins/controls/control-support';
import Proxy from 'furnace-forms/proxy';
/**
 * Panel control component proxy
 *
 * @class Panel
 * @namespace Furnace.Forms.Controls
 * @extends Furnace.Forms.Controls.Abstract
 * @protected
 */
export default Control.extend(ControlSupport,{
	_component : 'panel',

	'for' : null,

	modelName: Ember.computed.alias('_modelName'),

	init: function() {
//		if(this['for']===null) {
//			if(this.get('_panel.for.'+this._name)) {
//				this.reopen({
//					'for': Ember.computed.alias('_panel.for.'+this._name)
//				});
//			} else {
//				this.reopen({
//					'for': Ember.computed.alias('_panel.for')
//				});
//			}
//		}
		this._super();
		if(this._panel && this.get('for')===this.get('_panel.for')) {
			this.set('_path',this.get('_panel._path'));
		}
	},

	actions: {
		apply:function() {
			this._apply();
		},
		reset : function() {
			this._reset();
		},
	},

	setEnabled: function(enabled) {
		if(enabled!==this._enabled) {
			this.set('_enabled',enabled);
		}
		this.setFlag('isEnabled',this._enabled && (!this._panel || (this.get('_panel.isEnabled') && this.get('_panel.hasPrerequisites')!==false)));
	},
	_panelEnabledObserver:Ember.observer('_panel.hasPrerequisites,_panel.isEnabled',function() {
		this.setEnabled(this._enabled);
	}),

	_modelName : Ember.computed('for',function(key,value) {
		if(value)  {
			return value;
		}
		if(this.get('for')===this.get('_panel.for')) {
			return this.get('_panel._modelName');
		}
		else if(this.get('for')) {
			return getName(this.get('for'));
		}
		else {
			return null;
		}
	}),

	_targetName : function() {
		if(this.get('targetObject')) {
			return getName(this.get('targetObject'));
		}
		else {
			return null;
		}
	}.property('targetObject'),

	caption : null,

	_apply:function() {
		this._super();
		this.get('inputControls').invoke('_apply');
		if((!this._form || this.get('for')!==this._form.get('for')) && this.get('for') instanceof Proxy) {
			this.get('for')._apply();
		}
	},

	_reset:function(modelChanged) {
		this._super(modelChanged);
	},

}).reopenClass({

	generate : function(mixins,options) {
		options=options || {};
		mixins=mixins || [];
		if(!options['for']) {
//			if(options._panel && options._panel._isFormOption) {
//				options['for']=Ember.computed.alias('_panel.for');
//			} else

			if(options._name!==null && Ember.Enumerable.detect(options._panel.get('for'))) {
				if(options._panel.get('for') instanceof DS.ManyArray) {
					options['for']=Ember.computed('_panel.for',function() {
						return this.get('_panel.for').objectAt(this._name);
					});
				} else {
					options['for']=Ember.computed.alias('_panel.for.'+options._name);
				}
			}
			else if(options._panel.get('for') && options._panel.get('for.'+options._name)!==undefined) {
				options['for']=Ember.computed.alias('_panel.for.'+options._name);
			} else {
				options['for']=Ember.computed.alias('_panel.for');
			}
		}
		mixins.push(options);
		var typeKey=this.typeKey;
		var component = this.extend.apply(this,mixins);
		component.typeKey=typeKey;
		return component;
	}
});<commit_msg>Fixed a bug with panels generated computed for<commit_after>/**
 * Provides Form and input features.
 *
 * @module furnace
 * @submodule furnace-forms
 */
import Control from './abstract';
import Ember from 'ember';

import DS from 'ember-data';
import getName from 'furnace-forms/utils/get-name';
import ControlSupport from 'furnace-forms/mixins/controls/control-support';
import Proxy from 'furnace-forms/proxy';
/**
 * Panel control component proxy
 *
 * @class Panel
 * @namespace Furnace.Forms.Controls
 * @extends Furnace.Forms.Controls.Abstract
 * @protected
 */
export default Control.extend(ControlSupport,{
	_component : 'panel',

	'for' : null,

	modelName: Ember.computed.alias('_modelName'),

	init: function() {
//		if(this['for']===null) {
//			if(this.get('_panel.for.'+this._name)) {
//				this.reopen({
//					'for': Ember.computed.alias('_panel.for.'+this._name)
//				});
//			} else {
//				this.reopen({
//					'for': Ember.computed.alias('_panel.for')
//				});
//			}
//		}
		this._super();
		if(this._panel && this.get('for')===this.get('_panel.for')) {
			this.set('_path',this.get('_panel._path'));
		}
	},

	actions: {
		apply:function() {
			this._apply();
		},
		reset : function() {
			this._reset();
		},
	},

	setEnabled: function(enabled) {
		if(enabled!==this._enabled) {
			this.set('_enabled',enabled);
		}
		this.setFlag('isEnabled',this._enabled && (!this._panel || (this.get('_panel.isEnabled') && this.get('_panel.hasPrerequisites')!==false)));
	},
	_panelEnabledObserver:Ember.observer('_panel.hasPrerequisites,_panel.isEnabled',function() {
		this.setEnabled(this._enabled);
	}),

	_modelName : Ember.computed('for',function(key,value) {
		if(value)  {
			return value;
		}
		if(this.get('for')===this.get('_panel.for')) {
			return this.get('_panel._modelName');
		}
		else if(this.get('for')) {
			return getName(this.get('for'));
		}
		else {
			return null;
		}
	}),

	_targetName : function() {
		if(this.get('targetObject')) {
			return getName(this.get('targetObject'));
		}
		else {
			return null;
		}
	}.property('targetObject'),

	caption : null,

	_apply:function() {
		this._super();
		this.get('inputControls').invoke('_apply');
		if((!this._form || this.get('for')!==this._form.get('for')) && this.get('for') instanceof Proxy) {
			this.get('for')._apply();
		}
	},

	_reset:function(modelChanged) {
		this._super(modelChanged);
	},

}).reopenClass({

	generate : function(mixins,options) {
		options=options || {};
		mixins=mixins || [];
		if(!options['for']) {
//			if(options._panel && options._panel._isFormOption) {
//				options['for']=Ember.computed.alias('_panel.for');
//			} else

			if(options._name!==null && Ember.Enumerable.detect(options._panel.get('for'))) {
				if(options._panel.get('for') instanceof DS.ManyArray) {
					options['for']=Ember.computed('_panel.for',function() {
						if(!this.get('_panel.for')) {
							return undefined;
						}
						return this.get('_panel.for').objectAt(this._name);
					});
				} else {
					options['for']=Ember.computed.alias('_panel.for.'+options._name);
				}
			}
			else if(options._panel.get('for') && options._panel.get('for.'+options._name)!==undefined) {
				options['for']=Ember.computed.alias('_panel.for.'+options._name);
			} else {
				options['for']=Ember.computed.alias('_panel.for');
			}
		}
		mixins.push(options);
		var typeKey=this.typeKey;
		var component = this.extend.apply(this,mixins);
		component.typeKey=typeKey;
		return component;
	}
});<|endoftext|>


<commit_before>'use strict';

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

// internal deps
require('mongodb-toolkit');
var BaseManager = require('module-toolkit').BaseManager;
var ComponentHelper = require('./component-helper');

var BateeqModels = require('bateeq-models');
var Item = BateeqModels.master.Item;
var FinishedGoods = BateeqModels.master.FinishedGoods;
var Material = BateeqModels.master.Material;
var Sales = BateeqModels.sales.Sales;
var map = BateeqModels.map;

module.exports = class ItemManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.master.Item);
        this.salesCollection = this.db.use(map.sales.SalesDoc);
        this.salesReturnCollection = this.db.use(map.sales.SalesReturnDoc);
        this.componentHelper = new ComponentHelper(this);
    }

    upsertComponents(data) {
        return new Promise((resolve, reject) => {
            var tag = `#${data.code}`;
            var task = [];
            for (var component of data.components) {

                var item = component.item;
                var tags = (item.tags || '').split(",").filter(el => el && el.trim().length > 0);
                var tagIndex = tags.findIndex(t => {
                    return t == tag;
                });

                if (tagIndex < 0)
                    tags.push(tag);

                item.tags = tags.join(",");

                if (item._id)
                    task.push(this.update(item));
                else
                    task.push(this.create(item));
            }

            Promise.all(task)
                .then(results => {
                    var getItems = [];

                    for (var itemId of results)
                        getItems.push(this.getSingleById(itemId));

                    Promise.all(getItems)
                        .then(items => {
                            var index = 0;
                            for (var item of items) {
                                var component = data.components[index++];
                                component.itemId = item._id;
                                component.item = item;
                            }
                            this.collection.update(data).then(id => {
                                resolve(id);
                            });
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });

        });
    }

    create(data) {
        return new Promise((resolve, reject) => {
            this._validate(data)
                .then(validData => {
                    this.collection.insert(validData)
                        .then(id => {
                            validData._id = id;
                            this.upsertComponents(validData)
                                .then(id => {
                                    resolve(id);
                                })
                                .catch(e => {
                                    reject(e);
                                });
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    //update 15-6-2017
    update(data) {
        return new Promise((resolve, reject) => {
            this._validate(data)
                .then(validData => {
                    this.collection.update(validData)
                        .then(id => {
                            this.updateItemOnSalesDoc(validData)
                                .then(salesDocUpdate => {
                                    this.updateItemOnSalesReturnDoc(validData)
                                        .then(salesReturnUpDate => {
                                            resolve(id);
                                        })
                                        .catch(e => {
                                            reject(e);
                                        })
                                })
                                .catch(e => {
                                    reject(e);
                                })
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    getByCode(code) {
        return new Promise((resolve, reject) => {
            if (code === '')
                resolve(null);
            var query = {
                code: code,
                _deleted: false
            };
            this.collection.singleOrDefault(query)
                .then(item => {
                    resolve(item);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

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

        var query = {};

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");
            var filterCode = {
                'code': {
                    '$regex': regex
                }
            };
            var filterName = {
                'name': {
                    '$regex': regex
                }
            };

            keywordFilter = {
                '$or': [filterCode, filterName]
            };
        }
        query = { '$and': [basicFilter, paging.filter, keywordFilter] };
        return query;
    }

    _validate(data) {
        var errors = {};
        return new Promise((resolve, reject) => {
            // 1. begin: Declare promises.
            var getItem = this.collection.singleOrDefault({
                "$and": [{
                    _id: {
                        '$ne': new ObjectId(data._id)
                    }
                }, {
                    code: data.code
                }]
            });
            // 1. end: Declare promises.

            // 2. begin: Validation.
            Promise.all([getItem])
                .then(results => {
                    var _item = results[0];

                    if (!data.code || data.code == '')
                        errors["code"] = "code is required";
                    else if (_item)
                        errors["code"] = "code already exists";

                    if (!data.name || data.name == '')
                        errors["name"] = "name is required";

                    if (!data.uom || data.uom == '')
                        errors["uom"] = "uom is required";

                    this.componentHelper.validate(data.components)
                        .then(result => {
                            data.components = result.components;

                            // 2c. begin: check if data has any error, reject if it has.
                            for (var prop in errors) {
                                var ValidationError = require('module-toolkit').ValidationError;
                                reject(new ValidationError('data does not pass validation', errors));
                            }
                            var valid = data;
                            if (!valid.stamp) {
                                switch (data._type) {
                                    case 'material':
                                        valid = new Material(data);
                                        break;
                                    case 'finished-goods':
                                        valid = new FinishedGoods(data);
                                        break;
                                    default:
                                        valid = new Item(data);
                                }
                            }
                            valid.stamp(this.user.username, 'manager');
                            resolve(valid);
                        })
                        .catch(e => {
                            errors["components"] = e;

                            // 2c. begin: check if data has any error, reject if it has.
                            for (var prop in errors) {
                                var ValidationError = require('module-toolkit').ValidationError;
                                reject(new ValidationError('data does not pass validation', errors));
                            }
                        });
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    //Code update on 20-6-2017
    //for update item on sales-doc
    updateItemOnSalesDoc(data) {
        var query = {};

        var filter = {
            'isVoid': false
        };

        var filterSalesItems = {
            'items.item.code': data.code
        };

        var filterSalesItemsReturnItems = {
            'items.returnItems.item.code': data.code
        }

        var itemFilter = {
            '$or': [filterSalesItems, filterSalesItemsReturnItems]
        }

        query = { '$and': [filter, itemFilter] };

        return new Promise((resolve, reject) => {
            this.salesCollection.where(query).execute()
                .then(salesDocs => {

                    if (salesDocs.data.length > 0) {
                        for (var salesDoc of salesDocs.data) {

                            if (salesDoc.items) {
                                for (var items of salesDoc.items) {
                                    if (items.item.code === data.code) {
                                        items.item = data;
                                    }
                                }
                            }

                            if (salesDoc.items.returnItems) {
                                for (var items of salesDoc.items.returnItems) {
                                    if (items.item.code === data.code) {
                                        items.item = data;
                                    }
                                }
                            }

                            salesDoc._updatedDate = data._updatedDate;
                            this.salesCollection.update(salesDoc)
                                .then(id => {
                                    resolve();
                                })
                                .catch(e => {
                                    reject(e);
                                })
                        }
                    } else {
                        resolve();
                    }

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

    //Code update on 20-6-2017
    //for update item inside sales-return-doc
    updateItemOnSalesReturnDoc(data) {
        var query = {};

        var filter = {
            'isVoid': false
        };

        var filterSales = {
            'salesDoc.items.item.code': data.code
        };

        var filterSalesReturnItem = {
            'salesDoc.items.returnItems.item.code': data.code
        };

        var filterSalesReturn = {
            'salesDocReturn.items.item.code': data.code
        };

        var filterSalesDocReturnReturnItems = {
            'salesDocReturn.items.returnItems.item.code': data.code
        }

        var filterReturnItems = {
            'returnItems.item.code': data.code
        }

        var itemFilter = {
            '$or': [filterSales, filterSalesReturnItem, filterSalesReturn, filterSalesDocReturnReturnItems, filterReturnItems]
        }

        query = { '$and': [filter, itemFilter] };

        return new Promise((resolve, reject) => [
            this.salesReturnCollection.where(query).execute()
                .then(salesReturnDocs => {

                    if (salesReturnDocs.data.length > 0) {
                        for (var salesReturnDoc of salesReturnDocs.data) {

                            if (salesReturnDoc.salesDoc.items) {
                                for (var items of salesReturnDoc.salesDoc.items) {
                                    if (items.item.code === data.code) {
                                        items.item = data;
                                    }
                                }
                            }

                            if (salesReturnDoc.salesDoc.items.returnItems) {
                                for (var items of salesReturnDoc.salesDoc.items.returnItems) {
                                    if (items.item.code === data.code) {
                                        items.item = data;
                                    }
                                }
                            }

                            if (salesReturnDoc.salesDocReturn.items) {
                                for (var items of salesReturnDoc.salesDocReturn.items) {
                                    if (items.item.code === data.code) {
                                        items.item = data;
                                    }
                                }
                            }

                            if (salesReturnDoc.salesDocReturn.items.returnItems) {
                                for (var items of salesReturnDoc.salesDocReturn.items.returnItems) {
                                    if (items.item.code === data.code) {
                                        items.item = data;
                                    }
                                }
                            }

                            if (salesReturnDoc.returnItems) {
                                for (var items of salesReturnDoc.returnItems) {
                                    if (items.item.code === data.code) {
                                        items.item = data;
                                    }
                                }
                            }

                            salesReturnDoc._updatedDate = data._updatedDate;
                            this.salesReturnCollection.update(salesReturnDoc)
                                .then(id => {
                                    resolve();
                                })
                                .catch(e => {
                                    reject(e);
                                })
                        }
                    } else {
                        resolve();
                    }
                })
                .catch(e => {
                    reject(e);
                })
        ]);
    }
};<commit_msg>update item-manajer<commit_after>'use strict';

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

// internal deps
require('mongodb-toolkit');
var BaseManager = require('module-toolkit').BaseManager;
var ComponentHelper = require('./component-helper');

var BateeqModels = require('bateeq-models');
var Item = BateeqModels.master.Item;
var FinishedGoods = BateeqModels.master.FinishedGoods;
var Material = BateeqModels.master.Material;
var Sales = BateeqModels.sales.Sales;
var map = BateeqModels.map;

module.exports = class ItemManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.master.Item);
        this.salesCollection = this.db.use(map.sales.SalesDoc);
        this.salesReturnCollection = this.db.use(map.sales.SalesReturnDoc);
        this.componentHelper = new ComponentHelper(this);
    }

    upsertComponents(data) {
        return new Promise((resolve, reject) => {
            var tag = `#${data.code}`;
            var task = [];
            for (var component of data.components) {

                var item = component.item;
                var tags = (item.tags || '').split(",").filter(el => el && el.trim().length > 0);
                var tagIndex = tags.findIndex(t => {
                    return t == tag;
                });

                if (tagIndex < 0)
                    tags.push(tag);

                item.tags = tags.join(",");

                if (item._id)
                    task.push(this.update(item));
                else
                    task.push(this.create(item));
            }

            Promise.all(task)
                .then(results => {
                    var getItems = [];

                    for (var itemId of results)
                        getItems.push(this.getSingleById(itemId));

                    Promise.all(getItems)
                        .then(items => {
                            var index = 0;
                            for (var item of items) {
                                var component = data.components[index++];
                                component.itemId = item._id;
                                component.item = item;
                            }
                            this.collection.update(data).then(id => {
                                resolve(id);
                            });
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                });

        });
    }

    create(data) {
        return new Promise((resolve, reject) => {
            this._validate(data)
                .then(validData => {
                    this.collection.insert(validData)
                        .then(id => {
                            validData._id = id;
                            this.upsertComponents(validData)
                                .then(id => {
                                    resolve(id);
                                })
                                .catch(e => {
                                    reject(e);
                                });
                        })
                        .catch(e => {
                            reject(e);
                        });
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    //update 15-6-2017
    update(data) {
        return new Promise((resolve, reject) => {
            this._validate(data)
                .then(validData => {
                    this.collection.update(validData)
                        .then(id => {
                            this.updateItemOnSalesDoc(validData)
                                .then(salesDocUpdate => {
                                    this.updateItemOnSalesReturnDoc(validData)
                                        .then(salesReturnUpDate => {
                                            resolve(id);
                                        })
                                        .catch(e => {
                                            reject(e);
                                        })
                                })
                                .catch(e => {
                                    reject(e);
                                })
                        })
                        .catch(e => {
                            reject(e);
                        })
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    getByCode(code) {
        return new Promise((resolve, reject) => {
            if (code === '')
                resolve(null);
            var query = {
                code: code,
                _deleted: false
            };
            this.collection.singleOrDefault(query)
                .then(item => {
                    resolve(item);
                })
                .catch(e => {
                    reject(e);
                });
        });
    }

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

        var query = {};

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");
            var filterCode = {
                'code': {
                    '$regex': regex
                }
            };
            var filterName = {
                'name': {
                    '$regex': regex
                }
            };

            keywordFilter = {
                '$or': [filterCode, filterName]
            };
        }
        query = { '$and': [basicFilter, paging.filter, keywordFilter] };
        return query;
    }

    _validate(data) {
        var errors = {};
        return new Promise((resolve, reject) => {
            // 1. begin: Declare promises.
            var getItem = this.collection.singleOrDefault({
                "$and": [{
                    _id: {
                        '$ne': new ObjectId(data._id)
                    }
                }, {
                    code: data.code
                }]
            });
            // 1. end: Declare promises.

            // 2. begin: Validation.
            Promise.all([getItem])
                .then(results => {
                    var _item = results[0];

                    if (!data.code || data.code == '')
                        errors["code"] = "code is required";
                    else if (_item)
                        errors["code"] = "code already exists";

                    if (!data.name || data.name == '')
                        errors["name"] = "name is required";

                    if (!data.uom || data.uom == '')
                        errors["uom"] = "uom is required";

                    this.componentHelper.validate(data.components)
                        .then(result => {
                            data.components = result.components;

                            // 2c. begin: check if data has any error, reject if it has.
                            for (var prop in errors) {
                                var ValidationError = require('module-toolkit').ValidationError;
                                reject(new ValidationError('data does not pass validation', errors));
                            }
                            var valid = data;
                            if (!valid.stamp) {
                                switch (data._type) {
                                    case 'material':
                                        valid = new Material(data);
                                        break;
                                    case 'finished-goods':
                                        valid = new FinishedGoods(data);
                                        break;
                                    default:
                                        valid = new Item(data);
                                }
                            }
                            valid.stamp(this.user.username, 'manager');
                            resolve(valid);
                        })
                        .catch(e => {
                            errors["components"] = e;

                            // 2c. begin: check if data has any error, reject if it has.
                            for (var prop in errors) {
                                var ValidationError = require('module-toolkit').ValidationError;
                                reject(new ValidationError('data does not pass validation', errors));
                            }
                        });
                })
                .catch(e => {
                    reject(e);
                })
        });
    }

    //Code update on 20-6-2017
    //for update item on sales-doc
    updateItemOnSalesDoc(data) {
        var query = {};

        var filter = {
            'isVoid': false
        };

        var filterSalesItems = {
            'items.item.code': data.code
        };

        var filterSalesItemsReturnItems = {
            'items.returnItems.item.code': data.code
        }

        var itemFilter = {
            '$or': [filterSalesItems, filterSalesItemsReturnItems]
        }

        query = { '$and': [filter, itemFilter] };

        return new Promise((resolve, reject) => {
            this.salesCollection.where(query).execute()
                .then(salesDocs => {

                    if (salesDocs.data.length > 0) {
                        for (var salesDoc of salesDocs.data) {

                            if (salesDoc.items) {
                                for (var items of salesDoc.items) {

                                    if (items.item.code === data.code) {
                                        items.item = data;
                                    }

                                    for (var returnItem of items.returnItems) {
                                        if (returnItem.item.code === data.code) {
                                            returnItem.item = data;
                                        }
                                    }
                                }
                            }

                            salesDoc._updatedDate = data._updatedDate;
                            this.salesCollection.update(salesDoc)
                                .then(id => {
                                    resolve();
                                })
                                .catch(e => {
                                    reject(e);
                                })
                        }
                    } else {
                        resolve();
                    }

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

    //Code update on 20-6-2017
    //for update item inside sales-return-doc
    updateItemOnSalesReturnDoc(data) {
        var query = {};

        var filter = {
            'isVoid': false
        };

        var filterSales = {
            'salesDoc.items.item.code': data.code
        };

        var filterSalesReturnItem = {
            'salesDoc.items.returnItems.item.code': data.code
        };

        var filterSalesReturn = {
            'salesDocReturn.items.item.code': data.code
        };

        var filterSalesDocReturnReturnItems = {
            'salesDocReturn.items.returnItems.item.code': data.code
        }

        var filterReturnItems = {
            'returnItems.item.code': data.code
        }

        var itemFilter = {
            '$or': [filterSales, filterSalesReturnItem, filterSalesReturn, filterSalesDocReturnReturnItems, filterReturnItems]
        }

        query = { '$and': [filter, itemFilter] };

        return new Promise((resolve, reject) => [
            this.salesReturnCollection.where(query).execute()
                .then(salesReturnDocs => {

                    if (salesReturnDocs.data.length > 0) {
                        for (var salesReturnDoc of salesReturnDocs.data) {

                            if (salesReturnDoc.salesDoc.items) {
                                for (var items of salesReturnDoc.salesDoc.items) {

                                    if (items.item.code === data.code) {
                                        items.item = data;
                                    }

                                    for (var returnItem of items.returnItems) {
                                        if (returnItem.item.code === data.code) {
                                            returnItem.item = data;
                                        }
                                    }
                                }
                            }

                            if (salesReturnDoc.salesDocReturn.items) {
                                for (var items of salesReturnDoc.salesDocReturn.items) {

                                    if (items.item.code === data.code) {
                                        items.item = data;
                                    }

                                    for (var returnItem of items.returnItems) {
                                        if (returnItem.item.code === data.code) {
                                            returnItem.item = data;
                                        }
                                    }
                                }
                            }

                            if (salesReturnDoc.returnItems) {
                                for (var items of salesReturnDoc.returnItems) {
                                    if (items.item.code === data.code) {
                                        items.item = data;
                                    }
                                }
                            }

                            salesReturnDoc._updatedDate = data._updatedDate;
                            this.salesReturnCollection.update(salesReturnDoc)
                                .then(id => {
                                    resolve();
                                })
                                .catch(e => {
                                    reject(e);
                                })
                        }
                    } else {
                        resolve();
                    }
                })
                .catch(e => {
                    reject(e);
                })
        ]);
    }
};<|endoftext|>


<commit_before>import Ember from 'ember';
import RecordKeeperMixin from 'ember-time-machine/mixins/time-machine';
import Record from 'ember-time-machine/-private/Record';
import { wrapValue, unwrapValue } from 'ember-time-machine/utils/value';
import { pathInGlobs } from 'ember-time-machine/utils/utils';

export default Ember.ObjectProxy.extend(RecordKeeperMixin, {
  unknownProperty(key) {
    return wrapValue(this, key, this._super(...arguments));
  },

  setUnknownProperty(key, value) {
    let content = this.get('content');
    let state = this.get('_rootMachineState');
    let path = this.get('_path');

    if (state && !pathInGlobs(path.concat(key).join('.'), state.get('frozenProperties'))) {
      this._addRecord(new Record({
        target: content,
        path,
        key,
        before: content.get(key),
        after: value
      }));

      return this._super(key, unwrapValue(value));
    }

    this.notifyPropertyChange(key);
    return;
  }
});
<commit_msg>Use Ember.get in Object Proxy<commit_after>import Ember from 'ember';
import RecordKeeperMixin from 'ember-time-machine/mixins/time-machine';
import Record from 'ember-time-machine/-private/Record';
import { wrapValue, unwrapValue } from 'ember-time-machine/utils/value';
import { pathInGlobs } from 'ember-time-machine/utils/utils';

const { get } = Ember;

export default Ember.ObjectProxy.extend(RecordKeeperMixin, {
  unknownProperty(key) {
    return wrapValue(this, key, this._super(...arguments));
  },

  setUnknownProperty(key, value) {
    let content = get(this, 'content');
    let state = get(this, '_rootMachineState');
    let path = get(this, '_path');

    if (state && !pathInGlobs(path.concat(key).join('.'), get(state, 'frozenProperties'))) {
      this._addRecord(new Record({
        target: content,
        path,
        key,
        before: get(content, key),
        after: value
      }));

      return this._super(key, unwrapValue(value));
    }

    this.notifyPropertyChange(key);
    return;
  }
});
<|endoftext|>


<commit_before>var assert = require('assert')
var log = require('npmlog')
var path = require('path')
var sha = require('sha')
var retry = require('retry')
var writeStreamAtomic = require('fs-write-stream-atomic')
var PassThrough = require('readable-stream').PassThrough
var normalizePkgData = require('normalize-package-data')
var npm = require('../npm.js')
var inflight = require('inflight')
var getDlFilename = require('./get-dl-filename.js')
var filenameParser = require('./npm-package-filename.js')
var readTarballJson = require('../fetch-package-metadata.js').readTarballJson
var semver = require('semver')
var pulseTillDone = require('../utils/pulse-till-done.js')

module.exports = fetchRemoteTarball

// This is called from download_ (in download.js) and fetchNamed (fetch-named.js).
// Result data fields potentially set here: name, version, tag, filename, anomaly,
// and the three underscore-prefixed ones below.
function fetchRemoteTarball (inParams, _cb) {

  assert(typeof inParams === 'object' && typeof inParams.url === 'string',
         'must have module URL')
  assert(typeof _cb === 'function', 'must have callback')

  if (!inParams.name)
    log.warn('fetchRemoteTarball', 'Package name not known in advance')
  if (!inParams.ver)
    log.warn('fetchRemoteTarball', 'Package version not known in advance')

  var u = inParams.url
  var shasum = inParams.shasum

  _cb = inflight(u, _cb)
  if (!_cb) return log.verbose('fetchRemoteTarball', u, 'already in flight; waiting')
  log.verbose('fetchRemoteTarball', u, 'not in flight; adding')
  log.verbose('fetchRemoteTarball', [u, shasum])

  function cb (er, dlData) {
    if (dlData) {
      dlData._from = u
      dlData._resolved = u
      dlData._shasum = dlData._shasum || shasum

      getPackageData(dlData.filename, function(pdErr, pkgData, wrapData) {
        _cb(pdErr, dlData, pkgData, wrapData)
      })
    }
    else _cb(er)
  }

  // Tuned to spread 3 attempts over about a minute.
  // See formula at <https://github.com/tim-kos/node-retry>.
  var operation = retry.operation({
    retries: npm.config.get('fetch-retries'),
    factor: npm.config.get('fetch-retry-factor'),
    minTimeout: npm.config.get('fetch-retry-mintimeout'),
    maxTimeout: npm.config.get('fetch-retry-maxtimeout')
  })
  operation.attempt(function (currentAttempt) {
    log.info(
      'retry',
      'fetch attempt', currentAttempt,
      'at', (new Date()).toLocaleTimeString()
    )
    fetchAndShaCheck(inParams, function (er, response, dlData) {
      // Only retry on 408, 5xx or no `response`.
      var sc = response && response.statusCode
      var statusRetry = !sc || (sc === 408 || sc >= 500)
      if (er && statusRetry && operation.retry(er)) {
        log.warn('retry', 'will retry, error on last attempt: ' + er)
        return
      }
      cb(er, dlData)
    })
  })
}

function fetchAndShaCheck (inParams, cb) {
  cb = pulseTillDone('fetchTarball', cb)
  npm.registry.fetch(inParams.url, { auth : inParams.auth },
    function afterFetch (er, response) {
      var thisFunc = 'afterFetch'
      if (er) {
        log.error(thisFunc, 'fetch failed', inParams.url)
        return cb(er, response)
      }

      // Options to get a name for the download, in order of preference:
      // 1. If both name & version are available, construct from those.
      //    If dlData.version is set non-null below, we know it's valid!
      // 2. Try to get the filename from the response headers.
      // 3. See if basename from the URL is acceptable as a package filename.
      // 4. If a semver-compliant version string is recognized in the basename
      //    of the URL, concatenate the version tail onto the package name.
      // 5. If none of these works, just ensure that the basename of the URL
      //    has the package name prefixed onto it, and that there's no file by
      //    that name already in the dl-dir.

      var dlData = {}
      var version = inParams.ver && semver.valid(inParams.ver, true)
      if (version) dlData.version = version
      if (inParams.name) dlData.name = inParams.name
      if (inParams.tag && inParams.tag !== 'latest') dlData.tag = inParams.tag

      // Option #1
      if (dlData.name && dlData.version) {
        dlData.filename = dlData.name + '-' + dlData.version + '.tar.gz'
      }
      if (!dlData.filename) {
        // Option #2
        deriveFromResponse(response, dlData)
      }
      if (!dlData.filename) {
        // Options #3-5
        deriveFromURL(inParams.url, dlData)
      }

      var filePath = path.join(npm.dlTracker.path, dlData.filename)
      var tarball = writeStreamAtomic(filePath, { mode : npm.modes.file })
      tarball.on('error', function (er) {
        cb(er)
        tarball.destroy()
      })

      tarball.on('finish', function () {
        if (!inParams.shasum) {
          // Well, we weren't given a shasum, so at least sha what we have
          // in case we want to compare it to something else later
          return sha.get(filePath, function (er, shasum) {
            log.silly('fetchAndShaCheck', 'calculated shasum', shasum)
            dlData._shasum = shasum
            cb(er, response, dlData)
          })
        }

        // validate that the url we just downloaded matches the expected shasum.
        log.silly('fetchAndShaCheck', 'expected shasum', inParams.shasum)
        sha.check(filePath, inParams.shasum, function (er) {
          if (er && er.message) {
            // add original filename for better debuggability
            er.message = er.message + '\n' + 'From:     ' + inParams.url
          }
          else { dlData._shasum = inParams.shasum }
          cb(er, response, dlData)
        })
      })

      // See note about 0.8 http streams bug in cache/add-remote-tarball.js
      response.pipe(PassThrough({highWaterMark: Infinity})).pipe(tarball)
  })
}

// deriveFromResponse: try to extract from the given response headers object
// whatever information missing from dlData that we need to create a filename
// for a package tarball.
//
// TODO: seriously consider getting rid of the 'anomaly' property, since I have
// no plans for what to do with it, and currently it's not enough information
//
function deriveFromResponse(response, dlData)
{
  var thisFunc = 'deriveFromResponse'
  var filename = getDlFilename(response)
  var parsed

  if (!filename)
    return log.verbose(thisFunc, 'No filename from response headers')

  dlData.filename = filename
  parsed = filenameParser.parse(filename)
  if (!parsed) {
    log.verbose(thisFunc,
      'Non-conforming filename from response header:', filename)
    if (!dlData.name) {
      if (!dlData.version) dlData.anomaly = 'all'
      else dlData.anomaly = 'name,filename'
    }
    else dlData.anomaly = 'version,filename'
  }
  else {
    if (!dlData.name) { dlData.name = parsed.packageName }
    else if (parsed.packageName !== dlData.name) {
      log.warn(thisFunc,
        "Module name '%s' from response does not match expected name '%s'",
        parsed.packageName, dlData.name
      )
      dlData.anomaly = 'name'
    }
    if (!dlData.version) dlData.version = parsed.versionComparable
    else if (parsed.versionComparable !== dlData.version) {
      log.warn(thisFunc,
        "Module version '%s' from response does not match expected version '%s'",
        parsed.versionComparable, dlData.version
      )
      dlData.anomaly = 'version'
    }
  }
}

// deriveFromURL: try to extract from the given URL whatever information
// missing from dlData that we need to create a filename for a tarball.
//
// NOTE: semver.valid(expr, true) is used before the call to this,
// so we are sure that dlData.version can only be a (loose) valid
// version or null. (It will be null when expr is a URL, for example.)
// If version is not null, then name is empty; else the 1st preference for
// deriving a filename would have been satisfied, and this would not be called.
//
// Also, u is a valid URL, else the callback to npm.registry.fetch() would
// have ditched with an error before the call to this.
//
// NOTE: I *think* we can depend on the URL convention {domain}/{user}/{project}/
// when the domain is github.com, but probably not otherwise; therefore such
// parsing of the URL for a missing package name is not attempted here.
//
function deriveFromURL(u, dlData)
{
  var thisFunc = 'deriveFromURL'
  var urlParsed = url.parse(u)
  var urlBasename = path.basename(urlParsed.pathname)
  var fnameParsed = filenameParser.parse(urlBasename)

  if (fnameParsed) {
    log.verbose(thisFunc, 'URL basename %s is acceptable', urlBasename)
    dlData.filename = urlBasename
    delete dlData.anomaly
    if (!dlData.name) dlData.name = fnameParsed.packageName
    else if (fnameParsed.packageName !== dlData.name) {
      log.warn(thisFunc,
        "Module name '%s' from URL does not match expected name '%s'",
        fnameParsed.packageName, dlData.name
      )
      dlData.anomaly = 'name'
    }
    if (!dlData.version) dlData.version = fnameParsed.versionComparable
    else if (fnameParsed.versionComparable !== dlData.version) {
      log.warn(thisFunc,
        "Module version '%s' from URL does not match expected version '%s'",
        fnameParsed.versionComparable, dlData.version
      )
      dlData.anomaly = 'version'
    }
  }
  else {
    var ver = filenameParser.extractVersion(urlBasename) ||
              filenameParser.extractVersion(urlParsed.pathname)
    if (ver) {
      dlData.version = ver
      if (dlData.name) {
        log.verbose(thisFunc, "filename can be built from '%s' and '%s'",
          dlData.name, urlParsed.pathname)
        dlData.filename = dlData.name + '-' + ver + '.tar.gz'
        delete dlData.anomaly
      }
      else {
        // It's possible for a spec given on the command line to be nothing but
        // a URL, among other no-name edge cases; but that seems to be the only
        // way to get here without a package name.
        log.verbose(thisFunc, "Could not derive conforming filename from '%s'",
          urlParsed.pathname)
        dlData.filename = urlBasename
        dlData.anomaly = 'name,filename'
      }
    }
    else {
      if (dlData.name) {
        if (urlBasename.indexOf(dlData.name) === -1) {
          dlData.filename = dlData.name + '-' + urlBasename
        }
        dlData.anomaly = 'version,filename'
      }
      else {
        dlData.filename = urlBasename
        dlData.anomaly = 'all'
      }
    }

    if (!filenameParser.hasTarballExtension(dlData.filename)) {
      dlData.filename += '.tar.gz'
    }
  }
}

function getPackageData (tbName, cb) {
  var filePath = path.join(npm.dlTracker.path, tbName)
  readTarballJson(filePath, 'package.json', function (pjErr, pkgData) {
    log.silly('getPackageData', 'readTarballJson(package.json) callback entry')
    if (pjErr) return cb(pjErr)
    if (pkgData === null) {
      pjErr = new Error('No package.json found in ' + tbName)
      pjErr.code = 'ENOPACKAGEJSON'
      return cb(pjErr)
    }

    try { normalizePkgData(pkgData) }
    catch (normErr) {
      log.error('getPackageData', 'While normalizing package data from', tbName)
      return cb(normErr)
    }

    if (npm.config.get('shrinkwrap') === false) return cb(null, pkgData)

    readTarballJson(filePath, 'npm-shrinkwrap.json', function (err, wrapData) {
      log.silly('getPackageData', 'readTarballJson(npm-shrinkwrap.json) callback entry')
      // No error if no shrinkwrap file found;
      // errors only from untar, jsonParse, ...
      if (err)
        log.error('getPackageData', 'getting npm-shrinkwrap.json from', tbName)
      cb(err, pkgData, wrapData)
    })
  })
}

<commit_msg>Fix #5: handling for scoped packages, fetch-remote-tarball.js<commit_after>var assert = require('assert')
var log = require('npmlog')
var path = require('path')
var sha = require('sha')
var retry = require('retry')
var writeStreamAtomic = require('fs-write-stream-atomic')
var PassThrough = require('readable-stream').PassThrough
var normalizePkgData = require('normalize-package-data')
var npm = require('../npm.js')
var inflight = require('inflight')
var getDlFilename = require('./get-dl-filename.js')
var filenameParser = require('./npm-package-filename.js')
var readTarballJson = require('../fetch-package-metadata.js').readTarballJson
var semver = require('semver')
var pulseTillDone = require('../utils/pulse-till-done.js')
var npa = require('npm-package-arg')

module.exports = fetchRemoteTarball

// This is called from download_ (in download.js) and fetchNamed (fetch-named.js).
// Result data fields potentially set here: name, version, tag, filename, anomaly,
// and the three underscore-prefixed ones below.
function fetchRemoteTarball (inParams, _cb) {

  assert(typeof inParams === 'object' && typeof inParams.url === 'string',
         'must have module URL')
  assert(typeof _cb === 'function', 'must have callback')

  if (!inParams.name)
    log.warn('fetchRemoteTarball', 'Package name not known in advance')
  if (!inParams.ver)
    log.warn('fetchRemoteTarball', 'Package version not known in advance')

  var u = inParams.url
  var shasum = inParams.shasum

  _cb = inflight(u, _cb)
  if (!_cb) return log.verbose('fetchRemoteTarball', u, 'already in flight; waiting')
  log.verbose('fetchRemoteTarball', u, 'not in flight; adding')
  log.verbose('fetchRemoteTarball', [u, shasum])

  function cb (er, dlData) {
    if (dlData) {
      dlData._from = u
      dlData._resolved = u
      dlData._shasum = dlData._shasum || shasum

      getPackageData(dlData.filename, function(pdErr, pkgData, wrapData) {
        _cb(pdErr, dlData, pkgData, wrapData)
      })
    }
    else _cb(er)
  }

  // Tuned to spread 3 attempts over about a minute.
  // See formula at <https://github.com/tim-kos/node-retry>.
  var operation = retry.operation({
    retries: npm.config.get('fetch-retries'),
    factor: npm.config.get('fetch-retry-factor'),
    minTimeout: npm.config.get('fetch-retry-mintimeout'),
    maxTimeout: npm.config.get('fetch-retry-maxtimeout')
  })
  operation.attempt(function (currentAttempt) {
    log.info(
      'retry',
      'fetch attempt', currentAttempt,
      'at', (new Date()).toLocaleTimeString()
    )
    fetchAndShaCheck(inParams, function (er, response, dlData) {
      // Only retry on 408, 5xx or no `response`.
      var sc = response && response.statusCode
      var statusRetry = !sc || (sc === 408 || sc >= 500)
      if (er && statusRetry && operation.retry(er)) {
        log.warn('retry', 'will retry, error on last attempt: ' + er)
        return
      }
      cb(er, dlData)
    })
  })
}

function fetchAndShaCheck (inParams, cb) {
  cb = pulseTillDone('fetchTarball', cb)
  npm.registry.fetch(inParams.url, { auth : inParams.auth },
    function afterFetch (er, response) {
      var thisFunc = 'afterFetch'
      if (er) {
        log.error(thisFunc, 'fetch failed', inParams.url)
        return cb(er, response)
      }

      // Options to get a name for the download, in order of preference:
      // 1. If both name & version are available, construct from those.
      //    If dlData.version is set non-null below, we know it's valid!
      // 2. Try to get the filename from the response headers.
      // 3. See if basename from the URL is acceptable as a package filename.
      // 4. If a semver-compliant version string is recognized in the basename
      //    of the URL, concatenate the version tail onto the package name.
      // 5. If none of these works, just ensure that the basename of the URL
      //    has the package name prefixed onto it, and that there's no file by
      //    that name already in the dl-dir.

      var dlData = {}
      var version = inParams.ver && semver.valid(inParams.ver, true)
      if (version) dlData.version = version
      if (inParams.tag && inParams.tag !== 'latest') dlData.tag = inParams.tag
      if (inParams.name) {
        dlData.name = inParams.name

        var npaObj = npa(inParams.name)
        if (npaObj.scope) dlData.safeName = npaObj.escapedName
        else dlData.safeName = inParams.name
      }

      // Option #1
      if (dlData.name && dlData.version) {
        dlData.filename = dlData.safeName + '-' + dlData.version + '.tar.gz'
      }
      if (!dlData.filename) {
        // Option #2
        deriveFromResponse(response, dlData)
      }
      if (!dlData.filename) {
        // Options #3-5
        deriveFromURL(inParams.url, dlData)
      }

      // Was only needed for constructing the tarball filename:
      if (dlData.safeName) delete dlData.safeName

      var filePath = path.join(npm.dlTracker.path, dlData.filename)
      var tarball = writeStreamAtomic(filePath, { mode : npm.modes.file })
      tarball.on('error', function (er) {
        cb(er)
        tarball.destroy()
      })

      tarball.on('finish', function () {
        if (!inParams.shasum) {
          // Well, we weren't given a shasum, so at least sha what we have
          // in case we want to compare it to something else later
          return sha.get(filePath, function (er, shasum) {
            log.silly('fetchAndShaCheck', 'calculated shasum', shasum)
            dlData._shasum = shasum
            cb(er, response, dlData)
          })
        }

        // validate that the url we just downloaded matches the expected shasum.
        log.silly('fetchAndShaCheck', 'expected shasum', inParams.shasum)
        sha.check(filePath, inParams.shasum, function (er) {
          if (er && er.message) {
            // add original filename for better debuggability
            er.message = er.message + '\n' + 'From:     ' + inParams.url
          }
          else { dlData._shasum = inParams.shasum }
          cb(er, response, dlData)
        })
      })

      // See note about 0.8 http streams bug in cache/add-remote-tarball.js
      response.pipe(PassThrough({highWaterMark: Infinity})).pipe(tarball)
  })
}

// deriveFromResponse: try to extract from the given response headers object
// whatever information missing from dlData that we need to create a filename
// for a package tarball.
//
// TODO: seriously consider getting rid of the 'anomaly' property, since I have
// no plans for what to do with it, and currently it's not enough information
//
function deriveFromResponse(response, dlData)
{
  var thisFunc = 'deriveFromResponse'
  var filename = getDlFilename(response)
  var parsed

  if (!filename)
    return log.verbose(thisFunc, 'No filename from response headers')

  dlData.filename = filename
  parsed = filenameParser.parse(filename)
  if (!parsed) {
    log.verbose(thisFunc,
      'Non-conforming filename from response header:', filename)
    if (!dlData.name) {
      if (!dlData.version) dlData.anomaly = 'all'
      else dlData.anomaly = 'name,filename'
    }
    else dlData.anomaly = 'version,filename'
  }
  else {
    if (!dlData.name) { dlData.name = parsed.packageName }
    else if (parsed.packageName !== dlData.name) {
      log.warn(thisFunc,
        "Module name '%s' from response does not match expected name '%s'",
        parsed.packageName, dlData.name
      )
      dlData.anomaly = 'name'
    }
    if (!dlData.version) dlData.version = parsed.versionComparable
    else if (parsed.versionComparable !== dlData.version) {
      log.warn(thisFunc,
        "Module version '%s' from response does not match expected version '%s'",
        parsed.versionComparable, dlData.version
      )
      dlData.anomaly = 'version'
    }
  }
}

// deriveFromURL: try to extract from the given URL whatever information
// missing from dlData that we need to create a filename for a tarball.
//
// NOTE: semver.valid(expr, true) is used before the call to this,
// so we are sure that dlData.version can only be a (loose) valid
// version or null. (It will be null when expr is a URL, for example.)
// If version is not null, then name is empty; else the 1st preference for
// deriving a filename would have been satisfied, and this would not be called.
//
// Also, u is a valid URL, else the callback to npm.registry.fetch() would
// have ditched with an error before the call to this.
//
// NOTE: I *think* we can depend on the URL convention {domain}/{user}/{project}/
// when the domain is github.com, but probably not otherwise; therefore such
// parsing of the URL for a missing package name is not attempted here.
//
function deriveFromURL(u, dlData)
{
  var thisFunc = 'deriveFromURL'
  var urlParsed = url.parse(u)
  var urlBasename = path.basename(urlParsed.pathname)
  var fnameParsed = filenameParser.parse(urlBasename)

  if (fnameParsed) {
    log.verbose(thisFunc, 'URL basename %s is acceptable', urlBasename)
    dlData.filename = urlBasename
    delete dlData.anomaly
    if (!dlData.name) dlData.name = fnameParsed.packageName
    else if (fnameParsed.packageName !== dlData.name) {
      log.warn(thisFunc,
        "Module name '%s' from URL does not match expected name '%s'",
        fnameParsed.packageName, dlData.name
      )
      dlData.anomaly = 'name'
    }
    if (!dlData.version) dlData.version = fnameParsed.versionComparable
    else if (fnameParsed.versionComparable !== dlData.version) {
      log.warn(thisFunc,
        "Module version '%s' from URL does not match expected version '%s'",
        fnameParsed.versionComparable, dlData.version
      )
      dlData.anomaly = 'version'
    }
  }
  else {
    var ver = filenameParser.extractVersion(urlBasename) ||
              filenameParser.extractVersion(urlParsed.pathname)
    if (ver) {
      dlData.version = ver
      if (dlData.name) {
        log.verbose(thisFunc, "filename can be built from '%s' and '%s'",
          dlData.safeName, urlParsed.pathname)
        dlData.filename = dlData.safeName + '-' + ver + '.tar.gz'
        delete dlData.anomaly
      }
      else {
        // It's possible for a spec given on the command line to be nothing but
        // a URL, among other no-name edge cases; but that seems to be the only
        // way to get here without a package name.
        log.verbose(thisFunc, "Could not derive conforming filename from '%s'",
          urlParsed.pathname)
        dlData.filename = urlBasename
        dlData.anomaly = 'name,filename'
      }
    }
    else {
      if (dlData.name) {
        if (urlBasename.indexOf(dlData.name) === -1) {
          dlData.filename = dlData.safeName + '-' + urlBasename
        }
        dlData.anomaly = 'version,filename'
      }
      else {
        dlData.filename = urlBasename
        dlData.anomaly = 'all'
      }
    }

    if (!filenameParser.hasTarballExtension(dlData.filename)) {
      dlData.filename += '.tar.gz'
    }
  }
}

function getPackageData (tbName, cb) {
  var filePath = path.join(npm.dlTracker.path, tbName)
  readTarballJson(filePath, 'package.json', function (pjErr, pkgData) {
    log.silly('getPackageData', 'readTarballJson(package.json) callback entry')
    if (pjErr) return cb(pjErr)
    if (pkgData === null) {
      pjErr = new Error('No package.json found in ' + tbName)
      pjErr.code = 'ENOPACKAGEJSON'
      return cb(pjErr)
    }

    try { normalizePkgData(pkgData) }
    catch (normErr) {
      log.error('getPackageData', 'While normalizing package data from', tbName)
      return cb(normErr)
    }

    if (npm.config.get('shrinkwrap') === false) return cb(null, pkgData)

    readTarballJson(filePath, 'npm-shrinkwrap.json', function (err, wrapData) {
      log.silly('getPackageData', 'readTarballJson(npm-shrinkwrap.json) callback entry')
      // No error if no shrinkwrap file found;
      // errors only from untar, jsonParse, ...
      if (err)
        log.error('getPackageData', 'getting npm-shrinkwrap.json from', tbName)
      cb(err, pkgData, wrapData)
    })
  })
}

<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Route.extend({

});

<commit_msg>add addon menu item<commit_after>import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

export default Ember.Route.extend(AuthenticatedRouteMixin, {

navbarService: Ember.inject.service('navbar'),

activate(){
	this.get('navbarService').navbarLabels.addObject('gittest');
},

});
<|endoftext|>


<commit_before>/*******************************************************************************
DigiBird meta information component
*******************************************************************************/
var platforms = require('../helpers/platforms');
var request = require('request-promise-native');
var winston = require('winston');

module.exports = {
    statistics: function(platformId) {
        var platform = platforms.platform(platformId);

        if (platform.endpoint_type === "json-api") {
            return this.statisticsJson(platform);
        } else if (platform.endpoint_type === "sparql") {
            var promises = [];

            for (var i=0; i<platform.statistics.length; i++)
                promises[i] = this.statisticsSparql(platform, platform.statistics[i]);

            return Promise.all(promises)
            .then(function(data) {
                var statistics = [];

                for (var i=0; i<platform.statistics.length; i++) {
                    statistics[i] =
                        {
                            type:platform.statistics[i],
                            value:data[i].results.bindings[0].result.value
                        };
                }

                return statistics;
            });
        } else {
            var value = Math.floor((Math.random() * 10) + 1);
            var statistics = [{type:"users", value:value}];

            return new Promise(function(resolve, reject) {
                setTimeout(
                    function() {
                        // We fulfill the promise !
                        resolve(statistics);
                    }, 1000);
            });
        }

        return statistics;
    },
    statisticsJson: function(platform) {
        // query the platforms endpoint for contributions from the Netherlands
        var options = {
            url: platform.endpoint_location,
            qs: { query: "cnt:netherlands" }
        };

        return request(options)
        .then(function(json) {
            var results = JSON.parse(json);
            var statistics = [{type:"Dutch contributions", value:results.numRecordings}];
            return statistics;
        }, function(error) {
            winston.log('error', "Could not obtain results api: ", error);
        });
    },
    statisticsSparql: function(platform, statistic) {
        var queries = this.sparqlStatisticsQueries();

        // query the platforms endpoint for contributions
        var options = {
            url: platform.endpoint_location,
            method: 'POST', // using post with query as body, get might be more generic?
            headers: {
                'Accept': 'application/sparql-results+json',
                'Content-Type': 'application/sparql-query'
            },
            body: queries[statistic]
        };

        return request(options)
        .then(function(response) {
            return JSON.parse(response);
        }, function (error) {
            winston.log('error', "Could not obtain SPARQL results: ", error);
        });
    },
    sparqlStatisticsQueries: function() {
        // create an object with queries that can be used for monitor purposes
        var queries =
        {
            test:
                "SELECT ?s ?p ?o " +
                "WHERE " +
                "{ ?s ?p ?o . } " +
                "LIMIT 10",
            users:
                "PREFIX oa: <http://www.w3.org/ns/oa#> " +
                "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
                "SELECT (COUNT(DISTINCT ?user) as ?result) " +
                "WHERE { " +
                    "?annotation oa:hasTarget ?work . " +
                    "?annotation oa:annotatedBy ?user . " +
                "}",
            users_birds:
                "PREFIX oa: <http://www.w3.org/ns/oa#> " +
                "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
                "SELECT (COUNT(DISTINCT ?user) as ?result) " +
                "WHERE { " +
                    "?annotation oa:hasTarget ?object . " +
                    "?object rdf:type <http://accurator.nl/bird#Target> . " +
                    "?annotation oa:annotatedBy ?user . " +
                "}",
            annotations:
                "PREFIX oa: <http://www.w3.org/ns/oa#> " +
                "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
                "SELECT (COUNT(DISTINCT ?annotation) as ?result) " +
                "WHERE { " +
                    "?annotation rdf:type oa:Annotation . " +
                "}",
            annotations_birds:
                "PREFIX oa: <http://www.w3.org/ns/oa#> " +
                "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
                "SELECT (COUNT(DISTINCT ?annotation) as ?result) " +
                "WHERE { " +
                    "?annotation oa:hasTarget ?object . " +
                    "?object rdf:type <http://accurator.nl/bird#Target> . " +
                    "?annotation rdf:type oa:Annotation . " +
                "}",
            objects:
                "PREFIX edm: <http://www.europeana.eu/schemas/edm/> " +
                "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
                "SELECT (COUNT(DISTINCT ?object) as ?result) " +
                "WHERE { ?object rdf:type edm:ProvidedCHO . }",
            objects_birds:
                "PREFIX edm: <http://www.europeana.eu/schemas/edm/> " +
                "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
                "SELECT (COUNT(DISTINCT ?object) as ?result) " +
                "WHERE { " +
                    "?object rdf:type edm:ProvidedCHO . " +
                    "?object rdf:type <http://accurator.nl/bird#Target> . " +
                "}",
            annotated_objects:
                "PREFIX edm: <http://www.europeana.eu/schemas/edm/> " +
                "PREFIX oa: <http://www.w3.org/ns/oa#> " +
                "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
                "SELECT (COUNT(DISTINCT ?object) as ?result) " +
                "WHERE { " +
                    "?annotation oa:hasTarget ?object . " +
                    "?object rdf:type edm:ProvidedCHO . " +
                    "?annotation rdf:type oa:Annotation . " +
                "}",
            annotated_objects_birds:
                "PREFIX oa: <http://www.w3.org/ns/oa#> " +
                "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
                "SELECT (COUNT(DISTINCT ?object) as ?result) " +
                "WHERE { " +
                    "?annotation oa:hasTarget ?object . " +
                    "?object rdf:type <http://accurator.nl/bird#Target> . " +
                    "?annotation rdf:type oa:Annotation . " +
                "}"
        };

        return queries;
    }
}
<commit_msg>Extended information in query object and optimized statistics retrieval code.<commit_after>/*******************************************************************************
DigiBird meta information component
*******************************************************************************/
var platforms = require('../helpers/platforms');
var request = require('request-promise-native');
var winston = require('winston');

module.exports = {
    statistics: function(platformId) {
        var platform = platforms.platform(platformId);

        if (platform.endpoint_type === "json-api") {
            return this.statisticsJson(platform);
        } else if (platform.endpoint_type === "sparql") {
            var promises = [];

            for (var i=0; i<platform.statistics.length; i++)
                promises[i] = this.statisticsSparql(platform, platform.statistics[i]);

            return Promise.all(promises)
            .then(function(statistics) {
                return statistics;
            });
        } else {
            var value = Math.floor((Math.random() * 10) + 1);
            var statistics = [{type:"users", value:value}];

            return new Promise(function(resolve, reject) {
                setTimeout(
                    function() {
                        // We fulfill the promise !
                        resolve(statistics);
                    }, 1000);
            });
        }

        return statistics;
    },
    statisticsJson: function(platform) {
        // query the platforms endpoint for contributions from the Netherlands
        var options = {
            url: platform.endpoint_location,
            qs: { query: "cnt:netherlands" }
        };

        return request(options)
        .then(function(json) {
            var results = JSON.parse(json);
            var statistics = [{type:"Dutch contributions", value:results.numRecordings}];
            return statistics;
        }, function(error) {
            winston.log('error', "Could not obtain results api: ", error);
        });
    },
    statisticsSparql: function(platform, statistic) {
        var queries = this.sparqlStatisticsQueries();

        // query the platforms endpoint for contributions
        var options = {
            url: platform.endpoint_location,
            method: 'POST', // using post with query as body, get might be more generic?
            headers: {
                'Accept': 'application/sparql-results+json',
                'Content-Type': 'application/sparql-query'
            },
            body: queries[statistic].query
        };

        return request(options)
        .then(function(response) {
            var value = JSON.parse(response).results.bindings[0].result.value;
            var name = queries[statistic].name;

            return { "type": name, "value": value };
        }, function (error) {
            winston.log('error', "Could not obtain SPARQL results: ", error);

            return { "type": "Error", "value": "No connection established" };
        });
    },
    sparqlStatisticsQueries: function() {
        // create an object with queries that can be used for monitor purposes
        var queries =
        {
            "test":
                {
                    "query":
                        "SELECT ?s ?p ?o " +
                        "WHERE " +
                            "{ ?s ?p ?o . } " +
                        "LIMIT 10",
                    "name": "test"
                },
            "users":
                {
                    "query":
                        "PREFIX oa: <http://www.w3.org/ns/oa#> " +
                        "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
                        "SELECT (COUNT(DISTINCT ?user) as ?result) " +
                        "WHERE { " +
                            "?annotation oa:hasTarget ?work . " +
                            "?annotation oa:annotatedBy ?user . " +
                        "}",
                    "name": "total contributors"
                },
            "users_birds":
                {
                    "query":
                        "PREFIX oa: <http://www.w3.org/ns/oa#> " +
                        "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
                        "SELECT (COUNT(DISTINCT ?user) as ?result) " +
                        "WHERE { " +
                            "?annotation oa:hasTarget ?object . " +
                            "?object rdf:type <http://accurator.nl/bird#Target> . " +
                            "?annotation oa:annotatedBy ?user . " +
                        "}",
                    "name":"contributors"
                },
            "annotations":
                {
                    "query":
                        "PREFIX oa: <http://www.w3.org/ns/oa#> " +
                        "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
                        "SELECT (COUNT(DISTINCT ?annotation) as ?result) " +
                        "WHERE { " +
                            "?annotation rdf:type oa:Annotation . " +
                        "}",
                    "name": "annotations"
                },
            "annotations_birds":
                {
                    "query":
                        "PREFIX oa: <http://www.w3.org/ns/oa#> " +
                        "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
                        "SELECT (COUNT(DISTINCT ?annotation) as ?result) " +
                        "WHERE { " +
                            "?annotation oa:hasTarget ?object . " +
                            "?object rdf:type <http://accurator.nl/bird#Target> . " +
                            "?annotation rdf:type oa:Annotation . " +
                        "}",
                    "name": "annotations"
                },
            "objects":
                {
                    "query":
                        "PREFIX edm: <http://www.europeana.eu/schemas/edm/> " +
                        "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
                        "SELECT (COUNT(DISTINCT ?object) as ?result) " +
                        "WHERE { ?object rdf:type edm:ProvidedCHO . }",
                    "name": "objects"
                },
            "objects_birds":
                {
                    "query":
                        "PREFIX edm: <http://www.europeana.eu/schemas/edm/> " +
                        "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
                        "SELECT (COUNT(DISTINCT ?object) as ?result) " +
                        "WHERE { " +
                            "?object rdf:type edm:ProvidedCHO . " +
                            "?object rdf:type <http://accurator.nl/bird#Target> . " +
                        "}",
                    "name": "objects"
                },
            "annotated_objects":
                {
                    "query":
                        "PREFIX edm: <http://www.europeana.eu/schemas/edm/> " +
                        "PREFIX oa: <http://www.w3.org/ns/oa#> " +
                        "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
                        "SELECT (COUNT(DISTINCT ?object) as ?result) " +
                        "WHERE { " +
                            "?annotation oa:hasTarget ?object . " +
                            "?object rdf:type edm:ProvidedCHO . " +
                            "?annotation rdf:type oa:Annotation . " +
                        "}",
                    "name": "annotated objects"
                },
            "annotated_objects_birds":
                {
                    "query":
                        "PREFIX oa: <http://www.w3.org/ns/oa#> " +
                        "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> " +
                        "SELECT (COUNT(DISTINCT ?object) as ?result) " +
                        "WHERE { " +
                            "?annotation oa:hasTarget ?object . " +
                            "?object rdf:type <http://accurator.nl/bird#Target> . " +
                            "?annotation rdf:type oa:Annotation . " +
                        "}",
                    "name": "annotated objects"
                }
        };

        return queries;
    }
}
<|endoftext|>