index.js 2.52 KB
// import { Orgs }                           from '/imports/collections/orgs/index';

import _                                  from 'lodash';
import { Mongo }                          from 'meteor/mongo';
import { SimpleSchema }                   from 'meteor/aldeed:simple-schema';

import { Users }                          from '/imports/collections/users/index';

class Org {
  constructor(doc) {
    _.assign(this, doc);
  };

  getUserIds() {
    return _.filter(_.map(this.users, 'userId'));
  };

  getInvitationIds() {
    return _.filter(_.map(this.users, 'invitationId'));
  };

  areDetailsDone() {
    return (
      this.name && this.name.length &&
      this.shortCode && this.shortCode.length &&
      this.acn && this.acn.length
    );
  };

  ifCurrentUserIsAdmin(){
    const user = Users.current();
    if(!user) return null;
    for(let i = 0; i < this.users.length; ++i) {
      if(
          (this.users[i].role == "SECRETARY")
          && this.users[i].userId == user._id
        ) {
         return true;
      }
    }
    return false;
  }


};
export { Org };

class OrgsCollection extends Mongo.Collection {
  insert(item, callback) {
    _.assign(item, {
      createdAt:        new Date().getTime(),
    });
    return super.insert(item, callback);
  };
};

export const Orgs = new OrgsCollection('Orgs', {
  transform: (item) => {
    return new Org(item);
  },
});

_.assign(Orgs, {
  allOrgsCurrentUser: () => {
    const user = Users.current();
    if(!user) return null;
    return Orgs.find({'users.userId': user._id});
  },
  current: () => {
    const user = Users.current();
    if(!user) return null;
    return Orgs.findOne({_id: user.orgId});
  },
  currentOrgUsers: () => {
    const OrgsArr = Orgs.current();
    if(!OrgsArr) return null;
    return OrgsArr.users;
  },

});

Orgs.deny({
  insert() { return true; },
  update() { return true; },
  remove() { return true; },
});

Orgs.schema = new SimpleSchema({

  name:             { type: String, },
  slug:             { type: String, optional: true},
  address:          { type: String, optional: true},
  users: {
    type: [new SimpleSchema({
      userId:           { type: String, optional: true},
      invitationId:     { type: String, optional: true},
      role:             { type: String, },
      email:            { type: String, optional: true},
    })],
  },
  createdAt:            { type: Date, autoValue: function(){return new Date();}},

});



Orgs.attachSchema(Orgs.schema);

Orgs.publicFields = {
  name:           1,
  slug:           1,
  createdAt:      1,
};