Exemplo n.º 1
0
export default function () {
  Meteor.methods({
    'accounts.deleteAccount'( userId ) {
      check( userId, String )
      // Demo the latency compensation (Delete this in production)
      Meteor._sleepForMs(500)
      if ( Meteor.user() ) {
        Meteor.users.remove( { _id: userId } )
      }
    },
    'accounts.sendResetPasswordLink'( email ) {
      check( email, String )
      let userId = Meteor.users.findOne({ 'emails.address': email })
      // Demo the latency compensation (Delete this in production)
      Meteor._sleepForMs(500)
      if ( !userId ) {
        console.log(`no user account with the address: ${email}`)
        throw new Meteor.Error(
          'sendResetPaswordLink.RESET_PASSWORD_ERROR',
          `User account with the address: ${email} not found. Please try again.`,
          'no user found',
        )
      } else if ( userId ) {
        return Accounts.sendResetPasswordEmail( userId )
      }
    },
  })
}
Exemplo n.º 2
0
export default function () {
  Meteor.methods({
    'posts.create'(_id, title, content) {
      check(_id, String);
      check(title, String);
      check(content, String);

      // Show the latency compensations
      Meteor._sleepForMs(500);

      // XXX: Do some user authorization
      const createdAt = new Date();
      const post = {_id, title, content, createdAt};
      Posts.insert(post);
    }
  });

  Meteor.methods({
    'posts.createComment'(_id, postId, text) {
      check(_id, String);
      check(postId, String);
      check(text, String);

      // Show the latency compensations
      Meteor._sleepForMs(500);

      // XXX: Do some user authorization
      const createdAt = new Date();
      const author = 'The User';
      const comment = {_id, postId, author, text, createdAt};
      Comments.insert(comment);
    }
  });
}
Exemplo n.º 3
0
	'some-method': function(id) {
		check(id, String);
		FiberScope.current.id = id;
		showContext("method");
		Meteor._sleepForMs(2000);
		nextThing("method");
		Meteor._sleepForMs(2000);
		nextThing("method");
		Meteor._sleepForMs(2000);
		nextThing("method");
		Meteor._sleepForMs(2000);
	},
Exemplo n.º 4
0
Meteor.publish('some-pub', function(id) {
	check(id, String);
	FiberScope.current.id = id;
	FiberScope.current.context = this;
	showContext("pub");
	Meteor._sleepForMs(2000);
	nextThing("pub");
	Meteor._sleepForMs(2000);
	nextThing("pub");
	Meteor._sleepForMs(2000);
	nextThing("pub");
	Meteor._sleepForMs(2000);
	return this.ready();
});
Exemplo n.º 5
0
	"my-method": function(id) {
		this.unblock(); // enables yielding between calls from the same connection
		FiberScope.current.x = Math.random();
		FiberScope.current.y = Math.random();
		displayCoords(id);
		Meteor._sleepForMs(2000); // causes a yield (other code can run during this pause)
		displayCoords(id);
	},
