"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
var _require = require('bson'),
  ObjectId = _require.ObjectId;
var ROLES = require('../constant/core/roles.constant');
var Family = require('../model/chemical/family');
var Helper = require('./permission.helper');
describe('Permission Helper', function () {
  var hannah = {
    userId: 'VUN8MDN8aGFwZXJlekB1Y2RhdmlzLmVkdQ',
    firstName: 'Hannah',
    lastName: 'Perez',
    tenantCode: 'UC',
    campusCode: '03',
    email: 'haperez@ucdavis.edu',
    roles: [{
      role: ROLES.RESPONSIBLE_PERSON,
      campusCode: '03'
    }, {
      role: ROLES.CHEMICAL_INFORMATICS,
      campusCode: null
    }, {
      role: ROLES.CONTROL_AREA_ADMIN,
      campusCode: '03'
    }],
    groups: [{
      id: 'dee70836-ab40-4437-b055-2cfeaac666f1',
      name: 'Team Purple',
      owner: {
        userId: 'VUN8MDN8aGFwZXJlekB1Y2RhdmlzLmVkdQ',
        campusCode: '03'
      },
      // Hannah
      roles: [ROLES.RESPONSIBLE_PERSON],
      colleagues: [{
        id: 'a21307f6-c584-46af-aa30-bffa956f6bff'
      }]
    }, {
      id: 'c9030912-0516-4963-abbb-b1276a418932',
      name: 'test group',
      owner: {
        userId: 'VUN8MDN8Y2NhcmNhbW9AdWNkYXZpcy5lZHU',
        campusCode: '03'
      },
      // Carcamo
      roles: [ROLES.DELEGATE, ROLES.AUTHORIZED_USER],
      colleagues: []
    }, {
      id: '6e080815-10ea-487e-9c44-44356508fefc',
      name: 'IT Serv Developers',
      owner: {
        userId: 'VUN8MDN8cHJhZGVlcGhAdWNkYXZpcy5lZHU',
        campusCode: '03'
      },
      // Pradeep
      roles: [ROLES.AUTHORIZED_USER, ROLES.LAB_MANAGER],
      colleagues: []
    }, {
      id: '18bcf5f2-efb5-4d23-8ff5-5969f0b538f4',
      name: 'Shaw Lab',
      owner: {
        userId: 'VUN8MDN8anRzaGF3QHVjZGF2aXMuZWR1',
        campusCode: '03'
      },
      // Jared Shaw
      roles: [ROLES.DELEGATE, ROLES.AUTHORIZED_USER],
      colleagues: []
    }, {
      id: 'a21307f6-c584-46af-aa30-bffa956f6bff',
      name: 'Demo Lab',
      owner: {
        userId: 'VUN8MDN8aGFwZXJlekB1Y2RhdmlzLmVkdQ',
        firstName: 'Hannah',
        lastName: 'Perez',
        tenantCode: null,
        campusCode: '03'
      },
      roles: [ROLES.RESPONSIBLE_PERSON, ROLES.LAB_MANAGER, ROLES.DELEGATE]
    }]
  };
  var inventory = {
    _id: new ObjectId('5adf97597ed8203054035908'),
    tenantCode: 'UC',
    campusCode: '03',
    colleagues: [{
      _id: new ObjectId('5adf975a7ed820305403590c'),
      tenantCode: 'UC',
      campusCode: null,
      name: 'test group'
    }, {
      _id: new ObjectId('5adf975a7ed8203054035914'),
      tenantCode: 'UC',
      campusCode: null,
      name: "Sydney's Group"
    }, {
      _id: new ObjectId('5adf975a7ed8203054035912'),
      tenantCode: 'UC',
      campusCode: '03',
      name: "Christine's Test Group"
    }, {
      _id: new ObjectId('5adf975a7ed8203054035912'),
      tenantCode: 'UC',
      campusCode: '03',
      name: "Christine's Test Group"
    }, {
      _id: new ObjectId('5adf975a7ed820305403590e'),
      tenantCode: null,
      campusCode: '03',
      name: "Ben's Test Group 2"
    }, {
      _id: new ObjectId('5adf975a7ed820305403590e'),
      tenantCode: null,
      campusCode: '03',
      name: "Ben's Test Group 2"
    }],
    groups: [{
      id: 'a21307f6-c584-46af-aa30-bffa956f6bff',
      name: 'Demo Lab',
      owner: {
        userId: 'VUN8MDN8aGFwZXJlekB1Y2RhdmlzLmVkdQ',
        firstName: 'Hannah',
        lastName: 'Perez',
        tenantCode: null,
        campusCode: '03'
      }
    }],
    name: 'Demo Lab',
    owner: {
      userId: 'VUN8MDN8aGFwZXJlekB1Y2RhdmlzLmVkdQ',
      firstName: 'Hannah',
      lastName: 'Perez',
      tenantCode: null,
      campusCode: '03'
    },
    tags: ['ACS Grade', 'Enzymes', 'Antibiotic', 'Chem 118', 'Chem2B', 'acid', 'pyrophoric', 'chem', "John's Chemicals", 'carbon', "Diana's Chemicals", 'Test', 'awesome', 'TEst 2']
  };
  var admin = {
    userId: 'TEST_ID',
    firstName: 'Chem',
    lastName: 'Admin',
    tenantCode: 'UC',
    campusCode: '03',
    email: 'chem_admin@ucdavis.edu',
    roles: [{
      role: ROLES.CHEMICAL_ADMIN,
      campusCode: '03'
    }, {
      role: 'Safety Coordinator',
      campusCode: '03',
      groupIds: ['a21307f6-c584-46af-aa30-bffa956f6bff']
    }],
    groups: []
  };
  var readOnlyUser = {
    userId: 'sc',
    firstName: 'safety',
    lastName: 'co',
    tenantCode: 'UC',
    campusCode: '03',
    email: 'safety_co@ucdavis.edu',
    roles: [{
      role: 'Safety Coordinator',
      campusCode: '03',
      groupIds: ['a21307f6-c584-46af-aa30-bffa956f6bff']
    }],
    groups: []
  };
  it('should have read access to container if member of group', function () {
    var container = {
      inventory: inventory,
      isPrivate: false
    };
    expect(Helper.hasReadAccessToContainer(container, _objectSpread(_objectSpread({}, hannah), {}, {
      inventories: [inventory]
    }))).toBeTruthy();
  });
  it('should have read access to container if colleagues of group', function () {
    var container = {
      inventory: inventory,
      isPrivate: false
    };
    expect(Helper.hasReadAccessToContainer(container, _objectSpread(_objectSpread({}, hannah), {}, {
      inventories: [inventory]
    }))).toBeTruthy();
  });
  it('should not have read access to container if colleagues of group and container is private', function () {
    var container = {
      inventory: {
        _id: hannah.groups[0].colleagues[0].id,
        campusCode: '03'
      },
      isPrivate: true
    };
    expect(Helper.hasReadAccessToContainer(container, hannah)).toBeFalsy();
  });
  it('should have read access if chemical admin and container belongs to the same campus', function () {
    var container = {
      inventory: inventory,
      isPrivate: false
    };
    expect(Helper.hasReadAccessToContainer(container, _objectSpread(_objectSpread({}, hannah), {}, {
      inventories: [inventory]
    }))).toBeTruthy();
  });
  it('should not have read access if chemical admin and container belongs to a different campus', function () {
    var container = {
      inventory: inventory,
      isPrivate: false
    };
    var user = {
      roles: [{
        role: ROLES.CHEMICAL_ADMIN,
        campusCode: '06'
      }],
      groups: []
    };
    expect(Helper.hasWriteAccessToContainer(container, _objectSpread(_objectSpread({}, user), {}, {
      inventories: []
    }))).toBeFalsy();
  });
  it('should have write access to container is member of Inventory', function () {
    var container = {
      inventory: inventory,
      isPrivate: false
    };
    expect(Helper.hasWriteAccessToContainer(container, _objectSpread(_objectSpread({}, hannah), {}, {
      inventories: [inventory]
    }))).toBeTruthy();
  });
  it('should not have write access to container is colleagues of Inventory', function () {
    var container = {
      inventory: _objectSpread(_objectSpread({}, inventory), {}, {
        _id: 'nope'
      }),
      isPrivate: false
    };
    expect(Helper.hasWriteAccessToContainer(container, _objectSpread(_objectSpread({}, hannah), {}, {
      inventories: [inventory]
    }))).toBeFalsy();
  });
  it('should be member of Inventory', function () {
    expect(Helper.isMemberOfInventory(inventory, hannah)).toBeTruthy();
  });
  it('should be colleage of Inventory', function () {
    var colleague = _objectSpread(_objectSpread({}, inventory), {}, {
      colleagues: [].concat(_toConsumableArray(inventory.colleagues), [{
        _id: inventory._id
      }])
    });
    expect(Helper.isMemberOrColleagueOfInventory(colleague, _objectSpread(_objectSpread({}, hannah), {}, {
      inventories: [inventory]
    }))).toBeTruthy();
  });
  it('should have manage access to Inventory if Delegate of Inventory', function () {
    var user = _objectSpread(_objectSpread({}, hannah), {}, {
      groups: [{
        id: 'a21307f6-c584-46af-aa30-bffa956f6bff',
        isDelegate: true
      }]
    });
    expect(Helper.isGroupDelegate(inventory, user)).toBeTruthy();
  });
  it('should have manage access to Inventory if Lab Manager of Inventory', function () {
    expect(Helper.hasManageAccessToInventory(inventory, hannah)).toBeTruthy();
  });
  it('should have manage access to Inventory if group owner', function () {
    var user = _objectSpread(_objectSpread({}, hannah), {}, {
      groups: [{
        id: 'a21307f6-c584-46af-aa30-bffa956f6bff',
        name: 'Demo Lab',
        owner: {
          userId: 'VUN8MDN8aGFwZXJlekB1Y2RhdmlzLmVkdQ'
        }
      }]
    });
    expect(Helper.isGroupOwner(inventory, user)).toBeTruthy();
  });
  it('should not allow chem admin from a different campus', function () {
    var marsAdmin = {
      tenantCode: 'MMM',
      campusCode: 'MARS',
      roles: [{
        role: ROLES.CHEMICAL_ADMIN,
        tenantCode: 'MMM',
        campusCode: 'MARS'
      }],
      groups: []
    };
    expect(Helper.hasReadAccessToInventory(inventory, marsAdmin)).toBeFalsy();
  });
  it('should have write access to family if family is owned by inventory', function () {
    var family = new Family({
      scope: 'INVENTORY',
      group: hannah.groups[0]
    });
    expect(Helper.hasWriteAccessToFamily(family, hannah)).toBeTruthy();
  });
  it('should not have write access to family if family is not novel', function () {
    var family = new Family();
    expect(Helper.hasWriteAccessToFamily(family, _objectSpread(_objectSpread({}, hannah), {}, {
      roles: []
    }))).toEqual(false);
  });
  it('should have write access to family if Chem Info', function () {
    var family = new Family();
    var chemInfo = {
      userId: 'CHEMINFO',
      firstName: 'Chem',
      lastName: 'Info',
      campusCode: '03',
      email: 'chem_info@ucdavis.edu',
      roles: [{
        role: ROLES.CHEMICAL_INFORMATICS,
        campusCode: null
      }],
      groups: []
    };
    expect(Helper.hasWriteAccessToFamily(family, chemInfo)).toEqual(true);
  });
  it('should return true if Chem Admin for person campus', function () {
    expect(Helper.isChemAdmin(admin.campusCode, admin)).toBeTruthy();
  });
  it('should return false if not Chem Admin for person campus', function () {
    expect(Helper.isChemAdmin(hannah.campusCode, hannah)).toBeFalsy();
  });
  it('should return true if has read only role to inventory', function () {
    expect(Helper.hasRoleWithReadAccessToInventory(inventory, readOnlyUser)).toBeTruthy();
  });
  it('should return false if does not have read only role to inventory', function () {
    expect(Helper.hasRoleWithReadAccessToInventory(inventory, admin)).toBeFalsy();
  });
  it('should return true if has Read access to inventory', function () {
    expect(Helper.hasRoleWithReadAccessToInventory(inventory, readOnlyUser)).toBeTruthy();
  });
  it('should return false if a chem admin for a different campus than inventory', function () {
    var marsAdmin = {
      tenantCode: 'MMM',
      campusCode: 'MARS',
      roles: [{
        role: ROLES.CHEMICAL_ADMIN,
        tenantCode: 'MMM',
        campusCode: 'MARS'
      }],
      groups: []
    };
    expect(Helper.hasRoleWithReadAccessToInventory(inventory, marsAdmin)).toBeFalsy();
  });
  it('should return true if has role', function () {
    expect(Helper.hasRole(hannah, ROLES.RESPONSIBLE_PERSON)).toBeTruthy();
  });
  it('should return false if does not have role', function () {
    expect(Helper.hasRole(hannah, ROLES.PROCEDURES_ADMIN)).toBeFalsy();
  });
  it('should have read access to library if chem admin', function () {
    var user = {
      userId: 'userid',
      roles: [{
        role: ROLES.CHEMICAL_ADMIN,
        tenantCode: null,
        campusCode: '03',
        types: null
      }],
      groups: [],
      campusCode: '03'
    };
    expect(Helper.hasReadAccessToLibrary(user)).toBeTruthy();
  });
  it('should have read access to library if control area admin', function () {
    var user = {
      userId: 'userid',
      roles: [{
        role: ROLES.CONTROL_AREA_ADMIN,
        tenantCode: null,
        campusCode: '03',
        types: null
      }],
      groups: [],
      campusCode: '03'
    };
    expect(Helper.hasReadAccessToLibrary(user)).toBeTruthy();
  });
  it('should have read access to library', function () {
    expect(Helper.hasReadAccessToLibrary(hannah)).toBeTruthy();
  });
  it('should have write access to library', function () {
    expect(Helper.hasWriteAccessToLibrary(hannah)).toBeTruthy();
  });
  it('should have read access to control area', function () {
    var controlArea = {
      name: 'control area 1',
      campusCode: '03',
      tenantCode: 'UC'
    };
    expect(Helper.hasReadAccessToControlArea(hannah, controlArea)).toBeTruthy();
  });
  it('should have read access to control area as a Chem Admin', function () {
    var controlArea = {
      name: 'control area 1',
      campusCode: '03',
      tenantCode: 'UC'
    };
    expect(Helper.hasReadAccessToControlArea(admin, controlArea)).toBeTruthy();
  });
  it('should have write access to control area', function () {
    var controlArea = {
      name: 'control area 1',
      campusCode: '03',
      tenantCode: 'UC'
    };
    expect(Helper.hasWriteAccessToControlArea(hannah, controlArea)).toBeTruthy();
  });
});