<commit_before>(function () {

    // core modules
    var path = require('path');

    // dep modules
    // var fs = require('fs-extra');

    // own modules
    var Docma = require('../../index');

    function getNavItems(routing) {
        function route(name, type) {
            name = name || '';
            type = type || 'content';
            if (routing === 'path') {
                if (type === 'api') return './api' + (name ? '/' + name : '');
                return './' + name;
            }
            return './?' + type + (name ? '=' + name : '');
        }
        return [
            {
                iconClass: 'ico-mouse-pointer',
                label: 'Guide',
                items: [
                    { label: 'Home', href: './' },
                    { label: 'Guide', href: route('guide') },
                    // { label: 'Building Documentation', href: './' },
                    // { label: 'Build Configuration', href: './' },
                    { separator: true },
                    { label: 'Docma Default Template', href: route('default-template') },
                    { separator: true },
                    { label: 'Creating Docma Templates', href: route('templates') },
                    { label: 'Docma Web Core', href: route('docma-web') },
                    { label: 'Docma Filters', href: route('docma-filters') },
                    { separator: true },
                    { label: 'HTML Page', href: route('page') },
                    { label: 'iFrame Page', href: route('iframe') }
                ]
            },
            {
                iconClass: 'ico-book',
                label: 'API Reference',
                items: [
                    { label: 'Docma (Builder) API', href: route('docma', 'api') },
                    { label: 'Docma (Web) API', href: route('docma-web', 'api') },
                    { label: 'Docma Web Utils', href: route('docma-web-utils', 'api') },
                    { label: 'Test (src)', href: route('src', 'api') },
                    { separator: true },
                    { label: 'Test (re)', href: route('re', 'api') },
                    { separator: true },
                    { label: 'API Not Found', href: route('foo', 'api') },
                    { separator: true },
                    { label: 'Default', href: route('', 'api') },
                    { label: '_def_', href: route('_def_', 'api') }
                ]
            },
            {
                iconClass: 'ico-md ico-download',
                label: 'Download',
                items: [
                    { label: 'Change Log', href: route('changelog') },
                    { label: 'Markdown Test', href: route('md-test') },
                    { separator: true },
                    { label: 'index.html', href: 'index.html' }, // or ./index.html
                    { separator: true },
                    { label: 'Content Not Found', href: route('bar') }
                ]
            },
            {
                iconClass: 'ico-md ico-github',
                label: 'GitHub',
                href: 'https://github.com/onury/docma',
                target: '_blank'
            }
        ];
    }

    describe('build', function () {
        var config = {
            debug: 16,
            jsdoc: {
                encoding: 'utf8',
                recurse: false,
                pedantic: false,
                access: ['public', 'protected'], // null, // ['private'],
                package: null,
                module: true,
                undocumented: false,
                undescribed: false,
                hierarchy: true,
                sort: true, // "grouped",
                relativePath: path.join(__dirname, '/code'),
                filter: null
            },
            // markdown options
            markdown: {
                gfm: true,
                tables: true,
                breaks: false,
                pedantic: false,
                sanitize: false,
                smartLists: true,
                smartypants: false,
                tasks: true,
                emoji: true
            },
            app: {
                title: 'Docma Documentation',
                meta: null,
                base: '/javascript/docma/test/output', // overwritten in specs
                entrance: 'content:guide',
                routing: 'path', // overwritten in specs
                server: 'apache' // overwritten in specs
            },
            template: {
                path: 'default',
                options: {
                    title: 'Docma',
                    sidebar: true,
                    collapsed: false,
                    badges: true,
                    search: true,
                    navbar: true,
                    navItems: []
                }
            },
            src: [
                './test/input/md-test.md',
                // './test/input/**/*.js',
                './test/input/code.js',
                {
                    'docma': './lib/docma.js',
                    'docma-web': [
                        './lib/web/core.js',
                        './lib/web/core.*.js',
                        '!./lib/web/core.utils.js'
                    ],
                    'docma-web-utils': './lib/web/core.utils.js'
                },
                {
                    'src': [
                        './test/input/private/core/*.js',
                        './test/input/src/lib/*.js'
                    ],
                    'priv': './test/input/private/*.js',
                    're': './test/input/private/re.js'
                },
                './doc/**/*.md',
                { 'guide': './README.md' }, // renamed markdown
                './CHANGELOG.md',
                {
                    'page': './test/input/html-test.html',
                    'iframe': './test/input/iframe-test.html'
                }
            ],
            dest: './test/output' // overwritten in specs
        };

        // beforeAll(function () {});

        it('should build with query-routing', function (done) {
            config.app.routing = 'query';
            config.template.options.navItems = getNavItems(config.app.routing);
            config.dest = 'test/output/query-routing';
            config.app.base = '/'; // '/javascript/docma/' + config.dest;
            Docma.create()
                .build(config)
                .then(function (success) {
                    expect(success).toEqual(true);
                })
                .catch(function (err) {
                    expect(Boolean(err)).toEqual(false);
                    console.log(err.stack || err);
                })
                .finally(done);
        });

        it('should build with path-routing (for GitHub)', function (done) {
            config.app.routing = 'path';
            config.app.server = 'github';
            config.template.options.navItems = getNavItems(config.app.routing);
            config.dest = 'test/output/path-routing';
            config.app.base = '/javascript/docma/' + config.dest;
            Docma.create()
                .build(config)
                .then(function (success) {
                    expect(success).toEqual(true);
                })
                .catch(function (err) {
                    expect(Boolean(err)).toEqual(false);
                    console.log(err.stack || err);
                })
                .finally(done);
        });

        fit('should build docma documentation', function (done) {
            Docma.create()
                .build('./doc/docma.config.json')
                .then(function (success) {
                    expect(success).toEqual(true);
                })
                .catch(function (err) {
                    expect(Boolean(err)).toEqual(false);
                    console.log(err.stack || err);
                })
                .finally(done);
        });

    });

})();
<commit_msg>update specs<commit_after>(function () {

    // core modules
    var path = require('path');

    // dep modules
    // var fs = require('fs-extra');

    // own modules
    var Docma = require('../../index');

    function getNavItems(routing) {
        function route(name, type) {
            name = name || '';
            type = type || 'content';
            if (routing === 'path') {
                if (type === 'api') return './api' + (name ? '/' + name : '');
                return './' + name;
            }
            return './?' + type + (name ? '=' + name : '');
        }
        return [
            {
                iconClass: 'ico-mouse-pointer',
                label: 'Guide',
                items: [
                    { label: 'Home', href: './' },
                    { label: 'Guide', href: route('guide') },
                    // { label: 'Building Documentation', href: './' },
                    // { label: 'Build Configuration', href: './' },
                    { separator: true },
                    { label: 'Docma Default Template', href: route('default-template') },
                    { separator: true },
                    { label: 'Creating Docma Templates', href: route('templates') },
                    { label: 'Docma Web Core', href: route('docma-web') },
                    { label: 'Docma Filters', href: route('docma-filters') },
                    { separator: true },
                    { label: 'HTML Page', href: route('page') },
                    { label: 'iFrame Page', href: route('iframe') }
                ]
            },
            {
                iconClass: 'ico-book',
                label: 'API Reference',
                items: [
                    { label: 'Docma (Builder) API', href: route('docma', 'api') },
                    { label: 'Docma (Web) API', href: route('docma-web', 'api') },
                    { label: 'Docma Web Utils', href: route('docma-web-utils', 'api') },
                    { label: 'Test (src)', href: route('src', 'api') },
                    { separator: true },
                    { label: 'Test (re)', href: route('re', 'api') },
                    { separator: true },
                    { label: 'API Not Found', href: route('foo', 'api') },
                    { separator: true },
                    { label: 'Default', href: route('', 'api') },
                    { label: '_def_', href: route('_def_', 'api') }
                ]
            },
            {
                iconClass: 'ico-md ico-download',
                label: 'Download',
                items: [
                    { label: 'Change Log', href: route('changelog') },
                    { label: 'Markdown Test', href: route('md-test') },
                    { separator: true },
                    { label: 'index.html', href: 'index.html' }, // or ./index.html
                    { separator: true },
                    { label: 'Content Not Found', href: route('bar') }
                ]
            },
            {
                iconClass: 'ico-md ico-github',
                label: 'GitHub',
                href: 'https://github.com/onury/docma',
                target: '_blank'
            }
        ];
    }

    describe('build', function () {
        var config = {
            debug: 16,
            jsdoc: {
                encoding: 'utf8',
                recurse: false,
                pedantic: false,
                access: ['public', 'protected'], // null, // ['private'],
                package: null,
                module: true,
                undocumented: false,
                undescribed: false,
                hierarchy: true,
                sort: true, // "grouped",
                relativePath: path.join(__dirname, '/code'),
                filter: null
            },
            // markdown options
            markdown: {
                gfm: true,
                tables: true,
                breaks: false,
                pedantic: false,
                sanitize: false,
                smartLists: true,
                smartypants: false,
                tasks: true,
                emoji: true
            },
            app: {
                title: 'Docma Documentation',
                meta: null,
                base: '/javascript/docma/test/output', // overwritten in specs
                entrance: 'content:guide',
                routing: 'path', // overwritten in specs
                server: 'apache' // overwritten in specs
            },
            template: {
                path: 'default',
                options: {
                    title: 'Docma',
                    sidebar: true,
                    collapsed: false,
                    badges: true,
                    search: true,
                    navbar: true,
                    navItems: []
                }
            },
            src: [
                './test/input/md-test.md',
                // './test/input/**/*.js',
                './test/input/code.js',
                {
                    'docma': './lib/docma.js',
                    'docma-web': [
                        './lib/web/core.js',
                        './lib/web/core.*.js',
                        '!./lib/web/core.utils.js'
                    ],
                    'docma-web-utils': './lib/web/core.utils.js'
                },
                {
                    'src': [
                        './test/input/private/core/*.js',
                        './test/input/src/lib/*.js'
                    ],
                    'priv': './test/input/private/*.js',
                    're': './test/input/private/re.js'
                },
                './doc/**/*.md',
                { 'guide': './README.md' }, // renamed markdown
                './CHANGELOG.md',
                {
                    'page': './test/input/html-test.html',
                    'iframe': './test/input/iframe-test.html'
                }
            ],
            dest: './test/output' // overwritten in specs
        };

        // beforeAll(function () {});

        it('should build with query-routing', function (done) {
            config.app.routing = 'query';
            config.template.options.navItems = getNavItems(config.app.routing);
            config.dest = 'test/output/query-routing';
            config.app.base = '/'; // '/javascript/docma/' + config.dest;
            Docma.create()
                .build(config)
                .then(function (success) {
                    expect(success).toEqual(true);
                })
                .catch(function (err) {
                    expect(Boolean(err)).toEqual(false);
                    console.log(err.stack || err);
                })
                .finally(done);
        });

        it('should build with path-routing (for GitHub)', function (done) {
            config.app.routing = 'path';
            config.app.server = 'github';
            config.template.options.navItems = getNavItems(config.app.routing);
            config.dest = 'test/output/path-routing';
            config.app.base = '/javascript/docma/' + config.dest;
            Docma.create()
                .build(config)
                .then(function (success) {
                    expect(success).toEqual(true);
                })
                .catch(function (err) {
                    expect(Boolean(err)).toEqual(false);
                    console.log(err.stack || err);
                })
                .finally(done);
        });

        xit('should build docma documentation', function (done) {
            Docma.create()
                .build('./docma.config.json')
                .then(function (success) {
                    expect(success).toEqual(true);
                })
                .catch(function (err) {
                    expect(Boolean(err)).toEqual(false);
                    console.log(err.stack || err);
                })
                .finally(done);
        });

    });

})();
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var async = require('async');
var mongoose = require('mongoose');
var Update = mongoose.model('Update');