Meteor.publish('moneyTransfer.customerExpiredDate', function (limit) {
    this.unblock();
    Meteor._sleepForMs(200);
    if (this.userId) {
        let currentDate = moment().toDate();
        return Customer.find({expiredDate: {$lt: currentDate}}, limit);
    }
    return this.ready();
});
Exemplo n.º 7
0
Migrations.migrateTo = function(command) {
	if (_.isUndefined(command) || command === '' || this._list.length === 0) { throw new Error(`Cannot migrate using invalid command: ${ command }`); }

	let version;
	let subcommands;
	if (typeof command === 'number') {
		version = command;
	} else {
		version = command.split(',')[0];
		subcommands = command.split(',').slice(1);
	}

	const { maxAttempts, retryInterval } = Migrations.options;
	let migrated;
	for (let attempts = 1; attempts <= maxAttempts; attempts++) {
		if (version === 'latest') {
			migrated = this._migrateTo(_.last(this._list).version);
		} else {
			migrated = this._migrateTo(parseInt(version), (subcommands.includes('rerun')));
		}
		if (migrated) {
			break;
		} else {
			let willRetry;
			if (attempts < maxAttempts) {
				willRetry = ` Trying again in ${ retryInterval } seconds.`;
				Meteor._sleepForMs(retryInterval * 1000);
			} else {
				willRetry = '';
			}
			console.log(`Not migrating, control is locked. Attempt ${ attempts }/${ maxAttempts }.${ willRetry }`.yellow);
		}
	}
	if (!migrated) {
		const control = this._getControl(); // Side effect: upserts control document.
		console.log(makeABox([
			'ERROR! SERVER STOPPED',
			'',
			'Your database migration control is locked.',
			'Please make sure you are running the latest version and try again.',
			'If the problem persists, please contact support.',
			'',
			`This Rocket.Chat version: ${ Info.version }`,
			`Database locked at version: ${ control.version }`,
			`Database target version: ${ version === 'latest' ? _.last(this._list).version : version }`,
			'',
			`Commit: ${ Info.commit.hash }`,
			`Date: ${ Info.commit.date }`,
			`Branch: ${ Info.commit.branch }`,
			`Tag: ${ Info.commit.tag }`,
		]));
		process.exit(1);
	}

	// remember to run meteor with --once otherwise it will restart
	if (subcommands.includes('exit')) { process.exit(0); }
};
Exemplo n.º 8
0
 it("should create top level variant", function (done) {
   sandbox.stub(Reaction, "hasPermission", () => true);
   const product = addProduct();
   let variants = Products.find({ ancestors: [product._id] }).fetch();
   expect(variants.length).to.equal(1);
   Meteor.call("products/createVariant", product._id);
   Meteor._sleepForMs(500);
   variants = Products.find({ ancestors: [product._id] }).fetch();
   expect(variants.length).to.equal(2);
   return done();
 });
