<commit_before>'use strict';

var fs          = require('fs'),
    tryCatch    = require('try-catch');

module.exports = function(name, json, options, callback) {
    if (!callback) {
        callback = options;
        options = {};
    }

    check(name, json, options);
    checkCB(callback);

    var str,
        error = tryCatch(function() {
            str = stringify(json, options);
        });

    if (error)
        callback(error);
    else
        fs.writeFile(name, str, callback);
};

module.exports.sync = sync;

function sync(name, data, options) {
    options = options || {};

    check(name, data, options);
    fs.writeFileSync(name, stringify(data, options));
}

module.exports.sync.try = function(name, data, options) {
    options = options || {};
    check(name, data, options);

    var error = tryCatch(function() {
        sync(name, data, options);
    });

    return error;
};

function defaultOptions(options) {
    if (typeof options.space === 'undefined')
        options.space = 4;

    if (typeof options.eof === 'undefined')
        options.eof = true;

    return options;
}

function stringify(data, options) {
    var result;

    defaultOptions(options);

    result = JSON.stringify(data, options.replacer, options.space);

    if (options.eof)
        result += '\n';

    return result;
}

function check(name, json, options) {
    if (typeof name !== 'string')
        throw Error('name should be string!');

    if (typeof json !== 'object')
        throw Error('json should be object!');

    if (typeof options !== 'object')
        throw Error('options should be object!');
}

function checkCB(callback) {
    if (typeof callback !== 'function')
        throw Error('callback should be function!');
}

<commit_msg>feature(writejson) rm extra tryCatch<commit_after>'use strict';

var fs          = require('fs'),
    tryCatch    = require('try-catch');

module.exports = function(name, json, options, callback) {
    var str;

    if (!callback) {
        callback = options;
        options = {};
    }

    check(name, json, options);
    checkCB(callback);

    str = stringify(json, options);
    fs.writeFile(name, str, callback);
};

module.exports.sync = sync;

function sync(name, data, options) {
    options = options || {};

    check(name, data, options);
    fs.writeFileSync(name, stringify(data, options));
}

module.exports.sync.try = function(name, data, options) {
    options = options || {};
    check(name, data, options);

    var error = tryCatch(function() {
        sync(name, data, options);
    });

    return error;
};

function defaultOptions(options) {
    if (typeof options.space === 'undefined')
        options.space = 4;

    if (typeof options.eof === 'undefined')
        options.eof = true;

    return options;
}

function stringify(data, options) {
    var result;

    defaultOptions(options);

    result = JSON.stringify(data, options.replacer, options.space);

    if (options.eof)
        result += '\n';

    return result;
}

function check(name, json, options) {
    if (typeof name !== 'string')
        throw Error('name should be string!');

    if (typeof json !== 'object')
        throw Error('json should be object!');

    if (typeof options !== 'object')
        throw Error('options should be object!');
}

function checkCB(callback) {
    if (typeof callback !== 'function')
        throw Error('callback should be function!');
}

<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;
var util = require('util');
var request;
if (process.title === 'browser')
    request = require('browser-request');
else {
    var requestPath = 'request';
    request = require(requestPath);
}
var ltx = require('ltx');

function BOSHConnection(opts) {
    var that = this;
    EventEmitter.call(this);

    this.boshURL = opts.boshURL;
    this.jid = opts.jid;
    this.xmlnsAttrs = {
	xmlns: "http://jabber.org/protocol/httpbind",
	'xmlns:xmpp': "urn:xmpp:xbosh",
	'xmlns:stream': "http://etherx.jabber.org/streams"
    };
    if (opts.xmlns)
	for(var prefix in opts.xmlns)
	    if (prefix)
		this.xmlnsAttrs["xmlns:" + prefix] = opts.xmlns[prefix];
	    else
		this.xmlnsAttrs["xmlns"] = opts.xmlns[prefix];
    this.currentRequests = 0;
    this.queue = [];
    this.rid = Math.ceil(Math.random() * 9999999999);

    this.request({
	to: this.jid.domain,
	ver: "1.6",
	wait: "10",
	hold: "1",
	content: this.contentType
    }, [], function(err, bodyEl) {
	if (err) {
	    that.emit('error', err);
	} else if (bodyEl && bodyEl.attrs) {
	    that.sid = bodyEl.attrs.sid;
	    that.maxRequests = parseInt(bodyEl.attrs.requests, 10) || 2;
	    that.emit('connect');
	    that.processResponse(bodyEl);
	    process.nextTick(that.mayRequest.bind(that));
	}
    });
}
util.inherits(BOSHConnection, EventEmitter);
exports.BOSHConnection = BOSHConnection;

BOSHConnection.prototype.contentType = "text/xml; charset=utf-8";

BOSHConnection.prototype.send = function(stanza) {
    this.queue.push({ stanza: stanza.root() });
    this.mayRequest();
};

BOSHConnection.prototype.processResponse = function(bodyEl) {
    if (bodyEl && bodyEl.children) {
	for(var i = 0; i < bodyEl.children.length; i++) {
	    var child = bodyEl.children[i];
	    if (child.name && child.attrs && child.children)
		this.emit('stanza', child);
	}
    }
};

BOSHConnection.prototype.mayRequest = function() {
    var that = this;
    var canRequest =
	this.currentRequests === 0 ||
	(this.queue.length > 0 && this.currentRequests < this.maxRequests);
    if (!canRequest)
	return;

    var stanzas = this.queue.map(function(queued) {
	return queued.stanza;
    });
    this.queue = [];
    this.request({}, stanzas, function(err, bodyEl) {
	if (!err && bodyEl)
	    that.processResponse(bodyEl);

	process.nextTick(that.mayRequest.bind(that));
    });
};

BOSHConnection.prototype.end = function(stanzas) {
    var that = this;
    stanzas = stanzas || [];
    if (typeof stanzas !== 'array')
	stanzas = [stanzas];
    this.request({ type: 'terminate' }, stanzas, function(err, bodyEl) {
	if (bodyEl)
	    that.processResponse(bodyEl);
	that.emit('end');
	delete that.sid;
    });
};

BOSHConnection.prototype.request = function(attrs, children, cb) {
    var that = this;

    attrs.rid = this.rid.toString();
    this.rid++;
    if (this.sid)
	attrs.sid = this.sid;

    for(var k in this.xmlnsAttrs)
	attrs[k] = this.xmlnsAttrs[k];
    var boshEl = new ltx.Element('body', attrs);
    for(var i = 0; i < children.length; i++)
	boshEl.cnode(children[i]);

    this.currentRequests++;
    request({
	uri: this.boshURL,
	method: 'POST',
	headers: {
	    "Content-Type": this.contentType
	},
	body: boshEl.toString()
    }, function(err, res, body) {
	that.currentRequests--;

	if (err)
	    return cb(err);
	if (res.statusCode < 200 || res.statusCode >= 400)
	    return cb(new Error("HTTP status " + res.statusCode));

	var bodyEl;
	try {
	    bodyEl = ltx.parse(body);
	} catch(e) {
	    return cb(e);
	}

	if (bodyEl && bodyEl.attrs.type === 'terminate')
	    cb(new Error(bodyEl.attrs.condition));
	else if (bodyEl)
	    cb(null, bodyEl);
	else
	    cb(new Error('no <body/>'));
    });
};
<commit_msg>bosh: check for sid<commit_after>var EventEmitter = require('events').EventEmitter;
var util = require('util');
var request;
if (process.title === 'browser')
    request = require('browser-request');
else {
    var requestPath = 'request';
    request = require(requestPath);
}
var ltx = require('ltx');

function BOSHConnection(opts) {
    var that = this;
    EventEmitter.call(this);

    this.boshURL = opts.boshURL;
    this.jid = opts.jid;
    this.xmlnsAttrs = {
	xmlns: "http://jabber.org/protocol/httpbind",
	'xmlns:xmpp': "urn:xmpp:xbosh",
	'xmlns:stream': "http://etherx.jabber.org/streams"
    };
    if (opts.xmlns)
	for(var prefix in opts.xmlns)
	    if (prefix)
		this.xmlnsAttrs["xmlns:" + prefix] = opts.xmlns[prefix];
	    else
		this.xmlnsAttrs["xmlns"] = opts.xmlns[prefix];
    this.currentRequests = 0;
    this.queue = [];
    this.rid = Math.ceil(Math.random() * 9999999999);

    this.request({
	to: this.jid.domain,
	ver: "1.6",
	wait: "10",
	hold: "1",
	content: this.contentType
    }, [], function(err, bodyEl) {
	if (err) {
	    that.emit('error', err);
	} else if (bodyEl && bodyEl.attrs) {
	    that.sid = bodyEl.attrs.sid;
	    that.maxRequests = parseInt(bodyEl.attrs.requests, 10) || 2;
	    if (that.sid && that.maxRequests > 0) {
		that.emit('connect');
		that.processResponse(bodyEl);
		process.nextTick(that.mayRequest.bind(that));
	    } else
		that.emit('error', "Invalid parameters");
	}
    });
}
util.inherits(BOSHConnection, EventEmitter);
exports.BOSHConnection = BOSHConnection;

BOSHConnection.prototype.contentType = "text/xml; charset=utf-8";

BOSHConnection.prototype.send = function(stanza) {
    this.queue.push({ stanza: stanza.root() });
    this.mayRequest();
};

BOSHConnection.prototype.processResponse = function(bodyEl) {
    if (bodyEl && bodyEl.children) {
	for(var i = 0; i < bodyEl.children.length; i++) {
	    var child = bodyEl.children[i];
	    if (child.name && child.attrs && child.children)
		this.emit('stanza', child);
	}
    }
    if (bodyEl && bodyEl.attrs.type === 'terminate') {
	this.emit('error', new Error(bodyEl.attrs.condition || "Session terminated"));
	this.emit('close');
    }
};

BOSHConnection.prototype.mayRequest = function() {
    var that = this;
    var canRequest =
	/* Must have a session already */
	this.sid &&
	/* We can only receive when one request is in flight */
	(this.currentRequests === 0 ||
	 /* Is there something to send, and are we allowed? */
	 ((this.queue.length > 0 && this.currentRequests < this.maxRequests))
	);
    if (!canRequest)
	return;

    var stanzas = this.queue.map(function(queued) {
	return queued.stanza;
    });
    this.queue = [];
    this.request({}, stanzas, function(err, bodyEl) {
	if (!err && bodyEl)
	    that.processResponse(bodyEl);

	process.nextTick(that.mayRequest.bind(that));
    });
};

BOSHConnection.prototype.end = function(stanzas) {
    var that = this;
    stanzas = stanzas || [];
    if (typeof stanzas !== 'array')
	stanzas = [stanzas];
    this.request({ type: 'terminate' }, stanzas, function(err, bodyEl) {
	if (bodyEl)
	    that.processResponse(bodyEl);
	that.emit('end');
	delete that.sid;
    });
};

BOSHConnection.prototype.request = function(attrs, children, cb) {
    var that = this;

    attrs.rid = this.rid.toString();
    this.rid++;
    if (this.sid)
	attrs.sid = this.sid;

    for(var k in this.xmlnsAttrs)
	attrs[k] = this.xmlnsAttrs[k];
    var boshEl = new ltx.Element('body', attrs);
    for(var i = 0; i < children.length; i++)
	boshEl.cnode(children[i]);

    this.currentRequests++;
    request({
	uri: this.boshURL,
	method: 'POST',
	headers: {
	    "Content-Type": this.contentType
	},
	body: boshEl.toString()
    }, function(err, res, body) {
	that.currentRequests--;

	if (err)
	    return cb(err);
	if (res.statusCode < 200 || res.statusCode >= 400)
	    return cb(new Error("HTTP status " + res.statusCode));

	var bodyEl;
	try {
	    bodyEl = ltx.parse(body);
	} catch(e) {
	    return cb(e);
	}

	if (bodyEl && bodyEl.attrs.type === 'terminate')
	    cb(new Error(bodyEl.attrs.condition));
	else if (bodyEl)
	    cb(null, bodyEl);
	else
	    cb(new Error('no <body/>'));
    });
};
<|endoftext|>