var Buffer = require('../../modules/buffer-api/src/buffer-api');
var buffer = new Buffer(process.env.BUFFER_ACCESS_TOKEN);

var DEBUG_MODE = false; // true means no real Buffer posting

var isVideo = function (url) {
	var fileExtension = url.substring(url.lastIndexOf('.')+1, url.length).toLowerCase();
	if (fileExtension === 'mp4' || fileExtension === 'mov')
		return true;
	else
		return false
}

module.exports = {

	makeUpdateFromArticle: function (profile, article) {

		var LINK_DUMMY = '123456789012345678901234'

		var appendTextIfThereIsSpace = function (oldText, appendText, separator, appendFirst) {
			// Link: 23 char, image 24
			if (profile.service !== 'twitter' || (oldText.length + appendText.length <= 116)) {
				if (appendFirst)
					oldText = appendText + separator + oldText;
				else
					oldText = oldText + separator + appendText;
			}
			return oldText;
		};

		var update = {};
		update.articleId = article._id;
		update.url = article.url;
		update.category = article.category;
		update.title = article.titles[Math.floor(Math.random() * article.titles.length)];
		update.originalTitle = article.titles[0];
		// Only images in 3/4
		if (Math.random() <= 0.75) {
			update.image = article.images[Math.floor(Math.random() * article.images.length)];
		}
		update.tags = article.tags;
		// Make text
		update.text = update.title;
		// TEMP: remove Media options for Buffer bug
		//if (profile.service === 'twitter') {
			update.text = update.title + '\n' + LINK_DUMMY;
		//}
		// Tags
		if (update.tags.length > 0) {
			update.text = update.text + '\n';
		}
		for (var t in update.tags) {
			if (update.tags.hasOwnProperty(t) && typeof(update.tags[t]) === 'string') {
				update.text = appendTextIfThereIsSpace(update.text, '#'+update.tags[t], ' ', false);
			}
		}
		update.text = update.text.replace(LINK_DUMMY, update.url);
		update.text = update.text.replace('\n #', '\n#');
		return update;
	},

	scheduleUpdates: function (profile, updates, callback) {
		console.log('Schedule updates:', profile.service, _.pluck(updates, 'text'));

		async.each(updates, function (update, cbEach) {
			update.service = profile.service;

			var bufferOptions = {
				profile_ids: [profile.bufferId],
				text: update.text,
				media: {},
				now: false,
				attachment: true,
				// shorten: false,
				// top: false,
				// scheduled_at: null,
				// retweet: false,
			};
			bufferOptions.media.photo = update.image;
			bufferOptions.media.thumbnail = update.image; // only for Buffer dashboard

			// TEMP: remove Media options for Buffer bug
			// bufferOptions.media.link = update.url;
			// bufferOptions.media.picture = update.image;
			// bufferOptions.media.title = update.originalTitle;
			// //bufferOptions.media.description = ;

			if (!DEBUG_MODE) {
				// Not debug mode
				buffer.createUpdate(
					bufferOptions,
					function (errBuffer, results) {
						if (!errBuffer) {
							Update.create(update, cbEach);
						}
						else {
							console.log('Buffer error:', errBuffer, results);
							cbEach();
						}
					}
				);
			}
			else {
				// Debug mode: just add to database
				Update.create(update, cbEach);
			}
		},
		callback)
	},

	getPendingUpdates: function (profile, callback) {
		buffer.getPendingUpdates(
			profile.bufferId,
			function (errBuffer, results) {
				console.log('getPendingUpdates', errBuffer, results);
				callback(errBuffer, results);
			}
		);
	},

}<commit_msg>Shuffle hashtags<commit_after>'use strict';

var _ = require('lodash');
var async = require('async');
var mongoose = require('mongoose');
var Update = mongoose.model('Update');

var Buffer = require('../../modules/buffer-api/src/buffer-api');
var buffer = new Buffer(process.env.BUFFER_ACCESS_TOKEN);

var DEBUG_MODE = false; // true means no real Buffer posting

var isVideo = function (url) {
	var fileExtension = url.substring(url.lastIndexOf('.')+1, url.length).toLowerCase();
	if (fileExtension === 'mp4' || fileExtension === 'mov')
		return true;
	else
		return false
}

module.exports = {

	makeUpdateFromArticle: function (profile, article) {

		var LINK_DUMMY = '123456789012345678901234'

		var appendTextIfThereIsSpace = function (oldText, appendText, separator, appendFirst) {
			// Link: 23 char, image 24
			if (profile.service !== 'twitter' || (oldText.length + appendText.length <= 116)) {
				if (appendFirst)
					oldText = appendText + separator + oldText;
				else
					oldText = oldText + separator + appendText;
			}
			return oldText;
		};

		var update = {};
		update.articleId = article._id;
		update.url = article.url;
		update.category = article.category;
		update.title = article.titles[Math.floor(Math.random() * article.titles.length)];
		update.originalTitle = article.titles[0];
		// Only images in 3/4
		if (Math.random() <= 0.75) {
			update.image = article.images[Math.floor(Math.random() * article.images.length)];
		}
		// Make text
		update.text = update.title;
		// TEMP: remove Media options for Buffer bug
		//if (profile.service === 'twitter') {
			update.text = update.title + '\n' + LINK_DUMMY;
		//}
		// Tags
		update.tags = _.shuffle(article.tags);
		if (update.tags.length > 0) {
			update.text = update.text + '\n';
		}
		for (var t in update.tags) {
			if (update.tags.hasOwnProperty(t) && typeof(update.tags[t]) === 'string') {
				update.text = appendTextIfThereIsSpace(update.text, '#'+update.tags[t], ' ', false);
			}
		}
		update.text = update.text.replace(LINK_DUMMY, update.url);
		update.text = update.text.replace('\n #', '\n#');
		return update;
	},

	scheduleUpdates: function (profile, updates, callback) {
		console.log('Schedule updates:', profile.service, _.pluck(updates, 'text'));

		async.each(updates, function (update, cbEach) {
			update.service = profile.service;

			var bufferOptions = {
				profile_ids: [profile.bufferId],
				text: update.text,
				media: {},
				now: false,
				attachment: true,
				// shorten: false,
				// top: false,
				// scheduled_at: null,
				// retweet: false,
			};
			bufferOptions.media.photo = update.image;
			bufferOptions.media.thumbnail = update.image; // only for Buffer dashboard

			// TEMP: remove Media options for Buffer bug
			// bufferOptions.media.link = update.url;
			// bufferOptions.media.picture = update.image;
			// bufferOptions.media.title = update.originalTitle;
			// //bufferOptions.media.description = ;

			if (!DEBUG_MODE) {
				// Not debug mode
				buffer.createUpdate(
					bufferOptions,
					function (errBuffer, results) {
						if (!errBuffer) {
							Update.create(update, cbEach);
						}
						else {
							console.log('Buffer error:', errBuffer, results);
							cbEach();
						}
					}
				);
			}
			else {
				// Debug mode: just add to database
				Update.create(update, cbEach);
			}
		},
		callback)
	},

	getPendingUpdates: function (profile, callback) {
		buffer.getPendingUpdates(
			profile.bufferId,
			function (errBuffer, results) {
				console.log('getPendingUpdates', errBuffer, results);
				callback(errBuffer, results);
			}
		);
	},

}<|endoftext|>


<commit_before>import h from 'virtual-dom/h'
import diff from 'virtual-dom/diff'
import patch from 'virtual-dom/patch'
import createElement from 'virtual-dom/create-element'

class Thunk {
  constructor(renderFn, state, shouldUpdate) {
    this.type = 'Thunk';
    this.renderFn = renderFn;
    this.state = state;
    this.shouldUpdate = shouldUpdate;
  }

  render(previous) {
    var previousState = previous ? previous.state : null;
    if (this.shouldUpdate(previousState)) {
      return this.renderFn(this.state);
    }
    return previous.vnode;
  }
}

export class Component {
  constructor(state) {
    this.state = state;
    this.name = this.constructor.name;
    this.thunk = this.newThunk();
  }

  newThunk() {
    return new Thunk((state) => {
      let Hook = function(){}
      Hook.prototype.hook = this.afterRender.bind(this);
      let vnode = h(this.name, {
        'after-render': new Hook(),
      }, [this.render(state)]);
      return vnode;
    }, this.state, this.shouldUpdate);
  }