export default function () {
  Meteor.methods({
    'comments.upvote'(_id) {
      check(_id, String);

      // Demo the latency compensations (Delete this in production)
      Meteor._sleepForMs(2000);

      Comments.update(_id, {$inc: {upvoteCount: 1}});
    }
  });
}
Exemplo n.º 10
0
export default function loadData() {
  if (!process.env.SKIP_FIXTURES) {
    /**
     * Hook to setup core additional imports during Reaction init (shops process first)
     */
    Logger.info("Load default data from /private/data/");

    // Since import overwrites, only import Shops when none exist
    if (!Reaction.getShopId()) {
      try {
        Logger.debug("Loading Shop Data");
        Reaction.Importer.process(Assets.getText("data/Shops.json"), ["name"], Reaction.Importer.shop);
        // ensure Shops are loaded first.
        Reaction.Importer.flush(Shops);
      } catch (error) {
        Logger.error(error, "Bypassing loading Shop default data");
      }

      // make sure the default shop has been created before going further
      while (!Reaction.getShopId()) {
        Logger.debug("Loading default shop, waiting until it's ready before moving on...");
        Meteor._sleepForMs(1000);
      }
    }

    try {
      Logger.debug("Loading Shipping Data");
      Fixture.process(Assets.getText("data/Shipping.json"), ["name"], Reaction.Importer.shipping);
    } catch (error) {
      Logger.error(error, "Bypassing loading Shipping default data.");
    }

    try {
      Logger.debug("Loading Product Data");
      Fixture.process(Assets.getText("data/Products.json"), ["title"], Reaction.Importer.product);
    } catch (error) {
      Logger.error(error, "Bypassing loading Products default data.");
    }

    try {
      Logger.debug("Loading Tag Data");
      Fixture.process(Assets.getText("data/Tags.json"), ["name"], Reaction.Importer.tag);
    } catch (error) {
      Logger.error(error, "Bypassing loading Tags default data.");
    }
    //
    // these will flush and import with the rest of the imports from core init.
    // but Bulk.find.upsert() = false
    //
    Fixture.flush();
  }
}
Exemplo n.º 11
0
Meteor.publish('pos.activeLendingStock', function activeLendingStocks(selector) {
    this.unblock();
    new SimpleSchema({
        selector: {type: Object, blackbox: true}
    }).validate({selector});
    if (this.userId) {
        Meteor._sleepForMs(200);
        let data = LendingStocks.find(selector);
        console.log(data.fetch());
        return data;
    }
    return this.ready();
});
Exemplo n.º 12
0
function processUpload (fileObj) {
  // process a file, which is either a .zip or a .json
  console.log('Processing upload ' + fileObj.name())
  for (var i = 0; i < 5; i++) {
    if (fileObj.hasStored(UploadTempStoreName)) {
      break
    }
    console.log('storage not done, sleeping')
    Meteor._sleepForMs(1000)
  }

  // Ideally, we would just directly get the data from the FS.File object
  // but I could not figure out how to do that. So we do the below hack
  // instead.

  var readStream = fileObj.createReadStream()
  // This is a hack. We should get the buffer directly from CollectionFS.
  var hack_fullpath = readStream.path
  var buf = fs.readFileSync(hack_fullpath)

  console.log('fileObj.size()', fileObj.size())
  if (fileObj.size() !== buf.length) {
    throw new Error('unexpected size mismatch')
  }

  let isZip = false
  const zip = new JSZip()
  console.log('loading file with length of', buf.length)

  try {
    zip.load(buf)
    isZip = true
  } catch (e) {
    console.log('not a zip file:', e)
  }

  let jsonResults = null
  let error = null
  try {
    jsonResults = isZip ? processZip(zip) : processRawJsonBuf(buf)
  } catch (e) {
    error = e.toString()
  } finally {
    // now remove file
    console.log('  removing file')
    UploadedTempFileStore.remove({_id: fileObj._id})
  }

  return {jsonResults, filename: fileObj.name(), error}
}
Exemplo n.º 13
0
 startLoop: function () {
     this.unblock();
     Data.canRun = true;
     var datas = Data.collection.find({}).fetch();
     while(Data.canRun && datas.length > 0){
         //DO SOMETHING WITH data
         var data = datas.shift();
         if(datas.length % 1000 === 0){
             Meteor._sleepForMs(2000);
             console.log(data, Data.canRun);
         }
     }
     return `remaining items is ${datas.length}`;
 },
Exemplo n.º 14
0
Meteor.publish('moneyTransfer.borrowingById', function moneyTransferBorrowingById(borrowingId) {
    this.unblock();
    Meteor._sleepForMs(200);

    new SimpleSchema({
        borrowingId: {type: String}
    }).validate({borrowingId});

    if (!this.userId) {
        return this.ready();
    }

    return Borrowing.find({_id: borrowingId});
});
Exemplo n.º 15
0
Meteor.publish('moneyTransfer.bankAccountById', function moneyTransferBankAccount(bankAccountId) {
    this.unblock();
    Meteor._sleepForMs(200);

    new SimpleSchema({
        bankAccountId: {type: String}
    }).validate({bankAccountId});

    if (!this.userId) {
        return this.ready();
    }

    return Transfer.find({_id: bankAccountId});
});
Exemplo n.º 16
0
Meteor.publish('Todos.list', (filter = 'all') => {
  const query = {}
  // simulate slow server
  Meteor._sleepForMs(1000)
  // simulate error when publishing
  // throw new Meteor.Error('Something went wrong!')
  if (filter === 'active') {
    query.completed = false
  }
  else if (filter === 'completed') {
    query.completed = true
  }
  return Todos.find(query)
})
Exemplo n.º 17
0
 it("should decrease the quantity when called with a quantity", function () {
   sandbox.stub(Meteor.server.method_handlers, "cart/resetShipmentMethod", function () {
     check(arguments, [Match.Any]);
   });
   sandbox.stub(Meteor.server.method_handlers, "shipping/updateShipmentQuotes", function () {
     check(arguments, [Match.Any]);
   });
   const cart = Factory.create("cartTwo");
   const cartUserId = cart.userId;
   sandbox.stub(Reaction, "getShopId", () => shop._id);
   sandbox.stub(Meteor, "userId", () => cartUserId);
   const cartFromCollection = Collections.Cart.findOne(cart._id);
   const cartItemId = cartFromCollection.items[0]._id;
   Meteor.call("cart/removeFromCart", cartItemId, 1);
   Meteor._sleepForMs(500);
   const updatedCart = Collections.Cart.findOne(cart._id);
   expect(updatedCart.items[0].quantity).to.equal(1);
 });