<commit_before>'use strict';

const builder = require('botbuilder');

const sendmail = require('../services/sendmail');
const secrets = require('../services/secrets');
const auth = require('../services/auth');

const lib = new builder.Library('signin');

const find = builder.EntityRecognizer.findEntity;

lib.dialog('/', [
        (session, args, next) => {

            const {
                name
            } = session.message.user;
            const {
                entities
            } = args.intent;

            const usernameOrEmail = find(entities, 'username') || find(entities, 'email');
            if (usernameOrEmail) {
                next({
                    response: usernameOrEmail
                });
            } else {
                builder.Prompts.text(session, `What's your domain username or office email address, ${name}?`);
            }
        },

        (session, results, next) => {
            const usernameOrEmail = session.dialogData.usernameOrEmail = results.response;
            session.sendTyping();

            auth
                .authenticate(usernameOrEmail)
                .then((response) => {
                    session.dialogData.profile = response.profile;
                    session.dialogData.jira = response.instances;
                    next();
                }).catch((ex) => {
                    const {
                        statusCode
                    } = ex;

                    switch (statusCode) {
                        case 404:
                            session.endDialog(`Looks like you are not in seranet. Talk to IT Services to see what's going on.`);
                            break;
                        default:
                            session.endDialog(`Oops! Something went wrong. Shame on us (facepalm). Let's start over.`);
                            break;
                    }
                });
        },

        (session, results, next) => {

            const {
                name
            } = session.message.user;
            const email = session.dialogData.profile.emailAddress;
            const secretCode = session.dialogData.secretCode = secrets.whisper();

            const draft = {
                to: `${name} <${email}>`,
                subject: `Your Secret Code: ${secretCode}`,
                text: `You just tryed to sign in with JIRA Journal. Here's your Secret Code: ${secretCode}`,
                html: `You just tryed to sign in with JIRA Journal. Here's your <b>Secret Code: ${secretCode}</b>`
            };

            session.sendTyping();

            sendmail.compose(draft)
                .then(() => {
                    session.send(`Ok. I dropped you a mail to ${email}.`);
                    next();
                }).catch((ex) => {
                    session.send(`Oops! Something went wrong with the email. Shame on us (facepalm). Let's start over.`);
                    session.replaceDialog('/signin', session.dialogData);
                });

        },
        (session) => {

            builder.Prompts.text(session, `What's the *secret code* in it?`);

        },
        (session, results, next) => {

            const {
                secretCode
            } = session.privateConversationData;
            const confirmCode = results.response;

            if (confirmCode !== secretCode) {
                session.send(`That's not the Secret Code I sent you (wonder). Let's start over.`);
                return session.replaceDialog('/signin');
            }

            next();

        },
        (session) => {

            const {
                jira
            } = session.privateConversationData;

            session.userData = session.privateConversationData;

            if (jira.length == 0) {
                return session.endDialog('(y)');
            }

            const jiraCards = jira.map((entity) => {
                return new builder.HeroCard(session)
                    .title(entity.account)
                    .subtitle(entity.description)
                    .buttons([
                        builder.CardAction.openUrl(session, entity.url, 'Learn More')
                    ])
            });
            const message = new builder.Message(session).attachmentLayout(builder.AttachmentLayout.carousel).attachments(jiraCards);
            session.endDialog(message);
        }
    ])
    .triggerAction({
        matches: ['/signin']
    })
    .cancelAction('/signin-cancel', '(y)', {
        matches: [/^(cancel|nevermind)$/g]
    });

module.exports = exports = {
    createNew: () => {
        return lib.clone();
    }
};<commit_msg>#10 find username or builtin email type from recognizer.<commit_after>'use strict';

const builder = require('botbuilder');

const sendmail = require('../services/sendmail');
const secrets = require('../services/secrets');
const auth = require('../services/auth');

const lib = new builder.Library('signin');

const find = (...args) => {
    const el = builder.EntityRecognizer.findEntity.call(this, ...args);
    return el ? el.entity : null;
};

lib.dialog('/', [
        (session, args, next) => {

            const {
                name
            } = session.message.user;
            const {
                entities
            } = args.intent;

            const usernameOrEmail = find.call(this, ...[entities, 'username']) || find.call(this, ...[entities, 'builtin.email']);

            if (usernameOrEmail) {
                next({
                    response: usernameOrEmail
                });
            } else {
                builder.Prompts.text(session, `What's your domain username or office email address, ${name}?`);
            }
        },

        (session, results, next) => {
            const usernameOrEmail = session.dialogData.usernameOrEmail = results.response;
            session.sendTyping();

            auth
                .authenticate(usernameOrEmail)
                .then((response) => {
                    session.dialogData.profile = response.profile;
                    session.dialogData.jira = response.instances;
                    next();
                }).catch((ex) => {
                    const {
                        statusCode
                    } = ex;

                    switch (statusCode) {
                        case 404:
                            session.endDialog(`Looks like you are not in seranet. Talk to IT Services to see what's going on.`);
                            break;
                        default:
                            session.endDialog(`Oops! Something went wrong. Shame on us (facepalm). Let's start over.`);
                            break;
                    }
                });
        },

        (session, results, next) => {

            const {
                name
            } = session.message.user;
            const email = session.dialogData.profile.emailAddress;
            const secretCode = session.dialogData.secretCode = secrets.whisper();

            const draft = {
                to: `${name} <${email}>`,
                subject: `Your Secret Code: ${secretCode}`,
                text: `You just tryed to sign in with JIRA Journal. Here's your Secret Code: ${secretCode}`,
                html: `You just tryed to sign in with JIRA Journal. Here's your <b>Secret Code: ${secretCode}</b>`
            };

            session.sendTyping();

            sendmail.compose(draft)
                .then(() => {
                    session.send(`Ok. I dropped you a mail to ${email}.`);
                    next();
                }).catch((ex) => {
                    session.send(`Oops! Something went wrong with the email. Shame on us (facepalm). Let's start over.`);
                    session.replaceDialog('/signin', session.dialogData);
                });

        },
        (session) => {

            builder.Prompts.text(session, `What's the *secret code* in it?`);

        },
        (session, results, next) => {

            const {
                secretCode
            } = session.dialogData;
            const confirmCode = results.response;

            if (confirmCode !== secretCode) {
                session.send(`That's not the Secret Code I sent you (wonder). Let's start over.`);
                return session.replaceDialog('/signin');
            }

            next();

        },
        (session) => {

            const {
                jira
            } = session.dialogData;

            session.userData = session.dialogData;

            if (jira.length == 0) {
                return session.endDialog('(y)');
            }

            const jiraCards = jira.map((entity) => {
                return new builder.HeroCard(session)
                    .title(entity.account)
                    .subtitle(entity.description)
                    .buttons([
                        builder.CardAction.openUrl(session, entity.url, 'Learn More')
                    ])
            });
            const message = new builder.Message(session).attachmentLayout(builder.AttachmentLayout.carousel).attachments(jiraCards);
            session.endDialog(message);
        }
    ])
    .triggerAction({
        matches: ['/signin']
    })
    .cancelAction('/signin-cancel', '(y)', {
        matches: [/^(cancel|nevermind)$/g]
    });

module.exports = exports = {
    createNew: () => {
        return lib.clone();
    }
};<|endoftext|>


<commit_before>import Ember from 'ember';
import ENV from '../config/environment';

export default Ember.Controller.extend({
  posList: ENV.posList,
  application: Ember.inject.controller("application"),
  currentUser: Ember.computed.alias('application.currentUser'),
  justVoted: false,
  invalidEdit: false,
  isLoading: false,
  isOpen: Ember.computed("model.state", function() {
    return (this.get("model.state") === "pending");
  }),
  isMine: Ember.computed("model.user.id", "currentUser.id", function() {
    return (this.get("model.user.id") === this.get("currentUser.id"));
  }),
  canChange: Ember.computed("isOpen", "isMine", function() {
    return (this.get("isOpen") && this.get("isMine"));
  }),
  isDeletion: Ember.computed("model.changes", function() {
    // This is a function to test whether all the changes are remove
    // meanings. We create an array, push each change type to it,
    // then remove all that are "removes". If there's nothing left,
    // we know it's a total meaning removal.
    var actions = [];
    this.get("model.changes.meanings.[]").forEach( function(meaning) {
      actions.push(meaning.action);
    });
    actions = actions.without("remove");
    return Ember.isEmpty(actions);
  }),
  actions: {
    startEdit() {
      this.set("isEditing", true);
    },
    submitEdit() {
      var _this = this;
      this.tracker.log("proposal", "edit");
      this.set("isLoading", true);
      this.get("model").save().then(
        function() {
          _this.set("isEditing", false);
          _this.set("isLoading", false);
        },
        function() {
          _this.set("isLoading", false);
          _this.set("isEditing", false);
        }
      );
    },
    withdraw() {
      var _this = this;
      this.set("isLoading", true);
      Ember.$.post(ENV.api + "/proposals/" + this.model.get("id") + "/withdraw",
      {}, function(data) {
        _this.store.pushPayload('proposal', data);
        _this.tracker.log("proposal", "withdraw");
        _this.set("isLoading", false);
      });
    },
    cancelEdit() {
      this.get("model").reload();
      this.set("isEditing", false);
    },
  }
});
<commit_msg>if an edit fails, reshow edit interface<commit_after>import Ember from 'ember';
import ENV from '../config/environment';

export default Ember.Controller.extend({
  posList: ENV.posList,
  application: Ember.inject.controller("application"),
  currentUser: Ember.computed.alias('application.currentUser'),
  justVoted: false,
  invalidEdit: false,
  isLoading: false,
  isOpen: Ember.computed("model.state", function() {
    return (this.get("model.state") === "pending");
  }),
  isMine: Ember.computed("model.user.id", "currentUser.id", function() {
    return (this.get("model.user.id") === this.get("currentUser.id"));
  }),
  canChange: Ember.computed("isOpen", "isMine", function() {
    return (this.get("isOpen") && this.get("isMine"));
  }),
  isDeletion: Ember.computed("model.changes", function() {
    // This is a function to test whether all the changes are remove
    // meanings. We create an array, push each change type to it,
    // then remove all that are "removes". If there's nothing left,
    // we know it's a total meaning removal.
    var actions = [];
    this.get("model.changes.meanings.[]").forEach( function(meaning) {
      actions.push(meaning.action);
    });
    actions = actions.without("remove");
    return Ember.isEmpty(actions);
  }),
  actions: {
    startEdit() {
      this.set("isEditing", true);
    },
    submitEdit() {
      var _this = this;
      this.tracker.log("proposal", "edit");
      this.set("isLoading", true);
      this.get("model").save().then(
        function() {
          _this.set("isEditing", false);
          _this.set("isLoading", false);
        },
        function() {
          _this.set("isLoading", false);
          _this.set("isEditing", true);
        }
      );
    },
    withdraw() {
      var _this = this;
      this.set("isLoading", true);
      Ember.$.post(ENV.api + "/proposals/" + this.model.get("id") + "/withdraw",
      {}, function(data) {
        _this.store.pushPayload('proposal', data);
        _this.tracker.log("proposal", "withdraw");
        _this.set("isLoading", false);
      });
    },
    cancelEdit() {
      this.get("model").reload();
      this.set("isEditing", false);
    },
  }
});
<|endoftext|>


<commit_before>
import moment from 'moment';

import Sinister from "../models/sinister";
import SinisterGeneral from "../models/sinisterGeneral";
import SinisterGeneralDocumentation from "../models/sinisterGeneralDocumentation";
import SinisterCar from "../models/sinisterCar";

import Ramo from "../models/ramo";
import Policy from "../models/policy";

import JSZip from 'jszip';
import Docxtemplater from 'docxtemplater';
import excelbuilder from 'msexcel-builder';
import fs from 'fs';
import path from 'path';

const pathRender = `download`;
const pathDownload = `./public/${pathRender}`;

