import { Meteor } from 'meteor/meteor'; import { Mongo } from 'meteor/mongo'; import { check } from 'meteor/check'; import {SimpleSchema} from 'meteor/aldeed:simple-schema'; Sales = new Mongo.Collection('Sales'); let SalesSchema = new SimpleSchema({ date: { type: Date, label: "Date", optional: false, index: 1 }, amount: { type: Number, label: "Amount", optional: false, decimal: true }, price: { type: Number, label: "Price", optional: false, min: 0, exclusiveMin: true, decimal: true }, measureId: { type: String, label: "Measure Id", trim: false, regEx: SimpleSchema.RegEx.Id, index: 1 }, productId: { type: String, label: "Product Id", trim: false, regEx: SimpleSchema.RegEx.Id, index: 1 }, venueId: { type: String, label: "Vendor Id", trim: false, regEx: SimpleSchema.RegEx.Id, index: 1 // autoform: { // type: 'relation', // settings: { // collection: 'Venues', // fields: ['name'] // } // } }, createdAt: { type: Date, label: "Created On", optional: false } }); Sales.attachSchema(SalesSchema); if(Meteor.isServer) { Meteor.publish('sales', function(query, limit = 100, skipCount) { let dbQuery = []; if(query) { // _.each(_.keys(query), function(key) { // if(_.isObject(query[key])) dbQuery[key] = query[key]; // else if(_.isNumber(query[key])) dbQuery[key] = query[key]; // else dbQuery[key] = {$regex: RegExp.escape(query[key]), $options: 'i'}; // }); _.each(_.keys(query), function(key) { if(_.isObject(query[key])) dbQuery.push({[key]: query[key]}); else if(_.isNumber(query[key])) dbQuery.push({[key]: query[key]}); else { let searchValue = query[key]; let searches = searchValue && searchValue.length > 0 ? searchValue.split(/\s+/) : undefined; for(let search of searches) { dbQuery.push({[key]: {$regex: '\\b' + search, $options: 'i'}}); } } }); } if(!_.isNumber(limit)) limit = 100; if(!_.isNumber(skipCount) || skipCount < 0) skipCount = 0; dbQuery = dbQuery.length > 0 ? {$and: dbQuery} : {}; return Meteor.collections.Sales.find(dbQuery, {limit: limit, sort: {date: -1, createdAt: -1}, skip: skipCount}); }); Meteor.methods({ getSalesCount: function(query) { //TODO: Validate the query? return Sales.find(query).count(); }, insertSale: function(sale) { //TODO: Check the structure of sale. Use: check(sale, {name: String, ...}); sale.createdAt = new Date(); if(Roles.userIsInRole(this.userId, [Meteor.UserRoles.ROLE_UPDATE])) { Sales.insert(sale, function(err, id) { if(err) console.log(err); }); } else throw new Meteor.Error(403, "Not authorized."); }, deleteSale: function(id) { check(id, String); if(Roles.userIsInRole(this.userId, [Meteor.UserRoles.ROLE_UPDATE])) { Sales.remove(id); } else throw new Meteor.Error(403, "Not authorized."); } }); } //Allows the client to do DB interaction without calling server side methods, while still retaining control over whether the user can make changes. Sales.allow({ insert: function() {return false;}, update: function() {return false;}, remove: function() {return false;} }); export default Sales;