Exemplo n.º 18
0
export default function () {

  Meteor.methods({
    'pgns.create'(_id, title, content) {
      check(_id, String);
      check(title, String);
      check(content, String);

      // Show the latency compensations
      Meteor._sleepForMs(500);

      // XXX: Do some user authorization
      const createdAt = new Date();
      const pgn = {_id, title, content, createdAt};
      Pgns.insert(pgn);
    }
  });
}
Exemplo n.º 19
0
    it("should create variant with predefined object", function (done) {
      sandbox.stub(Reaction, "hasPermission", () => true);
      const product = addProduct();
      const newVariant = {
        title: "newVariant"
      };
      let variants = Products.find({ ancestors: [product._id] }).fetch();
      const firstVariantId = variants[0]._id;
      expect(variants.length).to.equal(1);

      Meteor.call("products/createVariant", product._id, newVariant);
      Meteor._sleepForMs(500);
      variants = Products.find({ ancestors: [product._id] }).fetch();
      const createdVariant = variants.filter(v => v._id !== firstVariantId);
      expect(variants.length).to.equal(2);
      expect(createdVariant[0].title).to.equal("newVariant");
      return done();
    });
Exemplo n.º 20
0
    it("should create option variant", function (done) {
      sandbox.stub(Reaction, "hasPermission", () => true);
      let options;
      const product = addProduct();
      const variant = Products.find({ ancestors: [product._id] }).fetch()[0];
      options = Products.find({
        ancestors: { $in: [variant._id] }
      }).fetch();
      expect(options.length).to.equal(2);

      Meteor.call("products/createVariant", variant._id);
      Meteor._sleepForMs(500);
      options = Products.find({
        ancestors: { $in: [variant._id] }
      }).fetch();
      expect(options.length).to.equal(3);
      return done();
    });
Exemplo n.º 21
0
  FindFromPublication.publish('pcategories', function publications(skipCount) {
    Meteor._sleepForMs(500);
    const positiveIntegerCheck = Match.Where(function(x) {
      check(x, Match.Integer);
      return x >= 0;
    });

    check(skipCount, positiveIntegerCheck);

    Counts.publish(this, 'pcategoryCount', PostCategories.find(), {
      noReady: true
    });

    return PostCategories.find({}, {
      limit: parseInt(Meteor.settings.public.recordsPerPage),
      skip:skipCount
    });
  });
Exemplo n.º 22
0
 it("should remove cart item when quantity is decresed to zero", function () {
   sandbox.stub(Meteor.server.method_handlers, "cart/resetShipmentMethod", function () {
     check(arguments, [Match.Any]);
   });
   sandbox.stub(Meteor.server.method_handlers, "shipping/updateShipmentQuotes", function () {
     check(arguments, [Match.Any]);
   });
   const cart = Factory.create("cartOne");
   const cartUserId = cart.userId;
   sandbox.stub(Reaction, "getShopId", () => shop._id);
   sandbox.stub(Meteor, "userId", () => cartUserId);
   const cartFromCollection = Collections.Cart.findOne(cart._id);
   const cartItemId = cartFromCollection.items[0]._id;
   const originalQty = cartFromCollection.items[0].quantity;
   Meteor.call("cart/removeFromCart", cartItemId, originalQty);
   Meteor._sleepForMs(500);
   const updatedCart = Collections.Cart.findOne(cart._id);
   expect(updatedCart.items.length).to.equal(0);
 });