  render(state) {
    return h();
  }

  bind(root) {
    this.node = createElement(this.thunk);
    root.appendChild(this.node);
  }

  set(newState) {
    this.state = newState;
    let newThunk = this.newThunk();
    let patches = diff(this.thunk, newThunk);
    this.node = patch(this.node, patches);
    this.thunk = newThunk;
  }

  afterRender(node, propertyName, previousState) {
  }

  shouldUpdate(previousState) {
    if (!previousState || !this.state) {
      return true;
    }
    let previousType = typeof previousState;
    let currentType = typeof this.state;
    if (previousType != currentType) {
      return true;
    }
    switch (currentType) {
    case 'object': // shallow check
      let previousKeys = Object.keys(previousState);
      let currentKeys = Object.keys(this.state);
      if (previousKeys.length != currentKeys.length) {
        return true;
      }
      let len = currentKeys.length;
      for (let i = 0; i < len; i++) {
        let key = currentKeys[i];
        if (previousState[key] !== this.state[key]) {
          return true;
        }
      }
      return false;
    default:
      return !(previousState === this.state);
    }
  }
}

export function e(selector, properties, children) {
  switch (typeof selector) {
  case 'string':
    return h(selector, properties, children);
  default:
    return new selector(properties).thunk;
  }
}

export var none = h('div', { style: { display: 'none' } });

export function div(...subs) {
  return h('div', {}, [...subs]);
}
<commit_msg>clean-ups<commit_after>import h from 'virtual-dom/h'
import diff from 'virtual-dom/diff'
import patch from 'virtual-dom/patch'
import createElement from 'virtual-dom/create-element'

let debug = true;

class Thunk {
  constructor(renderFn, state, shouldUpdate) {
    this.type = 'Thunk';
    this.renderFn = renderFn;
    this.state = state;
    this.shouldUpdate = shouldUpdate;
  }

  render(previous) {
    var previousState = previous ? previous.state : null;
    if (this.shouldUpdate(this.state, previousState)) {
      return this.renderFn(this.state);
    }
    return previous.vnode;
  }
}

export class Component {
  constructor(state) {
    this.thunk = this.newThunk(state);
  }

  newThunk(state) {
    return new Thunk((state) => {
      let Hook = function(){}
      Hook.prototype.hook = (node) => {
        this.node = node;
        this.nodeChanged(node);
      };
      let vnode = h(this.constructor.name, {
        'node-changed': new Hook(),
      }, [this.render(state)]);
      return vnode;
    }, state, this.shouldUpdate);
  }

  render(state) {
    return h();
  }

  bind(parent) {
    this.node = createElement(this.thunk);
    parent.appendChild(this.node);
  }

  set(newState) {
    let newThunk = this.newThunk(newState);
    let patches = diff(this.thunk, newThunk);
    this.node = patch(this.node, patches);
    this.thunk = newThunk;
  }

  nodeChanged(node) {
    if (debug) {
      console.log('node changed', this.constructor.name);
    }
  }

  shouldUpdate(state, previousState) {
    if (!previousState || !state) {
      return true;
    }
    let previousType = typeof previousState;
    let currentType = typeof state;
    if (previousType != currentType) {
      return true;
    }
    switch (currentType) {
    case 'object': // shallow check
      let previousKeys = Object.keys(previousState);
      let currentKeys = Object.keys(state);
      if (previousKeys.length != currentKeys.length) {
        return true;
      }
      let len = currentKeys.length;
      for (let i = 0; i < len; i++) {
        let key = currentKeys[i];
        if (previousState[key] !== state[key]) {
          return true;
        }
      }
      return false;
    default:
      return !(previousState === state);
    }
  }
}

export function e(selector, properties, children) {
  switch (typeof selector) {
  case 'string':
    return h(selector, properties, children);
  default:
    return new selector(properties).thunk;
  }
}

export var none = h('div', { style: { display: 'none' } });

export function div(...subs) {
  return h('div', {}, [...subs]);
}
<|endoftext|>


<commit_before>
const Qs = require('qs');

const Track = require('./track.js');
const Reporting = require('./reporting.js');

let userId;

/*
 * Return a string of javascript that will post a message to us.
 * isInitial should be true for the very first message, false afterwards.
 */
function getInjectCode(isInitial) {
  const isInitialRepr = isInitial ? 'true' : 'false';

  /* eslint-disable prefer-template */
  const code = '(' + function inject() {
    window.postMessage(
      {isInitial: isInitialRepr,
        userId: window.USER_ID, tier: window.USER_CONTEXT[13], xt: window._GU_getCookie('xt')}, '*');
  } + ')()';
  /* eslint-enable prefer-template */

  // We need to actually get the value of our variable into the string, not a reference to it.
  return code.replace('isInitialRepr', isInitialRepr);
}

/*
 * Inject some javascript (as a string) into the DOM.
 */
function injectCode(code) {
  const script = document.createElement('script');
  script.textContent = code;
  (document.head || document.documentElement).appendChild(script);
  script.parentNode.removeChild(script);
}

/*
 * Callback an object with tracks (a list of jsproto tracks)
 * and timestamp keys from the local indexedDb.
 * Either may be null.
 */
function queryIDB(callback) {
  const dbName = `music_${userId}`;
  const DBOpenRequest = window.indexedDB.open(dbName, 6);

  DBOpenRequest.onerror = err => {
    console.error('could not open db', err);
    Reporting.Raven.captureMessage('DBOpenRequest.onerror', {
      extra: {err},
    });
    callback(null);
  };

  DBOpenRequest.onsuccess = event => { // eslint-disable-line no-unused-vars
    const db = DBOpenRequest.result;

    try {
      const transaction = db.transaction(['tracks', 'info'], 'readonly');
      queryInfo(transaction.objectStore('info'), timestamp => {
        queryTracks(transaction.objectStore('tracks'), tracks => {
          callback({timestamp, tracks});
        });
      });
    } catch (e) {
      // Sometimes the indexeddb just isn't written at all.
      // This happens for the very first load of Music, and maybe other cases.
      console.error(e);
      Reporting.Raven.captureException(e);
      callback(null);
    }
  };
}

// Callback the timestamp from the info object store, or null.
function queryInfo(infoStore, callback) {
  const infoRequest = infoStore.get('sync_token');

  infoRequest.onerror = err => {
    console.error(err);
    Reporting.Raven.captureMessage('infoRequest.onerror', {
      extra: {err},
    });
    callback(null);
  };

  infoRequest.onsuccess = event => {
    callback(event.target.result);
  };
}

// Callback a list of jsproto tracks from the tracks object store, or null.
function queryTracks(tracksStore, callback) {
  const gtracks = [];
  const tracksRequest = tracksStore.openCursor();

  tracksRequest.onerror = err => {
    console.error(err);
    Reporting.Raven.captureMessage('tracksRequest.onerror', {
      extra: {err},
    });
    callback(null);
  };

  tracksRequest.onsuccess = event => {
    const cursor = event.target.result;
    if (cursor) {
      const shard = JSON.parse(cursor.value);
      for (const id in shard) {
        gtracks.push(shard[id]);
      }

      cursor.continue();
    } else {
      callback(gtracks);
    }
  };
}

function main() {
  // This only exists in a multi-login session.
  const userIndex = Qs.parse(location.search.substring(1)).u || '0';

  // Pull the user id from the page before showing the page action.
  // Since we can't read window here, we inject code, then post a message back.

  window.addEventListener('message', event => {
    // We only accept messages from ourselves
    if (event.source !== window) {
      return;
    }

    console.log('received from page', event.data);

    userId = event.data.userId;
    const tier = event.data.tier;
    const xt = event.data.xt;
    const action = event.data.isInitial ? 'showPageAction' : 'setXsrf';

    chrome.runtime.sendMessage({
      action,
      tier,
      xt,
      userId: `${userId}`,
      userIndex: parseInt(userIndex, 10),
    });
  }, false);

  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log('got message', request);
    if (request.action === 'getLocalTracks') {
      queryIDB(result => {
        if (result.tracks !== null) {
          result.tracks = result.tracks.map(Track.fromJsproto); // eslint-disable-line no-param-reassign
        }

        sendResponse(result);
      });
      return true;
    } else if (request.action === 'getXsrf') {
      injectCode(getInjectCode(false));
    }
  });

  injectCode(getInjectCode(true));
}

main();
<commit_msg>ignore unauthed users<commit_after>
const Qs = require('qs');

const Track = require('./track.js');
const Reporting = require('./reporting.js');

let userId;

/*
 * Return a string of javascript that will post a message to us if the user is authenticated.
 * isInitial should be true for the very first message, false afterwards.
 */
function getInjectCode(isInitial) {
  const isInitialRepr = isInitial ? 'true' : 'false';

  // context[12] is the email for authenticated users.
  /* eslint-disable prefer-template */
  const code = '(' + function inject() {
    if (window.USER_CONTEXT[12] !== '') {
      window.postMessage(
        {isInitial: isInitialRepr,
          userId: window.USER_ID, tier: window.USER_CONTEXT[13], xt: window._GU_getCookie('xt')}, '*');
    }
  } + ')()';
  /* eslint-enable prefer-template */

  // We need to actually get the value of our variable into the string, not a reference to it.
  return code.replace('isInitialRepr', isInitialRepr);
}

/*
 * Inject some javascript (as a string) into the DOM.
 */
function injectCode(code) {
  const script = document.createElement('script');
  script.textContent = code;
  (document.head || document.documentElement).appendChild(script);
  script.parentNode.removeChild(script);
}

/*
 * Callback an object with tracks (a list of jsproto tracks)
 * and timestamp keys from the local indexedDb.
 * Either may be null.
 */