if (!fs.existsSync(pathDownload)){
    fs.mkdirSync(pathDownload);
}

let sinisterController = function (app, control={auth, passport, acl}){

   function controller (req, res, next) {
      req.controller = "sinister";
      return next();
   }

   function findAction (callback){
      Sinister.find({}, function (err, docs) {
         if (!err) {

            Ramo.populate(docs, {path: "ramo"},function(err, docs){
               callback(docs);
            });
         }
      });
   }

   app.get('/sinister/filter',[control.auth, controller], (req, res) => {
      let $filter =  global.filter(req.query.filter);
      Sinister.find($filter, function (err, docs) {
         if (typeof docs !== 'undefined') {
            control.log(req.route.path, req.user);

            Ramo.populate(docs, {path: "ramo"},function(err, docs){
               res.send({msg: "OK", sinisters: docs});
            });

         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.get('/sinister/list', [control.auth, controller, control.acl], (req, res) => {

      let typeList = app.locals.typeList;
      let filter = {};
      if(typeList=="99097f2c1f"){
         filter = {"userCreate": req.user.idUser};
      } else if(typeList=="99097f2c1c"){
         filter = {"branchCreate": req.user.idBranch};
      } else {
         filter = {};
      }

      Sinister.find(filter, function (err, docs) {
         if (typeof docs !== 'undefined') {
            control.log(req.route.path, req.user);
            Policy.populate(docs, {path: "policy"},function(err, docs){
                res.send({msg: "OK", sinisters: docs});
             });

         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.get('/sinister/view/:id', [control.auth, controller, control.acl], (req, res) => {

      Sinister.findById(req.params.id, function (err, doc) {
         if (!err) {
            control.log(req.route.path, req.user);
            res.send({msg: "OK", sinister: doc});
         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.post('/sinister/add', [control.auth, controller, control.acl], (req, res) => {

      let $data = req.body.sinister;
      let $sinisterData = $data;
      let $sinisterGeneral = $data.item;
      let $sinisterGeneralDocumentation = $data.item.items;
      let $moment = moment();
      delete($sinisterData.item);
      delete($sinisterGeneralDocumentation.items);
      $sinisterData["dateCreate"] = $moment;
      $sinisterData["userCreate"] = req.user.idUser;
      $sinisterData["branchCreate"] = req.user.idBranch;
      $sinisterData["dateUpdate"] = $moment;
      $sinisterData["userUpdate"] = req.user.idUser;
      let sinister = new Sinister($sinisterData);

      sinister.save((err, doc) => {
         if(!err){
            control.log(req.route.path, req.user);
            $sinisterGeneral["idSinister"] = doc._id;
            $sinisterGeneral["sinister"] = doc._id;
            $sinisterGeneral["dateCreate"] = $moment;
            $sinisterGeneral["userCreate"] = req.user.idUser;
            $sinisterGeneral["dateUpdate"] = $moment;
            $sinisterGeneral["userUpdate"] = req.user.idUser;
            let sinisterGeneral = new SinisterCar($sinisterGeneral);
            sinisterGeneral.save((err, doc) => {
               if(!err){
                  $sinisterGeneralDocumentation.forEach(function (item, index) {
                     $sinisterGeneralDocumentation[index]["idSinisterGeneral"]=doc._id;
                     $sinisterGeneralDocumentation[index]["sinisterGeneral"]=doc._id;
                     $sinisterGeneralDocumentation[index]["dateCreate"] = $moment;
                     $sinisterGeneralDocumentation[index]["userCreate"] = req.user.idUser;
                     $sinisterGeneralDocumentation[index]["dateUpdate"] = $moment;
                     $sinisterGeneralDocumentation[index]["userUpdate"] = req.user.idUser;
                  })
                  let sinisterGeneralDocumentation = new SinisterGeneralDocumentation();
                  sinisterGeneralDocumentation.insertMany($sinisterGeneralDocumentation, (err, docs) => {
                  });
               }
            });
            findAction(function(docs){
               res.send({msg: "OK", update: docs});
            });
         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.post('/sinister/edit/:id', [control.auth, controller, control.acl], (req, res) => {

      let filter = {
         _id: req.params.id
      }

      let update = {
         idPolicy: req.body.idPolicy,
         policyData: req.body.policyData,
         idPolicyAnnex: req.body.idPolicyAnnex,
         annexData: req.body.annexData,
         idClient: req.body.idClient,
         clientData: req.body.clientData,
         compName: req.body.compName,
         clientInsured: req.body.clientInsured,
         beneficiary: req.body.beneficiary,
         dateSinester: req.body.dateSinester,
         dateNotification: req.body.dateNotification,
         trackingDate: req.body.trackingDate,
         beneficiary: req.body.beneficiary,
         idRamo: req.body.idRamo,
         ramo: req.body.idRamo,
         sinisterState: req.body.sinisterState,
         settlementDate: req.body.settlementDate,
         approvalDate: req.body.approvalDate,
         checkApproved: req.body.checkApproved,
         dateUpdate: moment(),
         userUpdate: req.user.idUser
      };

      Sinister.findOneAndUpdate(filter, update, function (err, doc) {
         if (!err) {
            findAction(function(docs){
               control.log(req.route.path, req.user);
               res.send({msg: "OK", update: docs});
            });
         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.delete('/sinister/delete/:id', [control.auth, controller, control.acl], (req, res) => {

      let filter = {
         _id: req.params.id
      }

      Sinister.findByIdAndRemove(filter, function (err, doc) {
         if(!err){
            findAction(function(docs){
               control.log(req.route.path, req.user);
               res.send({msg: "OK", update: docs});
            });
         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.post('/sinister/report', [control.auth, controller, control.acl], (req, res) => {

      let $filter =  global.filter(req.body.filter);
      Sinister.find($filter, function (err, docs) {
         if (typeof docs !== 'undefined') {

         /*Ramo.populate(docs, {path: "ramo"},function(err, docs){
         City.populate(docs, {path: "city"},function(err, docs){
         Branch.populate(docs, {path: "branchCreate"},function(err, docs){
         PolicyType.populate(docs, {path: "policyType"},function(err, docs){*/

            var file = 'sinister.xlsx';
            var outPutFile = moment().format('YYYY-MM-DD-h:mm:ss') + file;
            var pathDownload = __dirname+'/../../public/download/';
            var workbook = excelbuilder.createWorkbook(pathDownload, outPutFile)
            var sheet1 = workbook.createSheet('sheet1', 15, 17);

            var cols = [2,3,4,5,6,7,8,9,10,11,12,13,14,15];
            var rowIni = 2;
            sheet1.set(cols[0], rowIni, 'Agencia');
            sheet1.set(cols[1], rowIni, 'Ciudad');
            sheet1.set(cols[2], rowIni, 'Nombre Cliente');
            sheet1.set(cols[4], rowIni, 'Numero de Poliza');
            sheet1.set(cols[5], rowIni, 'Numero de Siniestro');
            sheet1.set(cols[6], rowIni, 'Nombre Ramo');
            sheet1.set(cols[7], rowIni, 'Fecha de Inicio de Vigencia');
            sheet1.set(cols[8], rowIni, 'Fecha de fin de Vigencia');
            sheet1.set(cols[9], rowIni, 'Fecha de Siniestro');
            sheet1.set(cols[10], rowIni, 'Fecha de Notificacion');

            console.log(docs);
            let $length = docs.length;
            for (var i = 0; i < $length; i++) {
               rowIni++;
               let $cliente = '';
                  if(docs[i].typeRecipient == 'CLIENTE'){
                     $cliente = docs[i].recipient.name+' '+docs[i].recipient.lastName
                  }
               sheet1.set(cols[0], rowIni, docs[i]);
               /*sheet1.set(cols[0], rowIni, docs[i].branchCreate.name);
               sheet1.set(cols[1], rowIni, docs[i].city.name);
               sheet1.set(cols[2], rowIni, $cliente);
               sheet1.set(cols[3], rowIni, docs[i].policyNumber);
               sheet1.set(cols[4], rowIni, docs[i].ramo.name);
               sheet1.set(cols[5], rowIni, docs[i].policyType.name);
               sheet1.set(cols[6], rowIni, docs[i].startDate);
               sheet1.set(cols[7], rowIni, docs[i].finishDate);*/
            }

            workbook.save(function(err1, resp1){
               if (!err1){
                  console.log('congratulations, your workbook created');
                  res.send({msg: "OK", doc_name: outPutFile});
               }
               else{
                  workbook.cancel();
                  res.send({msg: "ERROR", err: err1});
               }
            });

         /*});
         });
         });
         });*/

         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

}

export default sinisterController
<commit_msg>fixed save<commit_after>
import moment from 'moment';

import Sinister from "../models/sinister";
import SinisterGeneral from "../models/sinisterGeneral";
import SinisterGeneralDocumentation from "../models/sinisterGeneralDocumentation";
import SinisterCar from "../models/sinisterCar";

import Ramo from "../models/ramo";
import Policy from "../models/policy";

import JSZip from 'jszip';
import Docxtemplater from 'docxtemplater';
import excelbuilder from 'msexcel-builder';
import fs from 'fs';
import path from 'path';

const pathRender = `download`;
const pathDownload = `./public/${pathRender}`;

if (!fs.existsSync(pathDownload)){
    fs.mkdirSync(pathDownload);
}

let sinisterController = function (app, control={auth, passport, acl}){

   function controller (req, res, next) {
      req.controller = "sinister";
      return next();
   }

   function findAction (callback){
      Sinister.find({}, function (err, docs) {
         if (!err) {

            Ramo.populate(docs, {path: "ramo"},function(err, docs){
               callback(docs);
            });
         }
      });
   }

   app.get('/sinister/filter',[control.auth, controller], (req, res) => {
      let $filter =  global.filter(req.query.filter);
      Sinister.find($filter, function (err, docs) {
         if (typeof docs !== 'undefined') {
            control.log(req.route.path, req.user);

            Ramo.populate(docs, {path: "ramo"},function(err, docs){
               res.send({msg: "OK", sinisters: docs});
            });

         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.get('/sinister/list', [control.auth, controller, control.acl], (req, res) => {

      let typeList = app.locals.typeList;
      let filter = {};
      if(typeList=="99097f2c1f"){
         filter = {"userCreate": req.user.idUser};
      } else if(typeList=="99097f2c1c"){
         filter = {"branchCreate": req.user.idBranch};
      } else {
         filter = {};
      }

      Sinister.find(filter, function (err, docs) {
         if (typeof docs !== 'undefined') {
            control.log(req.route.path, req.user);
            Policy.populate(docs, {path: "policy"},function(err, docs){
                res.send({msg: "OK", sinisters: docs});
             });

         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.get('/sinister/view/:id', [control.auth, controller, control.acl], (req, res) => {

      Sinister.findById(req.params.id, function (err, doc) {
         if (!err) {
            control.log(req.route.path, req.user);
            res.send({msg: "OK", sinister: doc});
         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.post('/sinister/add', [control.auth, controller, control.acl], (req, res) => {

      let $data = req.body.sinister;
      console.log($data);
      let $sinisterData = $data;
      let $sinisterGeneral = $data.item;
      let $sinisterGeneralDocumentation = $data.item.items;
      let $moment = moment();
      delete($sinisterData.item);
      delete($sinisterGeneralDocumentation.items);
      $sinisterData["dateCreate"] = $moment;
      $sinisterData["userCreate"] = req.user.idUser;
      $sinisterData["branchCreate"] = req.user.idBranch;
      $sinisterData["dateUpdate"] = $moment;
      $sinisterData["userUpdate"] = req.user.idUser;
      let sinister = new Sinister($sinisterData);

      sinister.save((err, doc) => {
         if(!err){
            control.log(req.route.path, req.user);
            $sinisterGeneral["idSinister"] = doc._id;
            $sinisterGeneral["sinister"] = doc._id;
            $sinisterGeneral["dateCreate"] = $moment;
            $sinisterGeneral["userCreate"] = req.user.idUser;
            $sinisterGeneral["dateUpdate"] = $moment;
            $sinisterGeneral["userUpdate"] = req.user.idUser;
            let sinisterGeneral = new SinisterGeneral($sinisterGeneral);
            sinisterGeneral.save((err, doc) => {
               if(!err){
                  $sinisterGeneralDocumentation.forEach(function (item, index) {
                     $sinisterGeneralDocumentation[index]["idSinisterGeneral"]=doc._id;
                     $sinisterGeneralDocumentation[index]["sinisterGeneral"]=doc._id;
                     $sinisterGeneralDocumentation[index]["dateCreate"] = $moment;
                     $sinisterGeneralDocumentation[index]["userCreate"] = req.user.idUser;
                     $sinisterGeneralDocumentation[index]["dateUpdate"] = $moment;
                     $sinisterGeneralDocumentation[index]["userUpdate"] = req.user.idUser;
                  })
                  //let sinisterGeneralDocumentation = new SinisterGeneralDocumentation();
                  SinisterGeneralDocumentation.insertMany($sinisterGeneralDocumentation, (err, docs) => {
                  });
               }
            });
            findAction(function(docs){
               res.send({msg: "OK", update: docs});
            });
         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.post('/sinister/edit/:id', [control.auth, controller, control.acl], (req, res) => {

      let filter = {
         _id: req.params.id
      }

      let update = {
         idPolicy: req.body.idPolicy,
         policyData: req.body.policyData,
         idPolicyAnnex: req.body.idPolicyAnnex,
         annexData: req.body.annexData,
         idClient: req.body.idClient,
         clientData: req.body.clientData,
         compName: req.body.compName,
         clientInsured: req.body.clientInsured,
         beneficiary: req.body.beneficiary,
         dateSinester: req.body.dateSinester,
         dateNotification: req.body.dateNotification,
         trackingDate: req.body.trackingDate,
         beneficiary: req.body.beneficiary,
         idRamo: req.body.idRamo,
         ramo: req.body.idRamo,
         sinisterState: req.body.sinisterState,
         settlementDate: req.body.settlementDate,
         approvalDate: req.body.approvalDate,
         checkApproved: req.body.checkApproved,
         dateUpdate: moment(),
         userUpdate: req.user.idUser
      };

      Sinister.findOneAndUpdate(filter, update, function (err, doc) {
         if (!err) {
            findAction(function(docs){
               control.log(req.route.path, req.user);
               res.send({msg: "OK", update: docs});
            });
         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.delete('/sinister/delete/:id', [control.auth, controller, control.acl], (req, res) => {

      let filter = {
         _id: req.params.id
      }

      Sinister.findByIdAndRemove(filter, function (err, doc) {
         if(!err){
            findAction(function(docs){
               control.log(req.route.path, req.user);
               res.send({msg: "OK", update: docs});
            });
         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

   app.post('/sinister/report', [control.auth, controller, control.acl], (req, res) => {

      let $filter =  global.filter(req.body.filter);
      Sinister.find($filter, function (err, docs) {
         if (typeof docs !== 'undefined') {

         /*Ramo.populate(docs, {path: "ramo"},function(err, docs){
         City.populate(docs, {path: "city"},function(err, docs){
         Branch.populate(docs, {path: "branchCreate"},function(err, docs){
         PolicyType.populate(docs, {path: "policyType"},function(err, docs){*/

            var file = 'sinister.xlsx';
            var outPutFile = moment().format('YYYY-MM-DD-h:mm:ss') + file;
            var pathDownload = __dirname+'/../../public/download/';
            var workbook = excelbuilder.createWorkbook(pathDownload, outPutFile)
            var sheet1 = workbook.createSheet('sheet1', 15, 17);

            var cols = [2,3,4,5,6,7,8,9,10,11,12,13,14,15];
            var rowIni = 2;
            sheet1.set(cols[0], rowIni, 'Agencia');
            sheet1.set(cols[1], rowIni, 'Ciudad');
            sheet1.set(cols[2], rowIni, 'Nombre Cliente');
            sheet1.set(cols[4], rowIni, 'Numero de Poliza');
            sheet1.set(cols[5], rowIni, 'Numero de Siniestro');
            sheet1.set(cols[6], rowIni, 'Nombre Ramo');
            sheet1.set(cols[7], rowIni, 'Fecha de Inicio de Vigencia');
            sheet1.set(cols[8], rowIni, 'Fecha de fin de Vigencia');
            sheet1.set(cols[9], rowIni, 'Fecha de Siniestro');
            sheet1.set(cols[10], rowIni, 'Fecha de Notificacion');

            console.log(docs);
            let $length = docs.length;
            for (var i = 0; i < $length; i++) {
               rowIni++;
               let $cliente = '';
                  if(docs[i].typeRecipient == 'CLIENTE'){
                     $cliente = docs[i].recipient.name+' '+docs[i].recipient.lastName
                  }
               sheet1.set(cols[0], rowIni, docs[i]);
               /*sheet1.set(cols[0], rowIni, docs[i].branchCreate.name);
               sheet1.set(cols[1], rowIni, docs[i].city.name);
               sheet1.set(cols[2], rowIni, $cliente);
               sheet1.set(cols[3], rowIni, docs[i].policyNumber);
               sheet1.set(cols[4], rowIni, docs[i].ramo.name);
               sheet1.set(cols[5], rowIni, docs[i].policyType.name);
               sheet1.set(cols[6], rowIni, docs[i].startDate);
               sheet1.set(cols[7], rowIni, docs[i].finishDate);*/
            }

            workbook.save(function(err1, resp1){
               if (!err1){
                  console.log('congratulations, your workbook created');
                  res.send({msg: "OK", doc_name: outPutFile});
               }
               else{
                  workbook.cancel();
                  res.send({msg: "ERROR", err: err1});
               }
            });

         /*});
         });
         });
         });*/

         } else {
            let error=global.error(err, 0, req.controller);
            res.send({msg: 'ERROR', err: error});
         }
      });

   });

}

export default sinisterController
<|endoftext|>


<commit_before>export default Ember.ArrayController.extend({
  needs: ['application'],
  numRows: 100,

  transactions: Ember.computed.alias('controllers.application.model'),

  categories: [
    {
      name: 'food',
      symbol: 'fo'
    },
    {
      name: 'entertainment',
      symbol: 'en'
    },
    {
      name: 'UNCATEGORIZED',
      symbol: 'UN'
    }
  ],

  columns: function() {
    var dateColumn = Ember.Table.ColumnDefinition.create({
      isResizable: false,
      textAlign: 'text-align-left',
      columnWidth: 100,
      headerCellName: 'Date',
      getCellContent: function(row) {
        return row.get('date').toDateString();
      }
    });
    var descriptionColumn = Ember.Table.ColumnDefinition.create({
      isResizable: false,
      textAlign: 'text-align-left',
      columnWidth: 200,
      headerCellName: 'Description',
      contentPath: 'description'
    });
    var categoryColumn = Ember.Table.ColumnDefinition.create({
      isResizable: false,
      textAlign: 'text-align-left',
      columnWidth: 120,
      headerCellName: 'Category',
      contentPath: 'category'
    });
    var amountColumn = Ember.Table.ColumnDefinition.create({
      isResizable: false,
      tableCellViewClass: Ember.Table.TableCell.extend({
        templateName: 'amount-table-cell',
      }),
      columnWidth: 80,
      headerCellName: 'Amount',
      getCellContent: function(row) {
        return '$ ' + row.get('amount').toFixed(2);
      }
    });
    return [dateColumn, descriptionColumn, categoryColumn, amountColumn];
  }.property(),

  content: Ember.computed.alias('controllers.application.model')
});
<commit_msg>WIP on multi-select<commit_after>export default Ember.ArrayController.extend({
  needs: ['application'],
  numRows: 100,

  transactions: Ember.computed.alias('controllers.application.model'),

  categories: [
    {
      name: 'food',
      symbol: 'fo',
      def: 'food'
    },
    {
      name: 'entertainment',
      symbol: 'en',
      def: 'entertainment'
    },
    {
      name: 'UNCATEGORIZED',
      symbol: 'UN',
      def: 'UNCATEGORIZED'
    }
  ],

  columns: function() {
    var dateColumn = Ember.Table.ColumnDefinition.create({
      isResizable: false,
      textAlign: 'text-align-left',
      columnWidth: 100,
      headerCellName: 'Date',
      getCellContent: function(row) {
        return row.get('date').toDateString();
      }
    });
    var descriptionColumn = Ember.Table.ColumnDefinition.create({
      isResizable: false,
      textAlign: 'text-align-left',
      columnWidth: 200,
      headerCellName: 'Description',
      contentPath: 'description'
    });
    var categoryColumn = Ember.Table.ColumnDefinition.create({
      isResizable: false,
      textAlign: 'text-align-left',
      tableCellViewClass: Ember.Table.TableCell.extend({
        templateName: 'category-table-cell',
      }),
      columnWidth: 120,
      headerCellName: 'Category',
      contentPath: 'category'
    });
    var amountColumn = Ember.Table.ColumnDefinition.create({
      isResizable: false,
      tableCellViewClass: Ember.Table.TableCell.extend({
        templateName: 'amount-table-cell',
      }),
      columnWidth: 80,
      headerCellName: 'Amount',
      getCellContent: function(row) {
        return '$ ' + row.get('amount').toFixed(2);
      }
    });
    return [dateColumn, descriptionColumn, categoryColumn, amountColumn];
  }.property(),

  content: Ember.computed.alias('controllers.application.model')
});
<|endoftext|>


<commit_before>'use strict';

const notification = require('./notifications');
const Product = require('../models/product');
const Vendor = require('../models/vendor');
const config = require('../../config/config');
const schedule = require('node-schedule');
const request = require('request');

function getProducts(vendorId) {
  const prods = [];
  return new Promise((resolve) => {
    Product.
    find().
    exec((err, products) => {
      products.forEach(product => {
        if (product.vendor.toString() === vendorId.toString()) {
          prods.push(product);
        }
      });
      resolve(prods);
    });
  });
}

function getVendor(url) {
  return new Promise((resolve, reject) => {
    Vendor.
    findOne().
    where('url').equals(url).
    exec((err, vendor) => {
      if (vendor !== null) {
        resolve(vendor);
      } else {
        reject('vendor not found');
      }
    });
  });
}

exports.job = function() {
  const rule = new schedule.RecurrenceRule();
  rule.minute = 0;
  schedule.scheduleJob(rule, () => {
    console.log('products update startd ', new Date());
    getVendor(config.integratedVendorUrl).then(vendor => {
      return getProducts(vendor._id);
    }).then(products => {
      request(config.menuUpdateUrl, (error, response, body) => {
        const responseProducts = JSON.parse(body);

        while (products.length !== 0) {
          const existedProduct = products.pop();
          let isRecived = false;

          for (let i = 0; i < responseProducts.length; i++) {
            if (responseProducts[i].vendorId === existedProduct.vendorId) {
              isRecived = true;
              Product.findByIdAndUpdate(existedProduct._id, {
                $set: {
                  title: responseProducts[i].title,
                  description: responseProducts[i].description,
                  imageUrl: responseProducts[i].imageUrl,
                  price: responseProducts[i].price,
                  category: responseProducts[i].category,
                  deletedByVendor: false
                }
              }, (err) => {
                if (err) {
                  console.log(err);
                }
              });
              break;
            }
          }

          if (!isRecived) {
            Product.findByIdAndUpdate(existedProduct._id, {
              $set: {
                deletedByVendor: true
              }
            }, (err) => {
              if (err) {
                console.log(err);
              }
            });
          }
        }
        console.log('products updated ', new Date());
        notification.sendEmail(config.adminEmail, 'products updated ');
      });
    });
  });
};
<commit_msg>change update time<commit_after>'use strict';

const notification = require('./notifications');
const Product = require('../models/product');
const Vendor = require('../models/vendor');
const config = require('../../config/config');
const schedule = require('node-schedule');
const request = require('request');

function getProducts(vendorId) {
  const prods = [];
  return new Promise((resolve) => {
    Product.
    find().
    exec((err, products) => {
      products.forEach(product => {
        if (product.vendor.toString() === vendorId.toString()) {
          prods.push(product);
        }
      });
      resolve(prods);
    });
  });
}

function getVendor(url) {
  return new Promise((resolve, reject) => {
    Vendor.
    findOne().
    where('url').equals(url).
    exec((err, vendor) => {
      if (vendor !== null) {
        resolve(vendor);
      } else {
        reject('vendor not found');
      }
    });
  });
}

exports.job = function() {
  const rule = new schedule.RecurrenceRule();
  rule.minute = 15;
  schedule.scheduleJob(rule, () => {
    console.log('products update startd ', new Date());
    getVendor(config.integratedVendorUrl).then(vendor => {
      return getProducts(vendor._id);
    }).then(products => {
      request(config.menuUpdateUrl, (error, response, body) => {
        const responseProducts = JSON.parse(body);

        while (products.length !== 0) {
          const existedProduct = products.pop();
          let isRecived = false;

          for (let i = 0; i < responseProducts.length; i++) {
            if (responseProducts[i].vendorId === existedProduct.vendorId) {
              isRecived = true;
              Product.findByIdAndUpdate(existedProduct._id, {
                $set: {
                  title: responseProducts[i].title,
                  description: responseProducts[i].description,
                  imageUrl: responseProducts[i].imageUrl,
                  price: responseProducts[i].price,
                  category: responseProducts[i].category,
                  deletedByVendor: false
                }
              }, (err) => {
                if (err) {
                  console.log(err);
                }
              });
              break;
            }
          }

          if (!isRecived) {
            Product.findByIdAndUpdate(existedProduct._id, {
              $set: {
                deletedByVendor: true
              }
            }, (err) => {
              if (err) {
                console.log(err);
              }
            });
          }
        }
        console.log('products updated ', new Date());
        notification.sendEmail(config.adminEmail, 'products updated ');
      });
    });
  });
};
<|endoftext|>


<commit_before>import {
  argsForFetch,
  parseResponse
} from './utils/request'
import 'cross-fetch'
import {uuidv4} from './utils/helpers'
import {needsRefresh} from './window'
import {withoutBZParams} from './utils/url'
import {parseSJR} from './utils/request'
import {
  SAVE_RESPONSE,
  HANDLE_GRAFT,
  SET_IN_PAGE,
  DEL_IN_PAGE,
  EXTEND_IN_PAGE,
  SET_IN_JOINT,
  DEL_IN_JOINT,
  EXTEND_IN_JOINT,
  BEFORE_FETCH,
  BREEZY_ERROR,
  OVERRIDE_VISIT_SEQ,
} from './actions'

export function saveResponse ({pageKey, page}) {
  return {
    type: SAVE_RESPONSE,
    payload: {
      pageKey,
      page
    }
  }
}

export function handleGraft ({pageKey, page}) {
  return {
    type: HANDLE_GRAFT,
    payload: {
      pageKey,
      page
    }
  }
}

export function setInPage ({pageKey, keypath, value}) {
  return {
    type: SET_IN_PAGE,
    payload: {
      pageKey,
      keypath,
      value
    }
  }
}

export function delInPage ({pageKey, keypath}) {
  return {
    type: DEL_IN_PAGE,
    payload: {
      pageKey,
      keypath,
    }
  }
}

export function extendInPage ({pageKey, keypath, value}) {
  return {
    type: EXTEND_IN_PAGE,
    payload:{
      pageKey,
      keypath,
      value
    }
  }
}

export function setInJoint ({name, keypath, value}) {
  return {
    type: SET_IN_JOINT,
    payload: {
      name,
      keypath,
      value
    }
  }
}

export function delInJoint ({name, keypath}) {
  return {
    type: DEL_IN_JOINT,
    payload: {
      name,
      keypath
    }
  }
}

export function extendInJoint ({name, keypath, value}) {
  return {
    type: EXTEND_IN_JOINT,
    payload: {
      name,
      keypath,
      value
    }
  }
}

export function beforeFetch (payload) {
  return {
    type: BEFORE_FETCH,
    payload,
  }
}

export function handleError (err) {
  return {
    type: BREEZY_ERROR,
    payload: {
      message: err.message
    }
  }
}

export function saveAndProcessSJRPage (pageKey, pageSJR) {
  const page = parseSJR(pageSJR)
  return saveAndProcessPage(pageKey, page)
}

export function saveAndProcessPage (pageKey, page) {
  return (dispatch) => {
    const {defers = []} = page

    defers.forEach(function ({url}){
      dispatch(remote(url, {}, pageKey))
    })

    if (page.action === 'graft') {
      dispatch(handleGraft({pageKey, page}))
    } else {
      dispatch(saveResponse({pageKey, page}))
    }
  }
}

function handleFetchErr (err, fetchArgs, dispatch) {
  err.fetchArgs = fetchArgs
  err.url = fetchArgs[0]
  err.pageKey = withoutBZParams(fetchArgs[0])
  dispatch(handleError(err))
  throw err
}

export function wrappedFetch (fetchArgs) {
  return fetch(...fetchArgs)
    .then((response) => {
      const location = response.headers.get('x-breezy-location')
      const nextOpts = {...fetchArgs[1], body: undefined}
      if (location) {
        return wrappedFetch([location, {...nextOpts, method: 'GET'}])
      } else {
        return response
      }
    })
}

const persistAndMeta = (state, rsp, page, pageKey, dispatch) => {
  const prevAssets = state.breezy.assets
  const newAssets = page.assets

  pageKey = withoutBZParams(pageKey)

  const meta = {
    pageKey,
    page,
    screen: page.screen,
    rsp,
    needsRefresh: needsRefresh(prevAssets, newAssets)
  }

  dispatch(saveAndProcessPage(pageKey, page))
  return meta
}

export function remote (pathQuery, {method = 'GET', headers, body = ''} = {}, pageKey) {
  if (!pageKey) {
    throw new Error('pageKey is a required parameter')
  }

  return (dispatch, getState) => {
    const fetchArgs = argsForFetch(getState, pathQuery, {method, headers, body})

    dispatch(beforeFetch({fetchArgs}))

    return wrappedFetch(fetchArgs)
      .then(parseResponse)
      .then(({rsp, page}) => persistAndMeta(getState(), rsp, page, pageKey, dispatch))
      .catch(e => handleFetchErr(e, fetchArgs, dispatch))
  }
}

function extractPageKey(pathQuery, {method = 'GET'}, rsp) {
  if (method === 'GET') {
    return pathQuery
  } else {
    const responseUrl = rsp.headers.get('x-response-url')
    const contentLocation = rsp.headers.get('content-location')

    return contentLocation || responseUrl
  }
}

function canNavigate(seqId, {controlFlows}) {
  if (controlFlows['visit'] === seqId ) {
    return true
  } else {
    return false
  }
}

export function visit (pathQuery, {method = 'GET', headers, body = ''} = {}, pageKey) {
  return (dispatch, getState) => {
    const fetchArgs = argsForFetch(getState, pathQuery, {headers, body, method})
    const seqId = uuidv4()
    let actualKey = null

    dispatch(beforeFetch({fetchArgs}))
    dispatch({
      type: OVERRIDE_VISIT_SEQ,
      payload: {
        seqId
      }
    })

    return wrappedFetch(fetchArgs)
      .then(parseResponse)
      .then(({rsp, page}) => {
        actualKey = pageKey || extractPageKey(...[...fetchArgs, rsp])

        const meta = persistAndMeta(getState(), rsp, page, actualKey, dispatch)
        const {breezy} = getState()
        return {...meta, canNavigate: canNavigate(seqId, breezy)}
      })
      .catch(e => handleFetchErr(e, fetchArgs, dispatch))
  }
}
<commit_msg>extract is graft helper<commit_after>import {
  argsForFetch,
  parseResponse
} from './utils/request'
import 'cross-fetch'
import {uuidv4} from './utils/helpers'
import {needsRefresh} from './window'
import {withoutBZParams} from './utils/url'
import {parseSJR} from './utils/request'
import {
  SAVE_RESPONSE,
  HANDLE_GRAFT,
  SET_IN_PAGE,
  DEL_IN_PAGE,
  EXTEND_IN_PAGE,
  SET_IN_JOINT,
  DEL_IN_JOINT,
  EXTEND_IN_JOINT,
  BEFORE_FETCH,
  BREEZY_ERROR,
  OVERRIDE_VISIT_SEQ,
} from './actions'

export function saveResponse ({pageKey, page}) {
  return {
    type: SAVE_RESPONSE,
    payload: {
      pageKey,
      page
    }
  }
}

export function handleGraft ({pageKey, page}) {
  return {
    type: HANDLE_GRAFT,
    payload: {
      pageKey,
      page
    }
  }
}

export function setInPage ({pageKey, keypath, value}) {
  return {
    type: SET_IN_PAGE,
    payload: {
      pageKey,
      keypath,
      value
    }
  }
}

export function delInPage ({pageKey, keypath}) {
  return {
    type: DEL_IN_PAGE,
    payload: {
      pageKey,
      keypath,
    }
  }
}

export function extendInPage ({pageKey, keypath, value}) {
  return {
    type: EXTEND_IN_PAGE,
    payload:{
      pageKey,
      keypath,
      value
    }
  }
}

export function setInJoint ({name, keypath, value}) {
  return {
    type: SET_IN_JOINT,
    payload: {
      name,
      keypath,
      value
    }
  }
}

export function delInJoint ({name, keypath}) {
  return {
    type: DEL_IN_JOINT,
    payload: {
      name,
      keypath
    }
  }
}

export function extendInJoint ({name, keypath, value}) {
  return {
    type: EXTEND_IN_JOINT,
    payload: {
      name,
      keypath,
      value
    }
  }
}

export function beforeFetch (payload) {
  return {
    type: BEFORE_FETCH,
    payload,
  }
}

export function handleError (err) {
  return {
    type: BREEZY_ERROR,
    payload: {
      message: err.message
    }
  }
}

export function saveAndProcessSJRPage (pageKey, pageSJR) {
  const page = parseSJR(pageSJR)
  return saveAndProcessPage(pageKey, page)
}

export function isGraft(page) {
  return page.action === 'graft'
}

export function saveAndProcessPage (pageKey, page) {
  return (dispatch) => {
    const {defers = []} = page

    defers.forEach(function ({url}){
      dispatch(remote(url, {}, pageKey))
    })

    if (isGraft(page)) {
      dispatch(handleGraft({pageKey, page}))
    } else {
      dispatch(saveResponse({pageKey, page}))
    }
  }
}

function handleFetchErr (err, fetchArgs, dispatch) {
  err.fetchArgs = fetchArgs
  err.url = fetchArgs[0]
  err.pageKey = withoutBZParams(fetchArgs[0])
  dispatch(handleError(err))
  throw err
}

export function wrappedFetch (fetchArgs) {
  return fetch(...fetchArgs)
    .then((response) => {
      const location = response.headers.get('x-breezy-location')
      const nextOpts = {...fetchArgs[1], body: undefined}
      if (location) {
        return wrappedFetch([location, {...nextOpts, method: 'GET'}])
      } else {
        return response
      }
    })
}

const persistAndMeta = (state, rsp, page, pageKey, dispatch) => {
  const prevAssets = state.breezy.assets
  const newAssets = page.assets

  pageKey = withoutBZParams(pageKey)

  const meta = {
    pageKey,
    page,
    screen: page.screen,
    rsp,
    needsRefresh: needsRefresh(prevAssets, newAssets)
  }

  dispatch(saveAndProcessPage(pageKey, page))
  return meta
}

export function remote (pathQuery, {method = 'GET', headers, body = ''} = {}, pageKey) {
  if (!pageKey) {
    throw new Error('pageKey is a required parameter')
  }

  return (dispatch, getState) => {
    const fetchArgs = argsForFetch(getState, pathQuery, {method, headers, body})

    dispatch(beforeFetch({fetchArgs}))

    return wrappedFetch(fetchArgs)
      .then(parseResponse)
      .then(({rsp, page}) => persistAndMeta(getState(), rsp, page, pageKey, dispatch))
      .catch(e => handleFetchErr(e, fetchArgs, dispatch))
  }
}

function extractPageKey(pathQuery, {method = 'GET'}, rsp) {
  if (method === 'GET') {
    return pathQuery
  } else {
    const responseUrl = rsp.headers.get('x-response-url')
    const contentLocation = rsp.headers.get('content-location')

    return contentLocation || responseUrl
  }
}

function canNavigate(seqId, {controlFlows}) {
  if (controlFlows['visit'] === seqId ) {
    return true
  } else {
    return false
  }
}

export function visit (pathQuery, {method = 'GET', headers, body = ''} = {}, pageKey) {
  return (dispatch, getState) => {
    const fetchArgs = argsForFetch(getState, pathQuery, {headers, body, method})
    const seqId = uuidv4()
    let actualKey = null

    dispatch(beforeFetch({fetchArgs}))
    dispatch({
      type: OVERRIDE_VISIT_SEQ,
      payload: {
        seqId
      }
    })

    return wrappedFetch(fetchArgs)
      .then(parseResponse)
      .then(({rsp, page}) => {
        actualKey = pageKey || extractPageKey(...[...fetchArgs, rsp])

        const meta = persistAndMeta(getState(), rsp, page, actualKey, dispatch)
        const {breezy} = getState()
        return {...meta, canNavigate: canNavigate(seqId, breezy)}
      })
      .catch(e => handleFetchErr(e, fetchArgs, dispatch))
  }
}
<|endoftext|>


<commit_before>/*
* AUI Base
*/
AUI.add('aui-base', function(A) {

	A.mix(A.Array, {
		remove: function(a, from, to) {
		  var rest = a.slice((to || from) + 1 || a.length);
		  a.length = (from < 0) ? (a.length + from) : from;

		  return a.push.apply(a, rest);
		},

		removeItem: function(a, item) {
			var index = A.Array.indexOf(a, item);

			return A.Array.remove(a, index);
		}
	});

	// Courtesy of: http://simonwillison.net/2006/Jan/20/escape/
	A.Lang.escapeRegEx = function(str) {
		return str.replace(/([.*+?^$(){}|[\]\/\\])/g, '\\$1');
	};

}, '@VERSION', { requires: [ 'yui-base', 'base' ] });

/*
* AUI Delayed Task
*/

AUI.add('delayed-task', function(A) {

	var DelayedTask = function(fn, scope, args) {
		var instance = this;

		instance._args = args;
		instance._delay = 0;
		instance._fn = fn;
		instance._id = null;
		instance._scope = scope || instance;
		instance._time = 0;

		instance._base = function() {
			var now = instance._getTime();

			if (now - instance._time >= instance._delay) {
				clearInterval(instance._id);

				instance._id = null;

				instance._fn.apply(instance._scope, instance._args || []);
			}
		};
	};

	DelayedTask.prototype = {
		delay: function(delay, newFn, newScope, newArgs) {
			var instance = this;

			if (instance._id && instance._delay != delay) {
				instance.cancel();
			}

			instance._delay = delay || instance._delay;
			instance._time = instance._getTime();

			instance._fn = newFn || instance._fn;
			instance._scope = newScope || instance._scope;
			instance._args = newArgs || instance._args;

			if (!A.Lang.isArray(instance._args)) {
				instance._args = [instance._args];
			}

			if (!instance._id) {
				if (instance._delay > 0) {
					instance._id = setInterval(instance._base, instance._delay);
				}
				else {
					instance._base();
				}
			}
		},

		cancel: function() {
			var instance = this;

			if (instance._id) {
				clearInterval(instance._id);

				instance._id = null;
			}
		},

		_getTime: function() {
			var instance = this;

			return (+new Date());
		}
	};

	A.DelayedTask = DelayedTask;

}, '@VERSION', { requires: [ 'yui-base' ] });

/*
* AUI Node
*/

AUI.add('aui-node', function(A) {

	var Lang = A.Lang,
		isArray = Lang.isArray,
		isString = Lang.isString,
		isUndefined = Lang.isUndefined,

		INNER_HTML = 'innerHTML',
		NEXT_SIBLING = 'nextSibling',
		NONE = 'none',
		PARENT_NODE = 'parentNode',
		SCRIPT = 'script',
		VALUE = 'value';

	A.mix(A.Node.prototype, {
		appendTo: function(selector) {
			var instance = this;

			A.get(selector).append(instance);

			return instance;
		},

		attr: function(name, value) {
			var instance = this;

			if (!isUndefined(value)) {
				return instance.set(name, value);
			}
			else {
				return instance.get(name) || instance.getAttribute(name);
			}
		},

		empty: function() {
			var instance = this;

			instance.queryAll('>*').remove();

			var el = A.Node.getDOMNode(instance);

			while (el.firstChild) {
				el.removeChild(el.firstChild);
			}

			return instance;
		},

		getDOM: function() {
			var instance = this;

			return A.Node.getDOMNode(instance);
		},

		guid: function(prefix) {
			var instance = this;
			var currentId = instance.get('id');

			if (!currentId) {
				currentId = A.stamp(instance);

				instance.set('id', currentId);
			}

			return currentId;
		},

		hide: function(cssClass) {
			var instance = this;

			instance.addClass(cssClass || instance._hideClass || 'aui-helper-hidden');

			return instance;
		},

		html: function() {
			var args = arguments, length = args.length;

			if (length) {
				this.set(INNER_HTML, args[0]);
			}
			else {
				return this.get(INNER_HTML);
			}

			return this;
		},

		outerHTML: function() {
			var instance = this;
			var temp = A.Node.create('

').append(
				this.cloneNode(true)
			);

			try {
				return temp.html();
			}
			catch(e) {}
			finally {
				temp = null;
			}
		},

		placeAfter: function(content) {
			var instance = this;

			var parent = instance.get(PARENT_NODE);

			if (parent) {
				parent.insertBefore(content, instance.get(NEXT_SIBLING));
			}
		},

		placeBefore: function(content) {
			var instance = this;

			var parent = instance.get(PARENT_NODE);

			if (parent) {
				parent.insertBefore(content, instance);
			}
		},

		prependTo: function(selector) {
			var instance = this;

			A.get(selector).prepend(instance);
		},

		resetId: function(prefix) {
			var instance = this;

			instance.attr('id', A.guid(prefix));

			return instance;
		},

		selectable: function() {
			var instance = this;

			instance.getDOM().unselectable = 'off';
			instance.detach('selectstart');

			instance.setStyles(
				{
					'MozUserSelect': '',
					'KhtmlUserSelect': ''
				}
			);

			instance.removeClass('aui-helper-unselectable');

			return instance;
		},

		show: function(cssClass) {
			var instance = this;

			instance.removeClass(cssClass || instance._hideClass || 'aui-helper-hidden')

			return instance;
		},

		swallowEvent: function(eventName, preventDefault) {
			var instance = this;

			var fn = function(event) {
				event.stopPropagation();

				if (preventDefault) {
					event.preventDefault();

					event.halt();
				}

				return false;
			};

			if(isArray(eventName)) {
				A.Array.each(
					eventName,
					function(name) {
						instance.on(name, fn);
					}
				);

				return this;
			}
			else {
				instance.on(eventName, fn);
			}

			return instance;
		},

		text: function(text) {
			var instance = this;
			var el = instance.getDOM();

			if (!isUndefined(text)) {
				text = A.DOM._getDoc(el).createTextNode(text);

				return instance.empty().append(text);
			}

			return instance._getText(el.childNodes);
		},

		toggle: function(cssClass) {
			var instance = this;

			var action = 'hide';
			var hideClass = cssClass || instance._hideClass || 'aui-helper-hidden';

			if (instance.hasClass(hideClass)) {
				action = 'show';
			}

			instance[action](hideClass);
		},

		unselectable: function() {
			var instance = this;

			instance.getDOM().unselectable = 'on';

			instance.swallowEvent('selectstart', true);

			instance.setStyles(
				{
					'MozUserSelect': NONE,
					'KhtmlUserSelect': NONE
				}
			);

			instance.addClass('aui-helper-unselectable');

			return instance;
		},

		val: function(value) {
			var instance = this;

			return instance.attr(VALUE, value);
		},

		_getText: function(childNodes) {
			var instance = this;

			var length = childNodes.length;
			var childNode;

			var str = [];

			for (var i = 0; i < length; i++) {
				childNode = childNodes[i];

				if (childNode && childNode.nodeType != 8) {
					if (childNode.nodeType != 1) {
						str.push(childNode.nodeValue);
					}

					if (childNode.childNodes) {
						str.push(instance._getText(childNode.childNodes));
					}
				}
			}

			return str.join('');
		}
	}, true);

	A.mix(A.Node, {
		globalEval: function(data) {
			if ( data && /\S/.test(data) ) {
				var head = document.getElementsByTagName('head')[0] || document.documentElement;
				var script = document.createElement('script');

				script.type = 'text/javascript';

				if (AUI.support.scriptEval) {
					script.appendChild(document.createTextNode(data));
				}
				else {
					script.text = data;
				}

				head.insertBefore(script, head.firstChild);
				head.removeChild(script);
			}
		},

		evalScript: function(elem) {
			if (elem.src) {
				A.io(elem.src, {
					async: false,
					on: {
						complete: function(i, o) {
							A.Node.globalEval(o.responseText);
						}
					}
				});
			}
			else {
				A.Node.globalEval(elem.text || elem.textContent || elem.innerHTML || '');
			}
		},

		clean: function(html) {
			var TPL_NODE = '

',
				IE_FIX_PADDING_NODE = '
_
';

			// instead of fix all tags to "XHTML"-style, make the firstChild be a valid non-empty tag
			html = IE_FIX_PADDING_NODE + A.Lang.trim(html);

			delete A.DOM._cloneCache[html];

			// wrap in a nodeType == 1, nodeType 11 (document fragment) does not support getElementsByTagName
			var temp = A.Node.create(TPL_NODE).append(
				A.Node.create(html)
			);

			var scripts = temp.getElementsByTagName(SCRIPT);

			scripts.each(function(elem) {
				elem.remove();
			});

			temp.removeChild(A.Node.getDOMNode(temp).firstChild);

			var html = temp.html();

			// avoid IE6 memory leak
			temp = null;

			return [ html, scripts ];
		},

		domManip: function(html, callback) {
			var clean = A.Node.clean(html);
			var content = clean[0];
			var scripts = clean[1];

			if (callback) {
				callback.apply(this, [ content ]);
			}

			scripts.each(function(elem) {
				A.Node.evalScript( A.Node.getDOMNode(elem) );
			});
		}
	});

	A.Node.ATTRS.innerHTML = {
		setter: function(v) {
			var instance = this;

			var defaultSetter = function(value) {
				A.Node.DEFAULT_SETTER.apply(instance, [ INNER_HTML, value ]);
			};

			if (isString(v)) {
				// eval scripts
				v = A.Node.domManip(v, defaultSetter);
			}
			else {
				defaultSetter(v);
			}
		}
	};

	A.NodeList.importMethod(
		A.Node.prototype,
		[
			'after',

			'appendTo',

			'attr',

			'before',

			'empty',

			'hide',

			'html',

			'outerHTML',

			'prepend',

			'prependTo',

			'selectable',

			'show',

			'text',

			'toggle',

			'unselectable'
		]
	);

	A.mix(
		A.NodeList.prototype,
		{
			all: function(selector) {
				var instance = this;

				var newNodeList = [];
				var nodes = instance._nodes;
				var length = nodes.length;

				var subList;

				for (var i = 0; i < length; i++) {
					subList = A.Selector.query(selector, nodes[i]);

					if (subList && subList.length) {
						newNodeList.push.apply(newNodeList, subList);
					}
				}

				newNodeList = A.Array.unique(newNodeList);

				return A.all(newNodeList);
			},

			getDOM: function() {
				var instance = this;

				return A.NodeList.getDOMNodes(this);
			},

			one: function(selector) {
				var instance = this;

				var newNode = null;

				var nodes = instance._nodes;
				var length = nodes.length;

				for (var i = 0; i < length; i++) {
					newNode = A.Selector.query(selector, nodes[i], true);

					if (newNode) {
						newNode = A.one(newNode);

						break;
					}
				}

				return newNode;
			}
		}
	);

	A.mix(
		A,
		{
			getBody: function() {
				var instance = this;

				if (!instance._bodyNode) {
					instance._bodyNode = A.get(document.body);
				}

				return instance._bodyNode;
			},

			getDoc: function() {
				var instance = this;

				if (!instance._documentNode) {
					instance._documentNode = A.get(document);
				}

				return instance._documentNode;
			},

			getWin: function() {
				var instance = this;

				if (!instance._windowNode) {
					instance._windowNode = A.get(window);
				}

				return instance._windowNode;
			}
		}
	);

}, '@VERSION', { requires: [ 'collection', 'node' ] });<commit_msg>base.js .outerHTML() improvements, IE, Opera and WebKit all have outerHTML.<commit_after>/*
* AUI Base
*/
AUI.add('aui-base', function(A) {

	A.mix(A.Array, {
		remove: function(a, from, to) {
		  var rest = a.slice((to || from) + 1 || a.length);
		  a.length = (from < 0) ? (a.length + from) : from;

		  return a.push.apply(a, rest);
		},

		removeItem: function(a, item) {
			var index = A.Array.indexOf(a, item);

			return A.Array.remove(a, index);
		}
	});

	// Courtesy of: http://simonwillison.net/2006/Jan/20/escape/
	A.Lang.escapeRegEx = function(str) {
		return str.replace(/([.*+?^$(){}|[\]\/\\])/g, '\\$1');
	};

}, '@VERSION', { requires: [ 'yui-base', 'base' ] });

/*
* AUI Delayed Task
*/

AUI.add('delayed-task', function(A) {

	var DelayedTask = function(fn, scope, args) {
		var instance = this;

		instance._args = args;
		instance._delay = 0;
		instance._fn = fn;
		instance._id = null;
		instance._scope = scope || instance;
		instance._time = 0;

		instance._base = function() {
			var now = instance._getTime();

			if (now - instance._time >= instance._delay) {
				clearInterval(instance._id);

				instance._id = null;

				instance._fn.apply(instance._scope, instance._args || []);
			}
		};
	};

	DelayedTask.prototype = {
		delay: function(delay, newFn, newScope, newArgs) {
			var instance = this;

			if (instance._id && instance._delay != delay) {
				instance.cancel();
			}

			instance._delay = delay || instance._delay;
			instance._time = instance._getTime();

			instance._fn = newFn || instance._fn;
			instance._scope = newScope || instance._scope;
			instance._args = newArgs || instance._args;

			if (!A.Lang.isArray(instance._args)) {
				instance._args = [instance._args];
			}

			if (!instance._id) {
				if (instance._delay > 0) {
					instance._id = setInterval(instance._base, instance._delay);
				}
				else {
					instance._base();
				}
			}
		},

		cancel: function() {
			var instance = this;

			if (instance._id) {
				clearInterval(instance._id);

				instance._id = null;
			}
		},

		_getTime: function() {
			var instance = this;

			return (+new Date());
		}
	};

	A.DelayedTask = DelayedTask;

}, '@VERSION', { requires: [ 'yui-base' ] });

/*
* AUI Node
*/

AUI.add('aui-node', function(A) {

	var Lang = A.Lang,
		isArray = Lang.isArray,
		isString = Lang.isString,
		isUndefined = Lang.isUndefined,

		INNER_HTML = 'innerHTML',
		NEXT_SIBLING = 'nextSibling',
		NONE = 'none',
		PARENT_NODE = 'parentNode',
		SCRIPT = 'script',
		VALUE = 'value';

	A.mix(A.Node.prototype, {
		appendTo: function(selector) {
			var instance = this;

			A.get(selector).append(instance);

			return instance;
		},

		attr: function(name, value) {
			var instance = this;

			if (!isUndefined(value)) {
				return instance.set(name, value);
			}
			else {
				return instance.get(name) || instance.getAttribute(name);
			}
		},

		empty: function() {
			var instance = this;

			instance.queryAll('>*').remove();

			var el = A.Node.getDOMNode(instance);

			while (el.firstChild) {
				el.removeChild(el.firstChild);
			}

			return instance;
		},

		getDOM: function() {
			var instance = this;

			return A.Node.getDOMNode(instance);
		},

		guid: function(prefix) {
			var instance = this;
			var currentId = instance.get('id');

			if (!currentId) {
				currentId = A.stamp(instance);

				instance.set('id', currentId);
			}

			return currentId;
		},

		hide: function(cssClass) {
			var instance = this;

			instance.addClass(cssClass || instance._hideClass || 'aui-helper-hidden');

			return instance;
		},

		html: function() {
			var args = arguments, length = args.length;

			if (length) {
				this.set(INNER_HTML, args[0]);
			}
			else {
				return this.get(INNER_HTML);
			}

			return this;
		},

		outerHTML: function() {
			var instance = this;
			var domEl = instance.getDOM();

			// IE, Opera and WebKit all have outerHTML.
			if ('outerHTML' in domEl) {
				return domEl.outerHTML;
			}

			var temp = A.Node.create('

').append(
				this.cloneNode(true)
			);

			try {
				return temp.html();
			}
			catch(e) {}
			finally {
				temp = null;
			}
		},

		placeAfter: function(content) {
			var instance = this;

			var parent = instance.get(PARENT_NODE);

			if (parent) {
				parent.insertBefore(content, instance.get(NEXT_SIBLING));
			}
		},

		placeBefore: function(content) {
			var instance = this;

			var parent = instance.get(PARENT_NODE);

			if (parent) {
				parent.insertBefore(content, instance);
			}
		},

		prependTo: function(selector) {
			var instance = this;

			A.get(selector).prepend(instance);
		},

		resetId: function(prefix) {
			var instance = this;

			instance.attr('id', A.guid(prefix));

			return instance;
		},

		selectable: function() {
			var instance = this;

			instance.getDOM().unselectable = 'off';
			instance.detach('selectstart');

			instance.setStyles(
				{
					'MozUserSelect': '',
					'KhtmlUserSelect': ''
				}
			);

			instance.removeClass('aui-helper-unselectable');

			return instance;
		},

		show: function(cssClass) {
			var instance = this;

			instance.removeClass(cssClass || instance._hideClass || 'aui-helper-hidden')

			return instance;
		},

		swallowEvent: function(eventName, preventDefault) {
			var instance = this;

			var fn = function(event) {
				event.stopPropagation();

				if (preventDefault) {
					event.preventDefault();

					event.halt();
				}

				return false;
			};

			if(isArray(eventName)) {
				A.Array.each(
					eventName,
					function(name) {
						instance.on(name, fn);
					}
				);

				return this;
			}
			else {
				instance.on(eventName, fn);
			}

			return instance;
		},

		text: function(text) {
			var instance = this;
			var el = instance.getDOM();

			if (!isUndefined(text)) {
				text = A.DOM._getDoc(el).createTextNode(text);

				return instance.empty().append(text);
			}

			return instance._getText(el.childNodes);
		},

		toggle: function(cssClass) {
			var instance = this;

			var action = 'hide';
			var hideClass = cssClass || instance._hideClass || 'aui-helper-hidden';

			if (instance.hasClass(hideClass)) {
				action = 'show';
			}

			instance[action](hideClass);
		},

		unselectable: function() {
			var instance = this;

			instance.getDOM().unselectable = 'on';

			instance.swallowEvent('selectstart', true);

			instance.setStyles(
				{
					'MozUserSelect': NONE,
					'KhtmlUserSelect': NONE
				}
			);

			instance.addClass('aui-helper-unselectable');

			return instance;
		},

		val: function(value) {
			var instance = this;

			return instance.attr(VALUE, value);
		},

		_getText: function(childNodes) {
			var instance = this;

			var length = childNodes.length;
			var childNode;

			var str = [];

			for (var i = 0; i < length; i++) {
				childNode = childNodes[i];

				if (childNode && childNode.nodeType != 8) {
					if (childNode.nodeType != 1) {
						str.push(childNode.nodeValue);
					}

					if (childNode.childNodes) {
						str.push(instance._getText(childNode.childNodes));
					}
				}
			}

			return str.join('');
		}
	}, true);

	A.mix(A.Node, {
		globalEval: function(data) {
			if ( data && /\S/.test(data) ) {
				var head = document.getElementsByTagName('head')[0] || document.documentElement;
				var script = document.createElement('script');

				script.type = 'text/javascript';

				if (AUI.support.scriptEval) {
					script.appendChild(document.createTextNode(data));
				}
				else {
					script.text = data;
				}

				head.insertBefore(script, head.firstChild);
				head.removeChild(script);
			}
		},

		evalScript: function(elem) {
			if (elem.src) {
				A.io(elem.src, {
					async: false,
					on: {
						complete: function(i, o) {
							A.Node.globalEval(o.responseText);
						}
					}
				});
			}
			else {
				A.Node.globalEval(elem.text || elem.textContent || elem.innerHTML || '');
			}
		},

		clean: function(html) {
			var TPL_NODE = '

',
				IE_FIX_PADDING_NODE = '
_
';

			// instead of fix all tags to "XHTML"-style, make the firstChild be a valid non-empty tag
			html = IE_FIX_PADDING_NODE + A.Lang.trim(html);

			delete A.DOM._cloneCache[html];

			// wrap in a nodeType == 1, nodeType 11 (document fragment) does not support getElementsByTagName
			var temp = A.Node.create(TPL_NODE).append(
				A.Node.create(html)
			);

			var scripts = temp.getElementsByTagName(SCRIPT);

			scripts.each(function(elem) {
				elem.remove();
			});

			temp.removeChild(A.Node.getDOMNode(temp).firstChild);

			var html = temp.html();

			// avoid IE6 memory leak
			temp = null;

			return [ html, scripts ];
		},

		domManip: function(html, callback) {
			var clean = A.Node.clean(html);
			var content = clean[0];
			var scripts = clean[1];

			if (callback) {
				callback.apply(this, [ content ]);
			}

			scripts.each(function(elem) {
				A.Node.evalScript( A.Node.getDOMNode(elem) );
			});
		}
	});

	A.Node.ATTRS.innerHTML = {
		setter: function(v) {
			var instance = this;

			var defaultSetter = function(value) {
				A.Node.DEFAULT_SETTER.apply(instance, [ INNER_HTML, value ]);
			};

			if (isString(v)) {
				// eval scripts
				v = A.Node.domManip(v, defaultSetter);
			}
			else {
				defaultSetter(v);
			}
		}
	};

	A.NodeList.importMethod(
		A.Node.prototype,
		[
			'after',

			'appendTo',

			'attr',

			'before',

			'empty',

			'hide',

			'html',

			'outerHTML',

			'prepend',

			'prependTo',

			'selectable',

			'show',

			'text',

			'toggle',

			'unselectable'
		]
	);

	A.mix(
		A.NodeList.prototype,
		{
			all: function(selector) {
				var instance = this;

				var newNodeList = [];
				var nodes = instance._nodes;
				var length = nodes.length;

				var subList;

				for (var i = 0; i < length; i++) {
					subList = A.Selector.query(selector, nodes[i]);

					if (subList && subList.length) {
						newNodeList.push.apply(newNodeList, subList);
					}
				}

				newNodeList = A.Array.unique(newNodeList);

				return A.all(newNodeList);
			},

			getDOM: function() {
				var instance = this;

				return A.NodeList.getDOMNodes(this);
			},

			one: function(selector) {
				var instance = this;

				var newNode = null;

				var nodes = instance._nodes;
				var length = nodes.length;

				for (var i = 0; i < length; i++) {
					newNode = A.Selector.query(selector, nodes[i], true);

					if (newNode) {
						newNode = A.one(newNode);

						break;
					}
				}

				return newNode;
			}
		}
	);

	A.mix(
		A,
		{
			getBody: function() {
				var instance = this;

				if (!instance._bodyNode) {
					instance._bodyNode = A.get(document.body);
				}

				return instance._bodyNode;
			},

			getDoc: function() {
				var instance = this;

				if (!instance._documentNode) {
					instance._documentNode = A.get(document);
				}

				return instance._documentNode;
			},

			getWin: function() {
				var instance = this;

				if (!instance._windowNode) {
					instance._windowNode = A.get(window);
				}

				return instance._windowNode;
			}
		}
	);

}, '@VERSION', { requires: [ 'collection', 'node' ] });<|endoftext|>


<commit_before>modulejs.define('transcript-viewer', function () {
  var $viewport = $('.viewport-content');

  var $text = $viewport.find('.transcript-text');
  var currentSeq = $text.data('seq');
  var currentDate;
  var currentPage;
  var count = $text.data('page-count');
  var totalPages = $text.data('total-pages');
  var fromSeq = $text.data('from-seq');
  var toSeq = $text.data('to-seq');
  var batchSize = 11;

  var goToSeq = function (seq) {
    currentSeq = Math.min(Math.max(seq, 1), totalPages);
    var $page = $viewport.find('.page[data-seq="'+currentSeq+'"]');
    $viewport.scrollTop($page[0].offsetTop - 10);
  };
  var goToPage = function (page) {
    var $page = $('.page[data-page="'+page+'"]');
    if ($page.length) {
      $viewport.scrollTop($page[0].offsetTop - 10);
      return true;
    }
    return false;
  };
  var goToDate = function (date) {
    var $page = $('.page[data-date="'+date+'"]');
    if ($page.length) {
      $viewport.scrollTop($page[0].offsetTop - 10);
      return true;
    }
    return false;
  };

  var initialSeq = currentSeq;
  goToSeq(initialSeq);
  setTimeout(function () {goToSeq(initialSeq);}, 100);

  $('.page-buttons .next-page').on('click', function () {
    goToSeq(currentSeq + 1);
  });
  $('.page-buttons .prev-page').on('click', function () {
    goToSeq(currentSeq - 1);
  });

  $('.page-buttons .first-page').on('click', function () {
    if (fromSeq <= 1) {
      goToSeq(1);
    } else {
      loadFromScratch({seq: 1});
    }
  });
  $('.page-buttons .last-page').on('click', function () {
    if (fromSeq >= totalPages) {
      goToSeq(1);
    } else {
      loadFromScratch({seq: totalPages});
    }
  });
  $('form.go-to-page').on('submit', function (e) {
    e.preventDefault();

    var $input = $(this).find('input[name=page]')
    var page = $input.val();
    if (page < 1)
      return $input.val(1);
    if (page > totalPages)
      return $input.val(totalPages);
    var $page = $('.page[data-page="'+page+'"]');

    if (!goToPage(page))
      loadFromScratch({page: page});
  });

  $('select.select-date').on('change', function () {
    var date = $(this).val();
    if (!goToDate(date))
      loadFromScratch({date: date});
  });

  if (fromSeq <= 1) {
    $viewport.find('.above .end-indicator').text('Beginning of transcript')
  }
  if (toSeq >= totalPages) {
    $viewport.find('.below .end-indicator').text('End of transcript');
  }

  var loadingBelow = false;
  var loadBelow = function () {
    if (loading || loadingBelow)
      return;
    loadingBelow = true;
    if (toSeq >= totalPages) {
      $viewport.find('.below .end-indicator').text('End of transcript');
      return;
    }
    $.get({
      url: '',
      data: {
        from_seq: toSeq,
        to_seq: Math.min(totalPages, toSeq + batchSize),
        partial: true,
      }
    })
    .then(function (data) {
      toSeq = data.to_seq;
      $text.append($(data.html));
      loadingBelow = false;
    })
  };

  var loadingAbove = false;
  var loadAbove = function () {
    if (loading || loadingAbove)
      return;
    loadingAbove = true;
    if (fromSeq <= 1) {
      $viewport.find('.above .end-indicator').text('Beginning of transcript')
      return;
    }
    $.get({
      url: '',
      data: {
        from_seq: Math.max(1, fromSeq - batchSize),
        to_seq: fromSeq,
        partial: true,
      }
    })
    .then(function (data) {
      fromSeq = data.from_seq;
      var container = $('

');
      container.append($(data.html));
      $text.prepend(container);
      $viewport.scrollTop($viewport.scrollTop() + container.height() + 29);
      loadingAbove = false;
    })
  };

  var loading = false;
  var loadFromScratch = function (options) {
    if (loading)
      return;
    options.partial = true;
    options.seq = options.seq || currentSeq;
    loading = true;
    $text.empty();
    $.get({
      url: '',
      data: options
    })
    .then(function (data) {
      fromSeq = data.from_seq;
      toSeq = data.to_seq;
      $text.append($(data.html));
      if (data.seq)
        goToSeq(data.seq)
      loading = false;
    })
  };

  $viewport.on('click', 'a.view-image', function () {
    var $a = $(this);
    var href = $a.siblings('.download-image').attr('href');
    $a.closest('.page-handle')
    .addClass('show')
    .after('

');
  });

  var handleScroll = function () {
    var view = {
      top: $viewport.scrollTop(),
      height: $viewport.height() * 2,
      bottom: $viewport.scrollTop() + $viewport.height()
    };

    var page = {
      top: 0,
      bottom: $viewport[0].scrollHeight
    };

    if (view.bottom + view.height > page.bottom) {
      loadBelow();
    } else if (view.top - view.height < page.top) {
      loadAbove();
    }
    var rect = $viewport[0].getBoundingClientRect();
    var point = {x: rect.left + 100, y: rect.top + 10};
    do {
      point.y += 100;
      if (point.y > rect.top + 1000) return;
      var target = document.elementFromPoint(point.x, point.y);
      var $page = $(target).closest('.page');
    } while ($page.length == 0)

    currentSeq = $page.data('seq');
    currentPage = $page.data('page');
    currentDate = $page.data('date');

    if (currentDate)
      $('select.select-date').val(currentDate);

    if (currentPage)
      $('form.go-to-page input[name=page]').val(currentPage);

    console.log('current', currentSeq, currentPage, currentDate);
  };

  $viewport.on('scroll', _.throttle(handleScroll, 300));

})
<commit_msg>fix infinite scroll after reloading results<commit_after>modulejs.define('transcript-viewer', function () {
  var $viewport = $('.viewport-content');

  var $text = $viewport.find('.transcript-text');
  var currentSeq = $text.data('seq');
  var currentDate;
  var currentPage;
  var count = $text.data('page-count');
  var totalPages = $text.data('total-pages');
  var fromSeq = $text.data('from-seq');
  var toSeq = $text.data('to-seq');
  var batchSize = 11;

  var goToSeq = function (seq) {
    currentSeq = Math.min(Math.max(seq, 1), totalPages);
    var $page = $viewport.find('.page[data-seq="'+currentSeq+'"]');
    $viewport.scrollTop($page[0].offsetTop - 10);
  };
  var goToPage = function (page) {
    var $page = $('.page[data-page="'+page+'"]');
    if ($page.length) {
      $viewport.scrollTop($page[0].offsetTop - 10);
      return true;
    }
    return false;
  };
  var goToDate = function (date) {
    var $page = $('.page[data-date="'+date+'"]');
    if ($page.length) {
      $viewport.scrollTop($page[0].offsetTop - 10);
      return true;
    }
    return false;
  };

  var initialSeq = currentSeq;
  goToSeq(initialSeq);
  setTimeout(function () {goToSeq(initialSeq);}, 100);

  $('.page-buttons .next-page').on('click', function () {
    goToSeq(currentSeq + 1);
  });
  $('.page-buttons .prev-page').on('click', function () {
    goToSeq(currentSeq - 1);
  });

  $('.page-buttons .first-page').on('click', function () {
    if (fromSeq <= 1) {
      goToSeq(1);
    } else {
      loadFromScratch({seq: 1});
    }
  });
  $('.page-buttons .last-page').on('click', function () {
    if (fromSeq >= totalPages) {
      goToSeq(1);
    } else {
      loadFromScratch({seq: totalPages});
    }
  });
  $('form.go-to-page').on('submit', function (e) {
    e.preventDefault();

    var $input = $(this).find('input[name=page]')
    var page = $input.val();
    if (page < 1)
      return $input.val(1);
    if (page > totalPages)
      return $input.val(totalPages);
    var $page = $('.page[data-page="'+page+'"]');

    if (!goToPage(page))
      loadFromScratch({page: page});
  });

  $('select.select-date').on('change', function () {
    var date = $(this).val();
    if (!goToDate(date))
      loadFromScratch({date: date});
  });

  if (fromSeq <= 1) {
    $viewport.find('.above .end-indicator').text('Beginning of transcript')
  }
  if (toSeq >= totalPages) {
    $viewport.find('.below .end-indicator').text('End of transcript');
  }

  var loading = false;
  var loadBelow = function () {
    if (toSeq >= totalPages) {
      $viewport.find('.below .end-indicator').text('End of transcript');
      return;
    } else {
      $viewport.find('.below .end-indicator').text('Loading...');
    }
    if (loading)
      return;
    loading = true;
    $.get({
      url: '',
      data: {
        from_seq: toSeq,
        to_seq: Math.min(totalPages, toSeq + batchSize),
        partial: true,
      }
    })
    .then(function (data) {
      toSeq = data.to_seq;
      $text.append($(data.html));
      loading = false;
    })
  };

  var loadAbove = function () {
    if (fromSeq <= 1) {
      $viewport.find('.above .end-indicator').text('Beginning of transcript');
      return;
    } else {
      $viewport.find('.above .end-indicator').text('Loading...');
    }
    if (loading)
    return;
    loading = true;
    $.get({
      url: '',
      data: {
        from_seq: Math.max(1, fromSeq - batchSize),
        to_seq: fromSeq,
        partial: true,
      }
    })
    .then(function (data) {
      fromSeq = data.from_seq;
      var container = $('

');
      container.append($(data.html));
      $text.prepend(container);
      $viewport.scrollTop($viewport.scrollTop() + container.height() + 29);
      loading = false;
    })
  };

  var loadFromScratch = function (options) {
    if (loading)
      return;
    options.partial = true;
    options.seq = options.seq || currentSeq;
    loading = true;
    $text.empty();
    $.get({
      url: '',
      data: options
    })
    .then(function (data) {
      fromSeq = data.from_seq;
      toSeq = data.to_seq;
      $text.append($(data.html));
      if (data.seq)
        goToSeq(data.seq)
      loading = false;
    })
  };

  $viewport.on('click', 'a.view-image', function () {
    var $a = $(this);
    var href = $a.siblings('.download-image').attr('href');
    $a.closest('.page-handle')
    .addClass('show')
    .after('

');
  });

  var handleScroll = function () {
    var view = {
      top: $viewport.scrollTop(),
      height: $viewport.height() * 2,
      bottom: $viewport.scrollTop() + $viewport.height()
    };

    var page = {
      top: 0,
      bottom: $viewport[0].scrollHeight
    };

    if (view.bottom + view.height > page.bottom) {
      loadBelow();
    } else if (view.top - view.height < page.top) {
      loadAbove();
    }
    var rect = $viewport[0].getBoundingClientRect();
    var point = {x: rect.left + 100, y: rect.top + 10};
    do {
      point.y += 100;
      if (point.y > rect.top + 1000) return;
      var target = document.elementFromPoint(point.x, point.y);
      var $page = $(target).closest('.page');
    } while ($page.length == 0)

    currentSeq = $page.data('seq');
    currentPage = $page.data('page');
    currentDate = $page.data('date');

    if (currentDate)
      $('select.select-date').val(currentDate);

    if (currentPage)
      $('form.go-to-page input[name=page]').val(currentPage);

    console.log('current', currentSeq, currentPage, currentDate);
  };

  $viewport.on('scroll', _.throttle(handleScroll, 300));

})
<|endoftext|>