Exemplo n.º 23
0
export default function () {

  Meteor.methods({
    'status.create'(_id, user, statusnews) {
      check(_id, String);
      check(user, String);
      check(statusnews, String);


      // Demo the latency compensations (Delete this in production)
      Meteor._sleepForMs(500);

      // XXX: Do some user authorization
      const createdAt = new Date();
      const status = {_id, user, createdAt, statusnews, createdAt};
      Status.insert(status);
    }
  });

}
Exemplo n.º 24
0
    it("should update variants' revision position", function () {
      sandbox.stub(Reaction, "hasPermission", () => true);
      const product1 = addProduct();
      const product2 = addProduct();
      const product3 = addProduct();

      expect(product1.index).to.be.undefined;
      expect(product2.index).to.be.undefined;
      expect(product3.index).to.be.undefined;

      Meteor.call("products/updateVariantsPosition", [
        product2._id, product3._id, product1._id
      ]);
      Meteor._sleepForMs(500);
      const modifiedProductRevision1 = Revisions.findOne({ documentId: product1._id });
      const modifiedProductRevision2 = Revisions.findOne({ documentId: product2._id });
      const modifiedProductRevision3 = Revisions.findOne({ documentId: product3._id });
      expect(modifiedProductRevision1.documentData.index).to.equal(2);
      expect(modifiedProductRevision2.documentData.index).to.equal(0);
      expect(modifiedProductRevision3.documentData.index).to.equal(1);
    });
Exemplo n.º 25
0
    it("should not update variants' position", function () {
      sandbox.stub(Reaction, "hasPermission", () => true);
      const product1 = addProduct();
      const product2 = addProduct();
      const product3 = addProduct();

      expect(product1.index).to.be.undefined;
      expect(product2.index).to.be.undefined;
      expect(product3.index).to.be.undefined;

      Meteor.call("products/updateVariantsPosition", [
        product2._id, product3._id, product1._id
      ]);
      Meteor._sleepForMs(500);
      const modifiedProduct1 = Products.findOne(product1._id);
      const modifiedProduct2 = Products.findOne(product2._id);
      const modifiedProduct3 = Products.findOne(product3._id);
      expect(modifiedProduct1.index).to.be.undefined;
      expect(modifiedProduct2.index).to.be.undefined;
      expect(modifiedProduct3.index).to.be.undefined;
    });
Exemplo n.º 26
0
// TODO: Make better validations
// TODO: add owner
export default function () {
  Meteor.methods({
    'question.create'(
      _id,
      questionSeq,
      questionName,
      imageUrl,
      classId,
      response,
      component,
      competence) {

      check(questionName, String);
      check(_id, String);
      check(classId, String);
      check(response, Number);
      check(component, String);
      check(competence, String);
      check(imageUrl, String);
      check(questionSeq, Number);

      const createdAt = new Date();
      const question = {
        _id,
        questionSeq,
        questionName,
        imageUrl,
        createdAt,
        classId,
        response,
        component,
        competence
      };

      Meteor._sleepForMs(5000);
      Questions.insert(question);
    }
  });
}
Exemplo n.º 27
0
 it("should remove item from cart", function (done) {
   this.timeout(5000);
   const cart = Factory.create("cart");
   const cartUserId = cart.userId;
   sandbox.stub(Reaction, "getShopId", () => shop._id);
   sandbox.stub(Meteor, "userId", () => cartUserId);
   sandbox.stub(Meteor.server.method_handlers, "cart/resetShipmentMethod", function () {
     check(arguments, [Match.Any]);
   });
   sandbox.stub(Meteor.server.method_handlers, "shipping/updateShipmentQuotes", function () {
     check(arguments, [Match.Any]);
   });
   const updateSpy = sandbox.spy(Collections.Cart, "update");
   const cartFromCollection = Collections.Cart.findOne(cart._id);
   const cartItemId = cartFromCollection.items[0]._id;
   assert.equal(cartFromCollection.items.length, 2);
   Meteor.call("cart/removeFromCart", cartItemId);
   assert.equal(updateSpy.callCount, 1, "update should be called one time");
   Meteor._sleepForMs(1000);
   const updatedCart = Collections.Cart.findOne(cart._id);
   assert.equal(updatedCart.items.length, 1, "there should be one item left in cart");
   return done();
 });