function queryIDB(callback) {
  const dbName = `music_${userId}`;
  const DBOpenRequest = window.indexedDB.open(dbName, 6);

  DBOpenRequest.onerror = err => {
    console.error('could not open db', err);
    Reporting.Raven.captureMessage('DBOpenRequest.onerror', {
      extra: {err},
    });
    callback(null);
  };

  DBOpenRequest.onsuccess = event => { // eslint-disable-line no-unused-vars
    const db = DBOpenRequest.result;

    try {
      const transaction = db.transaction(['tracks', 'info'], 'readonly');
      queryInfo(transaction.objectStore('info'), timestamp => {
        queryTracks(transaction.objectStore('tracks'), tracks => {
          callback({timestamp, tracks});
        });
      });
    } catch (e) {
      // Sometimes the indexeddb just isn't written at all.
      // This happens for the very first load of Music, and maybe other cases.
      console.error(e);
      Reporting.Raven.captureException(e);
      callback(null);
    }
  };
}

// Callback the timestamp from the info object store, or null.
function queryInfo(infoStore, callback) {
  const infoRequest = infoStore.get('sync_token');

  infoRequest.onerror = err => {
    console.error(err);
    Reporting.Raven.captureMessage('infoRequest.onerror', {
      extra: {err},
    });
    callback(null);
  };

  infoRequest.onsuccess = event => {
    callback(event.target.result);
  };
}

// Callback a list of jsproto tracks from the tracks object store, or null.
function queryTracks(tracksStore, callback) {
  const gtracks = [];
  const tracksRequest = tracksStore.openCursor();

  tracksRequest.onerror = err => {
    console.error(err);
    Reporting.Raven.captureMessage('tracksRequest.onerror', {
      extra: {err},
    });
    callback(null);
  };

  tracksRequest.onsuccess = event => {
    const cursor = event.target.result;
    if (cursor) {
      const shard = JSON.parse(cursor.value);
      for (const id in shard) {
        gtracks.push(shard[id]);
      }

      cursor.continue();
    } else {
      callback(gtracks);
    }
  };
}

function main() {
  // This only exists in a multi-login session.
  const userIndex = Qs.parse(location.search.substring(1)).u || '0';

  // Pull the user id from the page before showing the page action.
  // Since we can't read window here, we inject code, then post a message back.

  window.addEventListener('message', event => {
    // We only accept messages from ourselves
    if (event.source !== window) {
      return;
    }

    console.log('received from page', event.data);

    userId = event.data.userId;
    const tier = event.data.tier;
    const xt = event.data.xt;
    const action = event.data.isInitial ? 'showPageAction' : 'setXsrf';

    chrome.runtime.sendMessage({
      action,
      tier,
      xt,
      userId: `${userId}`,
      userIndex: parseInt(userIndex, 10),
    });
  }, false);

  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log('got message', request);
    if (request.action === 'getLocalTracks') {
      queryIDB(result => {
        if (result.tracks !== null) {
          result.tracks = result.tracks.map(Track.fromJsproto); // eslint-disable-line no-param-reassign
        }

        sendResponse(result);
      });
      return true;
    } else if (request.action === 'getXsrf') {
      injectCode(getInjectCode(false));
    }
  });

  injectCode(getInjectCode(true));
}

main();
<|endoftext|>


<commit_before>/**
 * Created by hpb on 7/15/2017.
 */
$(document).ready(function() {
    $('#example1').DataTable({responsive: true});

} );

$(document).on("click", ".open-modal-action", function () {
    var item_id = $(this).data('id');
    $(".modal-body #item-id").val( item_id );

    var item = $(this).data('id');
    $(".modal-body #dist-id").val( item );

    var return_id = $(this).data('id');
    $(".modal-body #return-id").val( return_id );

    var user_id = $(this).data('id');
    $(".modal-body #user-id").val( user_id );
});

var inventory;
var department;
var increaselog;

$(document).ready(function() {

    inventory = $('#table').DataTable({

        destroy: true,
        responsive: true,
        "ajax": {
            "url": 'inventory/inventory_list',
            "type": "POST",
        },
    });

    department = $('#department').DataTable({
        destroy: true,
        responsive: true,
        "ajax": {
            "url":'department/get_all_dept_list',
            "type": "POST",
        },
    });

    $('select[name="department"]').change(function(){
        var id = $(this).val();

        department = $('#department').DataTable({
            responsive: true,
            "destroy": true,
            "ajax": {
                "url":'department/get_dept_list/'+id,
                "type": "POST",
            },
        });
        if (id == 'none') {
            department.column( 0 ).visible( true );
        } else {
            department.column( 0 ).visible( false );
        }

    });

    increaselog = $('#increase_log').DataTable({
        destroy: true,
        responsive: true,
        "ajax": {
            "url": 'increaselog/increase_log_list',
            "type": "POST",
        },
    });

    decreaselog = $('#decrease_log').DataTable({
        responsive: true,
        "destroy":true,
        "ajax": {
            "url": 'decreaselog/decrease_log_list',
            "type": "POST",
        },
    });

    returnlog = $('#return_log').DataTable({
        responsive: true,
        "destroy":true,
        "ajax": {
            "url": 'returnlog/return_log_list',
            "type": "POST",
        },
    });

    returned_items = $('#returned_items').DataTable({
        responsive: true,
        "destroy":true,
        "ajax": {
            "url": 'returned/returned_list',
            "type": "POST",
        },
    });

    pending = $('#pending').DataTable({
        responsive: true,
        "destroy":true,
        "ajax": {
            "url": 'users/display_pending_users',
            "type": "POST",
        },
    });

    setInterval(function () {
        inventory.ajax.reload(null,false);
        department.ajax.reload(null,false);
        returned_items.ajax.reload(null,false);
        pending.ajax.reload(null,false);
    }, 1000);
});

function summary() {
    $('#departmentsummary').DataTable({
        responsive: true,
        "destroy": true,
        "ajax": {
            "url": 'department/summary_items',
            "type": "POST",
        },
    });
    $('#summary').modal('show');
}

function subtract_quantity(id) {
    $.ajax({
        url: 'inventory/get_quantity/' + id,
        type:"POST",
        dataType: 'json',
        success: function(data){
            $('input[name="Quantity"]').attr('max', data.data);
            $('#subqty').modal('show');
        },
    });

}

function return_no_action(id) {
    $.ajax({
        url: 'returned/no_action/' + id,
        type:"POST",
        success: function() {
            location.href = window.location.origin + "/app/returned"
        }
    });

}
//select all
$(document).ready(function () {
    $('input[name=select-all]').change(function () {
        $('input[name=item-det]').prop('checked',this.checked);
    });
});
function get_item_details(id) {
    var serial;
    var item_det_id = [];
    var oldData;
    //detail list
    details = $('#details').DataTable({
        responsive: true,
        "destroy": true,
        "ajax": {
            "url": 'inventory/itemdetail/' + id,
            "type": "GET",
        },
    });

    //multiple serial input
   $('#details ').on( 'change ',  function () {
           $('tr :nth-child(2)').attr('contentEditable', 'true');
           $(this).focus(function () {
               oldData = $(this).text();
           });

           // input field for serial
       $.each($('#details tr input[name=item-det]'),function () {
               // reset button
               $('input[type=reset]').on('click', function () {
                   $('input[type=number]').val('').change();
               });
               $('input[type=number]').on('keyup change ', function () {
                   serial = ($(this).val());
                   $.each($('#details tr input[name=item-det]:checked'), function () {
                       $(this).parent().siblings(':first').text(serial);
                   });

               });
       });
   });
   //single serial input
       $('#details').on( 'click', 'tr :nth-child(2)', function () {
           $(this).attr('contentEditable', 'true');
           $(this).focus(function () {
               oldData = $(this).text();
           });
           $(this).blur(function () {
               serial = $(this).text();
               if(oldData != serial) {
                   $.ajax({
                       type: "POST",
                       url: 'inventory/set_serial/' + id,
                       data: {'serial':serial},
                       dataType: 'json',
                   });
               }
           });

       });

    $('#view').modal('show');

}

function get_distribution_details(id) {
    $('#details').DataTable({
        responsive: true,
        "destroy": true,
        "ajax": {
            "url": 'department/dist_details/' + id,
            "type": "POST",
        },
    });
    $('#view').modal('show');
}

var save_method; //for save method string

function edit_inventory(id)
{
    save_method = 'update';

    //Ajax Load data from ajax
    $.ajax({
        url : 'inventory/edit/' + id,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {
            $.each(data, function(i, item) {
                $('[name="item_id"]').val(data[i].item_id);
                $('[name="item_name"]').val(data[i].item_name);
                $('[name="desc"]').val(data[i].item_description);
                $('[name="unit"]').val(data[i].unit);
                $('[name="qty"]').val(data[i].quantity);
            });
            $('#edit').modal('show'); // show bootstrap modal when complete loaded

        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error get data from ajax');
        }
    });
}
function save()
{
    var url;
    if(save_method === 'update')

        url = 'admin/edit/item_update';

    // ajax adding data to database
    $.ajax({
        url : url,
        type: "POST",
        data: $('#form').serialize(),
        dataType: "JSON",
        success: function(data)
        {
            //if success close modal and reload ajax table
            $('#edit').modal('hide');
            location.reload();// for reload a page
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error adding / update data');
        }
    });
}

//form validations
    $(document).ready(function () {

        $( "input[name=Item_Quantity]" ).on("keypress paste",function () {
            var x = event.charCode;
            if(x === 101 || x === 46 || x === 45 || x === 43){
                return false;
            }
        });
        $( "input[name=Cost]" ).on("keypress paste",function () {
            var x = event.charCode;
            if(x === 101 ||  x === 45 || x === 43){
                return false;
            }
        });
        $( "input[id=new_qty]" ).on("keypress paste",function () {
            var x = event.charCode;
            if(x === 101 || x === 46 || x === 45 || x === 43){
                return false;
            }
        });
        $( "input[id=new_cost]" ).on("keypress paste",function () {
            var x = event.charCode;
            if(x === 101 ||  x === 45 || x === 43){
                return false;
            }
        });
        $( "input[name=datereceived]" ).on("blur",function () {
            del_date = new Date($('input[name=datedelivered]').val());
            date_rec = new Date($('input[name=datereceived]').val());

            if(del_date > date_rec){
                $(this).val('');
            }
        });

        $( "input[name=ExpirationDate]" ).on("blur",function () {
            date_rec = new Date($('input[name=datereceived]').val());
            exp_date = new Date($('input[name=ExpirationDate]').val());

            if(exp_date < date_rec){
                $(this).val('');
            }
        });

    });
//return items

function return_selected_items() {
    var item_det_id = [];
    var reason;
    var person;
    var checked;

    $('#item_detail:checked').each(function () {
        item_det_id.push($(this).val());
    });

    $('#returnmodal').modal('show');

    $('button[id=save1]').on('click',function () {
        reason =  $('textarea#reason').val();
        person =  $('input[name=person]').val();

        if ($('input[name=defect]').is(":checked"))
        {
            checked = 'yes';
        } else {
            checked = 'no';
        }

        var item_data;

        if ($('#item_detail:checked').length > 0 && reason && person) {
            item_data = {'item_det_id':item_det_id,'reason':reason,'person':person, 'ischecked': checked};
        } else {
            window.alert("Please check at least 1 item and input all required fields. Try again.");
            return;
        }

        $.ajax({
           url : 'department/return_items',
           type: "POST",
           data: item_data,
           dataType: "JSON",
        });
    });
}

// var countreceiveditem
// var viewitemremaining
var countretitem
// var defitem
//var pendingusers

$(document).ready(function() {

 countretitem = $('#table').DataTable({

        destroy: true,
        responsive: true,
        "ajax": {
            "url": 'dashboard',
            "type": "POST",
        },
    });

 // countreceiveditem = $('#table').DataTable({

  //       destroy: true,
  //       responsive: true,
  //       "ajax": {
  //           "url": 'dashboard',
  //           "type": "POST",
  //       },
  //   });

  //viewitemremaining = $('#table').DataTable({

  //       destroy: true,
  //       responsive: true,
  //       "ajax": {
  //           "url": 'dashboard',
  //           "type": "POST",
  //       },
  //   });

  //defitem = $('#table').DataTable({

  //       destroy: true,
 //        responsive: true,
  //       "ajax": {
  //           "url": 'dashboard',
  //           "type": "POST",
  //       },
  //   });

  //pendingusers = $('#table').DataTable({

  //       destroy: true,
  //       responsive: true,
  //       "ajax": {
  //           "url": 'dashboard',
  //           "type": "POST",
  //       },
  //   });
}
<commit_msg>update<commit_after>/**
 * Created by hpb on 7/15/2017.
 */
$(document).ready(function() {
    $('#example1').DataTable({responsive: true});

} );

$(document).on("click", ".open-modal-action", function () {
    var item_id = $(this).data('id');
    $(".modal-body #item-id").val( item_id );

    var item = $(this).data('id');
    $(".modal-body #dist-id").val( item );

    var return_id = $(this).data('id');
    $(".modal-body #return-id").val( return_id );

    var user_id = $(this).data('id');
    $(".modal-body #user-id").val( user_id );
});

var inventory;
var department;
var increaselog;

$(document).ready(function() {

    inventory = $('#table').DataTable({

        destroy: true,
        responsive: true,
        "ajax": {
            "url": 'inventory/inventory_list',
            "type": "POST",
        },
    });

    department = $('#department').DataTable({
        destroy: true,
        responsive: true,
        "ajax": {
            "url":'department/get_all_dept_list',
            "type": "POST",
        },
    });

    $('select[name="department"]').change(function(){
        var id = $(this).val();

        department = $('#department').DataTable({
            responsive: true,
            "destroy": true,
            "ajax": {
                "url":'department/get_dept_list/'+id,
                "type": "POST",
            },
        });
        if (id == 'none') {
            department.column( 0 ).visible( true );
        } else {
            department.column( 0 ).visible( false );
        }

    });

    increaselog = $('#increase_log').DataTable({
        destroy: true,
        responsive: true,
        "ajax": {
            "url": 'increaselog/increase_log_list',
            "type": "POST",
        },
    });

    decreaselog = $('#decrease_log').DataTable({
        responsive: true,
        "destroy":true,
        "ajax": {
            "url": 'decreaselog/decrease_log_list',
            "type": "POST",
        },
    });

    returnlog = $('#return_log').DataTable({
        responsive: true,
        "destroy":true,
        "ajax": {
            "url": 'returnlog/return_log_list',
            "type": "POST",
        },
    });

    returned_items = $('#returned_items').DataTable({
        responsive: true,
        "destroy":true,
        "ajax": {
            "url": 'returned/returned_list',
            "type": "POST",
        },
    });

    pending = $('#pending').DataTable({
        responsive: true,
        "destroy":true,
        "ajax": {
            "url": 'users/display_pending_users',
            "type": "POST",
        },
    });

    setInterval(function () {
        inventory.ajax.reload(null,false);
        department.ajax.reload(null,false);
        returned_items.ajax.reload(null,false);
        pending.ajax.reload(null,false);
    }, 1000);
});

function summary() {
    $('#departmentsummary').DataTable({
        responsive: true,
        "destroy": true,
        "ajax": {
            "url": 'department/summary_items',
            "type": "POST",
        },
    });
    $('#summary').modal('show');
}

function subtract_quantity(id) {
    $.ajax({
        url: 'inventory/get_quantity/' + id,
        type:"POST",
        dataType: 'json',
        success: function(data){
            $('input[name="Quantity"]').attr('max', data.data);
            $('#subqty').modal('show');
        },
    });

}

function return_no_action(id) {
    $.ajax({
        url: 'returned/no_action/' + id,
        type:"POST",
        success: function() {
            location.href = window.location.origin + "/app/returned"
        }
    });

}
//select all
$(document).ready(function () {
    $('input[name=select-all]').change(function () {
        $('input[name=item-det]').prop('checked',this.checked);
    });
});
function get_item_details(id) {
    var serial;
    var item_det_id = [];
    var oldData;
    //detail list
    details = $('#details').DataTable({
        responsive: true,
        "destroy": true,
        "ajax": {
            "url": 'inventory/itemdetail/' + id,
            "type": "GET",
        },
    });

    //multiple serial input
   $('#details ').on( 'change ',  function () {
           $('tr :nth-child(2)').attr('contentEditable', 'true');
           $(this).focus(function () {
               oldData = $(this).text();
           });

           // input field for serial
       $.each($('#details tr input[name=item-det]'),function () {
               // reset button
               $('input[type=reset]').on('click', function () {
                   $('input[type=number]').val('').change();
               });
               $('input[type=number]').on('keyup change ', function () {
                   serial = ($(this).val());
                   $.each($('#details tr input[name=item-det]:checked'), function () {
                       $(this).parent().siblings(':first').text(serial);
                   });

               });
       });
   });
   //single serial input
       $('#details').on( 'click', 'tr :nth-child(2)', function () {
           $(this).attr('contentEditable', 'true');
           $(this).focus(function () {
               oldData = $(this).text();
           });
           $(this).blur(function () {
               serial = $(this).text();
               if(oldData != serial) {
                   $.ajax({
                       type: "POST",
                       url: 'inventory/set_serial/' + id,
                       data: {'serial':serial},
                       dataType: 'json',
                   });
               }
           });

       });

    $('#view').modal('show');

}

function get_distribution_details(id) {
    $('#details').DataTable({
        responsive: true,
        "destroy": true,
        "ajax": {
            "url": 'department/dist_details/' + id,
            "type": "POST",
        },
    });
    $('#view').modal('show');
}

var save_method; //for save method string

function edit_inventory(id)
{
    save_method = 'update';

    //Ajax Load data from ajax
    $.ajax({
        url : 'inventory/edit/' + id,
        type: "GET",
        dataType: "JSON",
        success: function(data)
        {
            $.each(data, function(i, item) {
                $('[name="item_id"]').val(data[i].item_id);
                $('[name="item_name"]').val(data[i].item_name);
                $('[name="desc"]').val(data[i].item_description);
                $('[name="unit"]').val(data[i].unit);
                $('[name="qty"]').val(data[i].quantity);
            });
            $('#edit').modal('show'); // show bootstrap modal when complete loaded

        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error get data from ajax');
        }
    });
}
function save()
{
    var url;
    if(save_method === 'update')

        url = 'admin/edit/item_update';

    // ajax adding data to database
    $.ajax({
        url : url,
        type: "POST",
        data: $('#form').serialize(),
        dataType: "JSON",
        success: function(data)
        {
            //if success close modal and reload ajax table
            $('#edit').modal('hide');
            location.reload();// for reload a page
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            alert('Error adding / update data');
        }
    });
}

//form validations
    $(document).ready(function () {

        $( "input[name=Item_Quantity]" ).on("keypress paste",function () {
            var x = event.charCode;
            if(x === 101 || x === 46 || x === 45 || x === 43){
                return false;
            }
        });
        $( "input[name=Cost]" ).on("keypress paste",function () {
            var x = event.charCode;
            if(x === 101 ||  x === 45 || x === 43){
                return false;
            }
        });
        $( "input[id=new_qty]" ).on("keypress paste",function () {
            var x = event.charCode;
            if(x === 101 || x === 46 || x === 45 || x === 43){
                return false;
            }
        });
        $( "input[id=new_cost]" ).on("keypress paste",function () {
            var x = event.charCode;
            if(x === 101 ||  x === 45 || x === 43){
                return false;
            }
        });
        $( "input[name=datereceived]" ).on("blur",function () {
            del_date = new Date($('input[name=datedelivered]').val());
            date_rec = new Date($('input[name=datereceived]').val());

            if(del_date > date_rec){
                $(this).val('');
            }
        });

        $( "input[name=ExpirationDate]" ).on("blur",function () {
            date_rec = new Date($('input[name=datereceived]').val());
            exp_date = new Date($('input[name=ExpirationDate]').val());

            if(exp_date < date_rec){
                $(this).val('');
            }
        });

    });
//return items

function return_selected_items() {
    var item_det_id = [];
    var reason;
    var person;
    var checked;

    $('#item_detail:checked').each(function () {
        item_det_id.push($(this).val());
    });

    $('#returnmodal').modal('show');

    $('button[id=save1]').on('click',function () {
        reason =  $('textarea#reason').val();
        person =  $('input[name=person]').val();

        if ($('input[name=defect]').is(":checked"))
        {
            checked = 'yes';
        } else {
            checked = 'no';
        }

        var item_data;

        if ($('#item_detail:checked').length > 0 && reason && person) {
            item_data = {'item_det_id':item_det_id,'reason':reason,'person':person, 'ischecked': checked};
        } else {
            window.alert("Please check at least 1 item and input all required fields. Try again.");
            return;
        }

        $.ajax({
           url : 'department/return_items',
           type: "POST",
           data: item_data,
           dataType: "JSON",
        });
    });
}

function count_received_item(item_id, quantity)
{
    $.ajax({
        method: "POST",
        url: "dashboard",
        dataType: "JSON",
        data:{item_id}
})
}

  //countreceiveditem = $('#table').DataTable({

  //       destroy: true,
  //       responsive: true,
  //       "ajax": {
  //           "url": 'dashboard',
  //           "type": "POST",
  //       },
  //   });

  //viewitemremaining = $('#table').DataTable({

  //       destroy: true,
  //       responsive: true,
  //       "ajax": {
  //           "url": 'dashboard',
  //           "type": "POST",
  //       },
  //   });

  //defitem = $('#table').DataTable({

  //       destroy: true,
 //        responsive: true,
  //       "ajax": {
  //           "url": 'dashboard',
  //           "type": "POST",
  //       },
  //   });

  //pendingusers = $('#table').DataTable({

  //       destroy: true,
  //       responsive: true,
  //       "ajax": {
  //           "url": 'dashboard',
  //           "type": "POST",
  //       },
  //   });
<|endoftext|>


<commit_before>var Remix = {
    init: function(apiKey) {
        if (apiKey) {
            // TODO handle quota exception
            localStorage.echoNestApiKey = apiKey;
        }
        swfobject.embedSWF('remix.swf', 'swf', '0', '0', '9.0.0', null, {apiKey: localStorage.echoNestApiKey}, {wmode: 'transparent'});

        this._tracks = [];
        this._trackMap = {};

        this._searchMap = {};

        // add selection and sorting functions to global scope
        extend(window, selection);
        extend(window, sorting);
    },

    apiKeyRequired: function () {
        return !localStorage.echoNestApiKey;
    },

    onError: function(message) {},

    log: function () {},

    __init: function() {
        this._swf = document.getElementById('swf');
    },

    getTrack: function(trackId) {
        var track = this._trackMap[trackId];
        if (!track) {
            track = {id: trackId};
            this._trackMap[trackId] = track;
            this._tracks.push(track);
            this.onTrackAdded(track);
        }
        return track;
    },

    removeTrack: function (track) {
        var i = this._tracks.indexOf(track);
        this._tracks.splice(i, 1);
        delete this._trackMap[track.id];
        this._swf.unloadTrack(track.id);
    },

    __setTrackState: function (trackId, state, arg) {
        Remix.log('track state: ', trackId, state, arg);
        var track = this.getTrack(trackId);
        track.state = state;
        if (state == 'sound_loading') {
            track.file = arg;
            this.onTrackSoundLoading(track);
        }
        else if (state == 'sound_loaded') {
            track.sound = arg;
            track.soundLoaded = true;
            this.onTrackSoundLoaded(track);
        }
        else if (state == 'md5_calculated') {
            track.md5 = arg;
            track.key = arg;
            this._loadAnalysis(track);
        }
        else if (state == 'analysis_loading') {
            this.onTrackAnalysisLoading(track);
        }
        else if (state == 'analysis_loaded') {
            track.rawAnalysis = arg;
            track.analysis = new AudioAnalysis(track.rawAnalysis);
            track.analysis.track = track;
            localStorage['analysis_' + track.key] = JSON.stringify(track.rawAnalysis);
            track.analysisLoaded = true;
            this.onTrackAnalysisLoaded(track);
        }
    },

    _loadAnalysis: function (track) {
        var analysisString = localStorage['analysis_' + track.key];
        if (analysisString) {
            track.rawAnalysis = JSON.parse(analysisString);
            track.analysis = new AudioAnalysis(track.rawAnalysis);
            track.analysis.track = track;
            track.analysisLoaded = true;
            this.onTrackAnalysisLoaded(track);
        }
        else {
            this._swf.loadAnalysis(track.id);
        }
    },

    onTrackAdded: function (track) {},

    onTrackSoundLoading: function (track) {},

    onTrackSoundLoaded: function (track) {},

    onTrackAnalysisLoading: function (track) {},

    onTrackAnalysisLoaded: function (track) {},

    togglePlayPause: function () {
        this._swf.togglePlayPause();
    },

    resetPlayer: function () {
        this._swf.resetPlayer();
    },

    __setProgress: function (progress, sourceIndex, sourcePosition) {
        this.onPlayerProgress(progress, sourceIndex, sourcePosition);
    },

    onPlayerProgress: function (progress, sourceIndex, sourcePosition) {},

    __setPlayerState: function (state) {
        this['onPlayer' + state[0].toUpperCase() + state.substring(1)]();
    },

    onPlayerReady: function () {},

    onPlayerEmpty: function () {},

    onPlayerPlaying: function () {},

    onPlayerPaused: function () {},

    onPlayerComplete: function () {},

    search: function (params) {
        var search = {params: params};
        var searchId = this._swf.search(params);
        search.id = searchId;
        this._searchMap[searchId] = search;
        return search;
    },

    __setSearchState: function (searchId, state, arg) {
        Remix.log('search state: ', searchId, state, arg);
        var search = this._searchMap[searchId];
        if (state == 'echo_nest_error') {
            if (arg.description == 'no results') {
                this.onSearchNoResults(search);
            }
            else {
                search.error = arg;
                this.onSearchError(search);
            }
        }
        else if (state == 'error') {
            search.error = arg;
            this.onSearchError(search);
        }
        else if (state == 'complete') {
            search.results = arg;
            this.onSearchResults(search);
        }
    },

    onSearchResults: function (search) {},

    onSearchNoResults: function (search) {},

    remix: function(aqs) {
        try {
            if (!aqs) {
                Remix.onError('remix must return an array of audio quanta');
                return;
            }
            aqs = Remix.processAqs(aqs);
            this.mixSpec = [];
            for (var i = 0; i < aqs.length; i++) {
                var aq = aqs[i];
                if (aq.end < aq.start) {
                    Remix.onError('end position ' + i + ' is before start position');
                    return;
                }
                var track = aq.track || aq.container.analysis.track;
                var spec = [track.id, aq.start, aq.end];

                if (aq.filters) {
                    spec.push({filters: aq.filters});
                }
                this.mixSpec.push(spec);
            }

            if (this.onRemix) {
                this.onRemix(aqs);
            }
            this.playingSingleRange = false;
            this.remixString(JSON.stringify(this.mixSpec));
        }
        catch (e) {
            Remix.onError(e);
        }
    },

    processAqs: function(aqs) {
        if (aqs.flatten) {
            aqs = aqs.flatten();
        }
        else {
            aqs = [aqs];
        }
        var result = [];
        var offset = 0;
        for (var i = 0; i < aqs.length; i++) {
            var aq = aqs[i];
            var track = aq.track || aq.container.analysis.track;
            var duration = aq.end - aq.start;
            result.push({
                track: track,
                source: aq,
                start: aq.start,
                end: aq.end,
                index: i,
                duration: duration,
                offset: offset,
                filters: aq.filters});

            offset += duration;
        }
        return result;
    },

    play: function (aq) {
        var track = aq.track || aq.container.analysis.track;
        var spec = [track.id, aq.start, aq.end];
        this.playingSingleRange = true;
        this.remixString(JSON.stringify([spec]));
    },

    remixString: function (string) {
        this._swf.setRemixString(string);
    },

    load: function (url, enTrackId) {
        var trackId = this._swf.load(url, enTrackId);
        var track = this.getTrack(trackId);
        track.key = enTrackId;
        this._loadAnalysis(track);
        return track;
    }
};

Remix.__log = Remix.log;

if (!window.localStorage) {
    window.localStorage = {};
}

if (''.toJSON) {
    JSON.stringify = Object.toJSON;
    JSON.parse = JSON.parse || function(s) { return s.evalJSON(true); };
}

FilteredAudioQuantum.addFilter('touch');
<commit_msg>fix remix to not process aqs twice<commit_after>var Remix = {
    init: function(apiKey) {
        if (apiKey) {
            // TODO handle quota exception
            localStorage.echoNestApiKey = apiKey;
        }
        swfobject.embedSWF('remix.swf', 'swf', '0', '0', '9.0.0', null, {apiKey: localStorage.echoNestApiKey}, {wmode: 'transparent'});

        this._tracks = [];
        this._trackMap = {};

        this._searchMap = {};

        // add selection and sorting functions to global scope
        extend(window, selection);
        extend(window, sorting);
    },

    apiKeyRequired: function () {
        return !localStorage.echoNestApiKey;
    },

    onError: function(message) {},

    log: function () {},

    __init: function() {
        this._swf = document.getElementById('swf');
    },

    getTrack: function(trackId) {
        var track = this._trackMap[trackId];
        if (!track) {
            track = {id: trackId};
            this._trackMap[trackId] = track;
            this._tracks.push(track);
            this.onTrackAdded(track);
        }
        return track;
    },

    removeTrack: function (track) {
        var i = this._tracks.indexOf(track);
        this._tracks.splice(i, 1);
        delete this._trackMap[track.id];
        this._swf.unloadTrack(track.id);
    },

    __setTrackState: function (trackId, state, arg) {
        Remix.log('track state: ', trackId, state, arg);
        var track = this.getTrack(trackId);
        track.state = state;
        if (state == 'sound_loading') {
            track.file = arg;
            this.onTrackSoundLoading(track);
        }
        else if (state == 'sound_loaded') {
            track.sound = arg;
            track.soundLoaded = true;
            this.onTrackSoundLoaded(track);
        }
        else if (state == 'md5_calculated') {
            track.md5 = arg;
            track.key = arg;
            this._loadAnalysis(track);
        }
        else if (state == 'analysis_loading') {
            this.onTrackAnalysisLoading(track);
        }
        else if (state == 'analysis_loaded') {
            track.rawAnalysis = arg;
            track.analysis = new AudioAnalysis(track.rawAnalysis);
            track.analysis.track = track;
            localStorage['analysis_' + track.key] = JSON.stringify(track.rawAnalysis);
            track.analysisLoaded = true;
            this.onTrackAnalysisLoaded(track);
        }
    },

    _loadAnalysis: function (track) {
        var analysisString = localStorage['analysis_' + track.key];
        if (analysisString) {
            track.rawAnalysis = JSON.parse(analysisString);
            track.analysis = new AudioAnalysis(track.rawAnalysis);
            track.analysis.track = track;
            track.analysisLoaded = true;
            this.onTrackAnalysisLoaded(track);
        }
        else {
            this._swf.loadAnalysis(track.id);
        }
    },

    onTrackAdded: function (track) {},

    onTrackSoundLoading: function (track) {},

    onTrackSoundLoaded: function (track) {},

    onTrackAnalysisLoading: function (track) {},

    onTrackAnalysisLoaded: function (track) {},

    togglePlayPause: function () {
        this._swf.togglePlayPause();
    },

    resetPlayer: function () {
        this._swf.resetPlayer();
    },

    __setProgress: function (progress, sourceIndex, sourcePosition) {
        this.onPlayerProgress(progress, sourceIndex, sourcePosition);
    },

    onPlayerProgress: function (progress, sourceIndex, sourcePosition) {},

    __setPlayerState: function (state) {
        this['onPlayer' + state[0].toUpperCase() + state.substring(1)]();
    },

    onPlayerReady: function () {},

    onPlayerEmpty: function () {},

    onPlayerPlaying: function () {},

    onPlayerPaused: function () {},

    onPlayerComplete: function () {},

    search: function (params) {
        var search = {params: params};
        var searchId = this._swf.search(params);
        search.id = searchId;
        this._searchMap[searchId] = search;
        return search;
    },

    __setSearchState: function (searchId, state, arg) {
        Remix.log('search state: ', searchId, state, arg);
        var search = this._searchMap[searchId];
        if (state == 'echo_nest_error') {
            if (arg.description == 'no results') {
                this.onSearchNoResults(search);
            }
            else {
                search.error = arg;
                this.onSearchError(search);
            }
        }
        else if (state == 'error') {
            search.error = arg;
            this.onSearchError(search);
        }
        else if (state == 'complete') {
            search.results = arg;
            this.onSearchResults(search);
        }
    },

    onSearchResults: function (search) {},

    onSearchNoResults: function (search) {},

    remix: function(aqs) {
        try {
            if (!aqs) {
                Remix.onError('remix must return an array of audio quanta');
                return;
            }
            if (!aqs.processed) {
                aqs = Remix.processAqs(aqs);
            }
            this.playingAqs = aqs;
            this.mixSpec = [];
            for (var i = 0; i < aqs.length; i++) {
                var aq = aqs[i];
                if (aq.end < aq.start) {
                    Remix.onError('end position ' + i + ' is before start position');
                    return;
                }
                var track = aq.track || aq.container.analysis.track;
                var spec = [track.id, aq.start, aq.end];

                if (aq.filters) {
                    spec.push({filters: aq.filters});
                }
                this.mixSpec.push(spec);
            }
            this.playingSingleRange = false;
            this.remixString(JSON.stringify(this.mixSpec));
        }
        catch (e) {
            Remix.onError(e);
        }
    },

    processAqs: function(aqs) {
        if (aqs.flatten) {
            aqs = aqs.flatten();
        }
        else {
            aqs = [aqs];
        }
        var result = [];
        result.processed = true;
        var offset = 0;
        for (var i = 0; i < aqs.length; i++) {
            var aq = aqs[i];
            var track = aq.track || aq.container.analysis.track;
            var duration = aq.end - aq.start;
            result.push({
                track: track,
                source: aq,
                start: aq.start,
                end: aq.end,
                index: i,
                duration: duration,
                offset: offset,
                filters: aq.filters});

            offset += duration;
        }
        return result;
    },

    play: function (aq) {
        var track = aq.track || aq.container.analysis.track;
        var spec = [track.id, aq.start, aq.end];
        this.playingSingleRange = true;
        this.remixString(JSON.stringify([spec]));
    },

    remixString: function (string) {
        this._swf.setRemixString(string);
    },

    load: function (url, enTrackId) {
        var trackId = this._swf.load(url, enTrackId);
        var track = this.getTrack(trackId);
        track.key = enTrackId;
        this._loadAnalysis(track);
        return track;
    }
};

Remix.__log = Remix.log;

if (!window.localStorage) {
    window.localStorage = {};
}

if (''.toJSON) {
    JSON.stringify = Object.toJSON;
    JSON.parse = JSON.parse || function(s) { return s.evalJSON(true); };
}

FilteredAudioQuantum.addFilter('touch');
<|endoftext|>


<commit_before>var helpers = require('./global-setup')
var path = require('path')

var describe = global.describe
var it = global.it
var before = global.before
var after = global.after

describe('window commands', function () {
  helpers.setupTimeout(this)

  var app = null

  before(function () {
    return helpers.startApplication({
      args: [path.join(__dirname, 'fixtures', 'app')]
    }).then(function (startedApp) { app = startedApp })
  })

  after(function () {
    return helpers.stopApplication(app)
  })

  describe('getWindowCount', function () {
    it('retrieves the window count', function () {
      return app.client.getWindowCount().should.eventually.equal(1)
    })
  })

  describe('getWindowBounds', function () {
    it('gets the window bounds', function () {
      return app.client.getWindowBounds().should.eventually.deep.equal({
        x: 25,
        y: 35,
        width: 200,
        height: 100
      })
    })
  })

  describe('getWindowWidth', function () {
    it('gets the window width', function () {
      return app.client.getWindowWidth().should.eventually.equal(200)
    })
  })

  describe('getWindowHeight', function () {
    it('gets the window height', function () {
      return app.client.getWindowHeight().should.eventually.equal(100)
    })
  })

  describe('setWindowBounds', function () {
    it('sets the window bounds', function () {
      return app.client
        .setWindowBounds({
          x: 100,
          y: 200,
          width: 50,
          height: 75
        })
        .pause(1000)
        .getWindowBounds().should.eventually.deep.equal({
          x: 100,
          y: 200,
          width: 50,
          height: 75
        })
    })
  })

  describe('isWindowFocused()', function () {
    it('returns true when the current window is focused', function () {
      return app.client.isWindowFocused().should.eventually.be.true
    })
  })

  describe('isWindowVisible()', function () {
    it('returns true when the window is visible, false otherwise', function () {
      return app.client
        .hideWindow()
        .isWindowVisible().should.eventually.be.false
        .showWindow()
        .isWindowVisible().should.eventually.be.true
    })
  })

  describe('isWindowDevToolsOpened()', function () {
    it('returns false when the dev tools are closed', function () {
      return app.client.isWindowDevToolsOpened().should.eventually.be.false
    })
  })

  describe('isWindowFullScreen()', function () {
    it('returns false when the window is not in full screen mode', function () {
      return app.client.isWindowFullScreen().should.eventually.be.false
    })
  })

  describe('waitUntilWindowLoaded()', function () {
    it('waits until the current window is loaded', function () {
      return app.client.waitUntilWindowLoaded().isWindowLoading().should.eventually.be.false
    })
  })

  describe('isWindowMaximized()', function () {
    it('returns true when the window is maximized, false otherwise', function () {
      return app.client.isWindowMaximized().should.eventually.be.false
        .maximizeWindow().waitUntil(function () {
          // FIXME window maximized state is never true on CI
          if (process.env.CI) return Promise.resolve(true)

          return this.isWindowMaximized()
        }, 5000).then(function () { })
    })
  })

  describe('isWindowMinimized()', function () {
    it('returns true when the window is minimized, false otherwise', function () {
      return app.client.isWindowMinimized().should.eventually.be.false
        .minimizeWindow().waitUntil(function () {
          // FIXME window minimized state is never true on CI
          if (process.env.CI) return Promise.resolve(true)

          return this.isWindowMinimized()
        }, 5000).then(function () { })
    })
  })

  describe('selectAll()', function () {
    it('selects all the text on the page', function () {
      return app.client.selectAll()
        .getSelectedText().should.eventually.contain('Hello')
    })
  })

  describe('paste()', function () {
    it('pastes the text into the focused element', function () {
      return app.client
        .getText('textarea').should.eventually.equal('')
        .setClipboardText('pasta')
        .getClipboardText().should.eventually.equal('pasta')
        .click('textarea')
        .paste()
        .waitForValue('textarea', 5000)
        .getValue('textarea').should.eventually.equal('pasta')
    })
  })

  describe('isDocumentEdited', function () {
    it('returns true when the document is edited', function () {
      if (process.platform !== 'darwin') return

      return app.client
        .isDocumentEdited().should.eventually.be.false
        .setDocumentEdited(true)
        .isDocumentEdited().should.eventually.be.true
    })
  })

  describe('getRepresentedFilename', function () {
    it('returns the represented filename', function () {
      if (process.platform !== 'darwin') return

      return app.client
        .getRepresentedFilename().should.eventually.equal('')
        .setRepresentedFilename('/foo.js')
        .getRepresentedFilename().should.eventually.equal('/foo.js')
    })
  })

  describe('deprecated APIs', function () {
    describe('setWindowDimensions', function () {
      it('sets the bounds of the window', function () {
        return app.client
          .setWindowDimensions(100, 200, 50, 75)
          .pause(1000)
          .getWindowDimensions().should.eventually.deep.equal({
            x: 100,
            y: 200,
            width: 50,
            height: 75
          })
      })
    })
  })
})
<commit_msg>:art:<commit_after>var helpers = require('./global-setup')
var path = require('path')

var describe = global.describe
var it = global.it
var before = global.before
var after = global.after

describe('window commands', function () {
  helpers.setupTimeout(this)

  var app = null

  before(function () {
    return helpers.startApplication({
      args: [path.join(__dirname, 'fixtures', 'app')]
    }).then(function (startedApp) { app = startedApp })
  })

  after(function () {
    return helpers.stopApplication(app)
  })

  describe('getWindowCount', function () {
    it('retrieves the window count', function () {
      return app.client.getWindowCount().should.eventually.equal(1)
    })
  })

  describe('getWindowBounds', function () {
    it('gets the window bounds', function () {
      return app.client.getWindowBounds().should.eventually.deep.equal({
        x: 25,
        y: 35,
        width: 200,
        height: 100
      })
    })
  })

  describe('getWindowWidth', function () {
    it('gets the window width', function () {
      return app.client.getWindowWidth().should.eventually.equal(200)
    })
  })

  describe('getWindowHeight', function () {
    it('gets the window height', function () {
      return app.client.getWindowHeight().should.eventually.equal(100)
    })
  })

  describe('setWindowBounds', function () {
    it('sets the window bounds', function () {
      return app.client
        .setWindowBounds({
          x: 100,
          y: 200,
          width: 50,
          height: 75
        })
        .pause(1000)
        .getWindowBounds().should.eventually.deep.equal({
          x: 100,
          y: 200,
          width: 50,
          height: 75
        })
    })
  })

  describe('isWindowFocused()', function () {
    it('returns true when the current window is focused', function () {
      return app.client.isWindowFocused().should.eventually.be.true
    })
  })

  describe('isWindowVisible()', function () {
    it('returns true when the window is visible, false otherwise', function () {
      return app.client
        .hideWindow()
        .isWindowVisible().should.eventually.be.false
        .showWindow()
        .isWindowVisible().should.eventually.be.true
    })
  })

  describe('isWindowDevToolsOpened()', function () {
    it('returns false when the dev tools are closed', function () {
      return app.client.isWindowDevToolsOpened().should.eventually.be.false
    })
  })

  describe('isWindowFullScreen()', function () {
    it('returns false when the window is not in full screen mode', function () {
      return app.client.isWindowFullScreen().should.eventually.be.false
    })
  })

  describe('waitUntilWindowLoaded()', function () {
    it('waits until the current window is loaded', function () {
      return app.client.waitUntilWindowLoaded()
        .isWindowLoading().should.eventually.be.false
    })
  })

  describe('isWindowMaximized()', function () {
    it('returns true when the window is maximized, false otherwise', function () {
      return app.client.isWindowMaximized().should.eventually.be.false
        .maximizeWindow().waitUntil(function () {
          // FIXME window maximized state is never true on CI
          if (process.env.CI) return Promise.resolve(true)

          return this.isWindowMaximized()
        }, 5000).then(function () { })
    })
  })

  describe('isWindowMinimized()', function () {
    it('returns true when the window is minimized, false otherwise', function () {
      return app.client.isWindowMinimized().should.eventually.be.false
        .minimizeWindow().waitUntil(function () {
          // FIXME window minimized state is never true on CI
          if (process.env.CI) return Promise.resolve(true)

          return this.isWindowMinimized()
        }, 5000).then(function () { })
    })
  })

  describe('selectAll()', function () {
    it('selects all the text on the page', function () {
      return app.client.selectAll()
        .getSelectedText().should.eventually.contain('Hello')
    })
  })

  describe('paste()', function () {
    it('pastes the text into the focused element', function () {
      return app.client
        .getText('textarea').should.eventually.equal('')
        .setClipboardText('pasta')
        .getClipboardText().should.eventually.equal('pasta')
        .click('textarea')
        .paste()
        .waitForValue('textarea', 5000)
        .getValue('textarea').should.eventually.equal('pasta')
    })
  })

  describe('isDocumentEdited', function () {
    it('returns true when the document is edited', function () {
      if (process.platform !== 'darwin') return

      return app.client
        .isDocumentEdited().should.eventually.be.false
        .setDocumentEdited(true)
        .isDocumentEdited().should.eventually.be.true
    })
  })

  describe('getRepresentedFilename', function () {
    it('returns the represented filename', function () {
      if (process.platform !== 'darwin') return

      return app.client
        .getRepresentedFilename().should.eventually.equal('')
        .setRepresentedFilename('/foo.js')
        .getRepresentedFilename().should.eventually.equal('/foo.js')
    })
  })

  describe('deprecated APIs', function () {
    describe('setWindowDimensions', function () {
      it('sets the bounds of the window', function () {
        return app.client
          .setWindowDimensions(100, 200, 50, 75)
          .pause(1000)
          .getWindowDimensions().should.eventually.deep.equal({
            x: 100,
            y: 200,
            width: 50,
            height: 75
          })
      })
    })
  })
})
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
var session = require('express-session');
var config = require('./config');
var fixtures = require('./fixtures');
var Db2Store = require('..')(session);

describe('Db2Store constructor', function () {
    it('Throws when called as a function', function () {
        assert.throws(function () {
            Db2Store(config);
        }, /Cannot call Db2Store constructor as a function/);
    });
});

describe('Session interface', function () {
    var sessionStore = new Db2Store(config);
    var session = fixtures.sessions[0];

    before(function (done) {
        sessionStore.createDatabaseTable(function (err) {
            if (err) throw err;
            done();
        });
    });

    after(function (done) {
        sessionStore.dropDatabaseTable(function (err) {
            if (err) throw err;
            sessionStore.close(function (err) {
                if (err) throw err;
                assert(!sessionStore._client.connected);
                done();
            });
        });
    });

    it('has database table', function (done) {
        sessionStore.hasDatabaseTable(function (err, result) {
            assert(!err);
            assert(result);
            done();
        });
    });

    it('sets session', function (done) {
        sessionStore.set(session.session_id, session.data, function (err) {
            assert(!err);
            done();
        });
    });

    it('sets session, updates existing session', function (done) {
        sessionStore.set(session.session_id, session.data, function (err) {
            assert(!err);
            done();
        });
    });

    it('gets session', function (done) {
        sessionStore.get(session.session_id, function (err, data) {
            assert(!err);
            assert(data, 'Data should be returned');
            assert.deepStrictEqual(data, session.data);
            done();
        });
    });

    it('length gets total session count', function (done) {
        sessionStore.length(function (err, length) {
            assert(!err);
            assert.equal(length, 1);
            done();
        });
    });

    it('touch updates session expiration', function (done) {
        sessionStore.touch(session.session_id, session, function (err) {
            assert(!err);
            done();
        });
    });

    it('destroy session deletes session', function (done) {
        sessionStore.destroy(session.session_id, function (err) {
            assert(!err);
            sessionStore.get(session.session_id, function (err, data) {
                assert(!err);
                assert(!data);
                done();
            });
        });
    });

    it('clear clears all sessions', function (done) {
        sessionStore.set(session.session_id, session.data, function (err) {
            assert(!err);

            sessionStore.clear(function (err) {
                assert(!err);

                sessionStore.length(function (err, length) {
                    assert(!err);
                    assert.equal(length, 0);
                    done();
                });
            });
        });

    });
});<commit_msg>Added test case.<commit_after>'use strict';

var assert = require('assert');
var session = require('express-session');
var config = require('./config');
var fixtures = require('./fixtures');
var Db2Store = require('..')(session);

describe('Db2Store constructor', function () {
    it('errors when called as a function', function () {
        assert.throws(function () {
            Db2Store(config);
        }, /Cannot call Db2Store constructor as a function/);
    });

    it('uses supplied connection', function () {
        var connection = {
            connected: true,
            dummy: true
        };
        var sessionStore = new Db2Store(config, connection);

        assert.deepStrictEqual(sessionStore._client, connection);
    });
});

describe('Session interface', function () {
    var sessionStore = new Db2Store(config);
    var session = fixtures.sessions[0];

    before(function (done) {
        sessionStore.createDatabaseTable(function (err) {
            if (err) throw err;
            done();
        });
    });

    after(function (done) {
        sessionStore.dropDatabaseTable(function (err) {
            if (err) throw err;
            sessionStore.close(function (err) {
                if (err) throw err;
                assert(!sessionStore._client.connected);
                done();
            });
        });
    });

    it('has database table', function (done) {
        sessionStore.hasDatabaseTable(function (err, result) {
            assert(!err);
            assert(result);
            done();
        });
    });

    it('sets session', function (done) {
        sessionStore.set(session.session_id, session.data, function (err) {
            assert(!err);
            done();
        });
    });

    it('sets session, updates existing session', function (done) {
        sessionStore.set(session.session_id, session.data, function (err) {
            assert(!err);
            done();
        });
    });

    it('gets session', function (done) {
        sessionStore.get(session.session_id, function (err, data) {
            assert(!err);
            assert(data, 'Data should be returned');
            assert.deepStrictEqual(data, session.data);
            done();
        });
    });

    it('length gets total session count', function (done) {
        sessionStore.length(function (err, length) {
            assert(!err);
            assert.equal(length, 1);
            done();
        });
    });

    it('touch updates session expiration', function (done) {
        sessionStore.touch(session.session_id, session, function (err) {
            assert(!err);
            done();
        });
    });

    it('destroy session deletes session', function (done) {
        sessionStore.destroy(session.session_id, function (err) {
            assert(!err);
            sessionStore.get(session.session_id, function (err, data) {
                assert(!err);
                assert(!data);
                done();
            });
        });
    });

    it('clear clears all sessions', function (done) {
        sessionStore.set(session.session_id, session.data, function (err) {
            assert(!err);

            sessionStore.clear(function (err) {
                assert(!err);

                sessionStore.length(function (err, length) {
                    assert(!err);
                    assert.equal(length, 0);
                    done();
                });
            });
        });

    });
});<|endoftext|>