Exemplo n.º 28
0
    it.skip("should publish variants' revision position", function () {
      sandbox.stub(Reaction, "hasPermission", () => true);
      const product1 = addProduct();
      const product2 = addProduct();
      const product3 = addProduct();

      expect(product1.index).to.be.undefined;
      expect(product2.index).to.be.undefined;
      expect(product3.index).to.be.undefined;

      Meteor.call("products/updateVariantsPosition", [
        product2._id, product3._id, product1._id
      ]);
      Meteor._sleepForMs(500);
      Meteor.publish("revisions/publish", [
        product1._id, product2._id, product3._id
      ]);
      const modifiedProduct1 = Products.findOne(product1._id);
      const modifiedProduct2 = Products.findOne(product2._id);
      const modifiedProduct3 = Products.findOne(product3._id);
      expect(modifiedProduct1.index).to.equal(2);
      expect(modifiedProduct2.index).to.equal(0);
      expect(modifiedProduct3.index).to.equal(1);
    });
Exemplo n.º 29
0
import { EJSON } from "meteor/ejson";
import { Jobs, Packages, Shops } from "/lib/collections";
import { Hooks, Logger } from "/server/api";
import ProcessJobs from "/server/jobs";
import { registerTemplate } from "./templates";
import { sendVerificationEmail } from "./accounts";
import { getMailUrl } from "./email/config";


export default {

  init() {
    // make sure the default shop has been created before going further
    while (!this.getShopId()) {
      Logger.warn("No shopId, waiting one second...");
      Meteor._sleepForMs(1000);
    }

    // run onCoreInit hooks
    Hooks.Events.run("onCoreInit");

    // start job server
    Jobs.startJobServer(() => {
      Logger.info("JobServer started");
      ProcessJobs();
      Hooks.Events.run("onJobServerStart");
    });
    if (process.env.VERBOSE_JOBS) {
      Jobs.setLogStream(process.stdout);
    }
Exemplo n.º 30
0
import {SimpleSchema} from 'meteor/aldeed:simple-schema';
import {CallPromiseMixin} from 'meteor/didericis:callpromise-mixin';
import {_} from 'meteor/erasaur:meteor-lodash';
import {moment} from  'meteor/momentjs:moment';

// Collection
import {Company} from '../../../../core/imports/api/collections/company.js';
import {Customer} from '../../../imports/api/collections/customer.js';

export const customerReport = new ValidatedMethod({
    name: 'pos.customerReport',
    mixins: [CallPromiseMixin],
    validate: null,
    run(params) {
        if (!this.isSimulation) {
            Meteor._sleepForMs(2000);

            let data = {
                title: {},
                header: {},
                content: [{index: 'No Result'}],
                footer: {}
            };

            // let date = _.trim(_.words(params.date, /[^To]+/g));
            let branch = params.branch;
            let name = params.name;
            let date = params.repDate;
            let fDate = moment(date[0]).toDate();
            let tDate = moment(date[1]).add(1, 'days').toDate();