/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "dist/";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ({

/***/ "./config/index.js":
/*!*************************!*\
  !*** ./config/index.js ***!
  \*************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! path */ "path");
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var dotenv__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! dotenv */ "dotenv");
/* harmony import */ var dotenv__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(dotenv__WEBPACK_IMPORTED_MODULE_1__);



dotenv__WEBPACK_IMPORTED_MODULE_1___default.a.config({
  path: path__WEBPACK_IMPORTED_MODULE_0___default.a.resolve(process.cwd(), '.env.test') });

/***/ }),

/***/ "./knexfile.js":
/*!*********************!*\
  !*** ./knexfile.js ***!
  \*********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(/*! dotenv */ "dotenv").config();

var MIGRATIONS_DIR = './src/database/migrations';
var SEEDS_DIR = './src/database/seeds';

module.exports = {
  test: {
    client: process.env.DB_CLIENT,
    migrations: {
      directory: MIGRATIONS_DIR },

    connection: {
      host: process.env.DB_HOST,
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_NAME,
      charset: 'utf8' } },


  development: {
    client: process.env.DB_CLIENT,
    connection: {
      host: process.env.DB_HOST,
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_NAME,
      charset: 'utf8' },

    migrations: {
      directory: MIGRATIONS_DIR },

    seeds: {
      directory: SEEDS_DIR } },


  production: {
    client: process.env.DB_CLIENT,
    connection: {
      host: process.env.DB_HOST,
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_NAME,
      charset: 'utf8' },

    migrations: {
      directory: MIGRATIONS_DIR },

    seeds: {
      directory: SEEDS_DIR } } };

/***/ }),

/***/ "./src/app.js":
/*!********************!*\
  !*** ./src/app.js ***!
  \********************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var helmet__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! helmet */ "helmet");
/* harmony import */ var helmet__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(helmet__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var express_boom__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! express-boom */ "express-boom");
/* harmony import */ var express_boom__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(express_boom__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var i18n__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! i18n */ "i18n");
/* harmony import */ var i18n__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(i18n__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../config */ "./config/index.js");
/* harmony import */ var _http__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/http */ "./src/http/index.js");
/* harmony import */ var _models__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/models */ "./src/models/index.js");








var app = express__WEBPACK_IMPORTED_MODULE_0___default()();

// i18n.configure({
//   // setup some locales - other locales default to en silently
//   locales: ['en'],

//   // sets a custom cookie name to parse locale settings from.
//   cookie: 'yourcookiename',

//   // where to store json files - defaults to './locales'
//   directory: `${__dirname}/resources/locale`,
// });

// i18n init parses req for language headers, cookies, etc.
// app.use(i18n.init);

// Express configuration
app.set('port', process.env.PORT || 3000);

app.use(helmet__WEBPACK_IMPORTED_MODULE_1___default()());
app.use(express_boom__WEBPACK_IMPORTED_MODULE_2___default()());
app.use(express__WEBPACK_IMPORTED_MODULE_0___default.a.json());

Object(_http__WEBPACK_IMPORTED_MODULE_5__["default"])(app);

/* harmony default export */ __webpack_exports__["default"] = (app);

/***/ }),

/***/ "./src/collection/BudgetEntriesSet.js":
/*!********************************************!*\
  !*** ./src/collection/BudgetEntriesSet.js ***!
  \********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return BudgetEntriesSet; });
/* harmony import */ var _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/toConsumableArray */ "@babel/runtime/helpers/toConsumableArray");
/* harmony import */ var _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__);
var

BudgetEntriesSet = /*#__PURE__*/function () {

  function BudgetEntriesSet() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default()(this, BudgetEntriesSet);
    this.accounts = {};
    this.totalSummary = {};
    this.orderSize = null;
  }_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(BudgetEntriesSet, [{ key: "setZeroPlaceholder", value: function setZeroPlaceholder()

    {var _this = this;
      if (!this.orderSize) {return;}

      Object.values(this.accounts).forEach(function (account) {

        for (var i = 0; i <= _this.orderSize.length; i++) {
          if (typeof account[i] === 'undefined') {
            account[i] = { amount: 0 };
          }
        }
      });
    } }, { key: "toArray", value: function toArray()















    {var _this2 = this;
      var output = [];

      Object.key(this.accounts).forEach(function (accountId) {
        var entries = _this2.accounts[accountId];
        output.push({
          account_id: accountId,
          entries: _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0___default()(
          Object.key(entries).map(function (order) {
            var entry = entries[order];
            return {
              order: order,
              amount: entry.amount };

          })) });


      });
    } }, { key: "calcTotalSummary", value: function calcTotalSummary()

    {var _this3 = this;
      var totalSummary = {};var _loop = function _loop(

      i) {
        Object.value(_this3.accounts).forEach(function (account) {
          if (typeof totalSummary[i] !== 'undefined') {
            totalSummary[i] = { amount: 0, order: i };
          }
          totalSummary[i].amount += account[i].amount;
        });};for (var i = 0; i < this.orderSize.length; i++) {_loop(i);
      }
      this.totalSummary = totalSummary;
    } }, { key: "toArrayTotalSummary", value: function toArrayTotalSummary()

    {
      return Object.values(this.totalSummary);
    } }], [{ key: "from", value: function from(accounts, configs) {var _this4 = this;var collection = new this(configs);accounts.forEach(function (entry) {if (typeof _this4.accounts[entry.accountId] === 'undefined') {collection.accounts[entry.accountId] = {};}if (entry.order) {collection.accounts[entry.accountId][entry.order] = entry;}});return collection;} }]);return BudgetEntriesSet;}();

/***/ }),

/***/ "./src/collection/NestedSet/index.js":
/*!*******************************************!*\
  !*** ./src/collection/NestedSet/index.js ***!
  \*******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return NestedSet; });
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__);
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}var
NestedSet = /*#__PURE__*/function () {
  /**
                                       * Constructor method.
                                       * @param {Object} options -
                                       */
  function NestedSet(items, options) {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default()(this, NestedSet);
    this.options = _objectSpread({
      parentId: 'parent_id',
      id: 'id' },
    options);

    this.items = items;
    this.collection = {};
  }

  /**
     * Link nodes children.
     */_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(NestedSet, [{ key: "linkChildren", value: function linkChildren()
    {var _this = this;
      if (this.items.length <= 0) return false;

      var map = {};
      this.items.forEach(function (item) {
        map[item.id] = item;
        map[item.id].children = [];
      });

      this.items.forEach(function (item) {
        var parentNodeId = item[_this.options.parentId];
        if (parentNodeId) {
          map[parentNodeId].children.push(item);
        }
      });
      return map;
    } }, { key: "toTree", value: function toTree()

    {var _this2 = this;
      var map = this.linkChildren();
      var tree = {};

      this.items.forEach(function (item) {
        var parentNodeId = item[_this2.options.parentId];
        if (!parentNodeId) {
          tree[item.id] = map[item.id];
        }
      });
      this.collection = Object.values(tree);
      return this.collection;
    } }, { key: "getTree", value: function getTree()

    {
      return this.collection;
    } }, { key: "flattenTree", value: function flattenTree(

    nodeMapper) {
      var flattenTree = [];

      var traversal = function traversal(nodes, parentNode) {
        nodes.forEach(function (node) {
          var nodeMapped = node;

          if (typeof nodeMapper === 'function') {
            nodeMapped = nodeMapper(nodeMapped, parentNode);
          }
          flattenTree.push(nodeMapped);

          if (node.children && node.children.length > 0) {
            traversal(node.children, node);
          }
        });
      };
      traversal(this.collection);

      return flattenTree;
    } }]);return NestedSet;}();

/***/ }),

/***/ "./src/collection/ResourceFieldMetadataCollection.js":
/*!***********************************************************!*\
  !*** ./src/collection/ResourceFieldMetadataCollection.js ***!
  \***********************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ResourceFieldMetadataCollection; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _lib_Metable_MetableCollection__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/lib/Metable/MetableCollection */ "./src/lib/Metable/MetableCollection.js");
/* harmony import */ var _models_ResourceFieldMetadata__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/models/ResourceFieldMetadata */ "./src/models/ResourceFieldMetadata.js");

var

ResourceFieldMetadataCollection = /*#__PURE__*/function (_MetableCollection) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_3___default()(ResourceFieldMetadataCollection, _MetableCollection);
  /**
                                                                                                                                               * Constructor method.
                                                                                                                                               */
  function ResourceFieldMetadataCollection() {var _this;_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, ResourceFieldMetadataCollection);
    _this = _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_1___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_2___default()(ResourceFieldMetadataCollection).call(this));

    _this.setModel(_models_ResourceFieldMetadata__WEBPACK_IMPORTED_MODULE_5__["default"]);
    _this.extraColumns = ['resource_id', 'resource_item_id'];return _this;
  }return ResourceFieldMetadataCollection;}(_lib_Metable_MetableCollection__WEBPACK_IMPORTED_MODULE_4__["default"]);

/***/ }),

/***/ "./src/data/ResourceFieldsKeys.js":
/*!****************************************!*\
  !*** ./src/data/ResourceFieldsKeys.js ***!
  \****************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);

/* harmony default export */ __webpack_exports__["default"] = ({
  "expense_account": 'expense_account_id',
  "payment_account": 'payment_account_id',
  "account_type": "account_type_id" });

/***/ }),

/***/ "./src/database/knex.js":
/*!******************************!*\
  !*** ./src/database/knex.js ***!
  \******************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var knex__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! knex */ "knex");
/* harmony import */ var knex__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(knex__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! objection */ "objection");
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(objection__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _knexfile__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @/../knexfile */ "./knexfile.js");
/* harmony import */ var _knexfile__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_knexfile__WEBPACK_IMPORTED_MODULE_3__);
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}



var config = _knexfile__WEBPACK_IMPORTED_MODULE_3___default.a["development"];
var knex = knex__WEBPACK_IMPORTED_MODULE_1___default()(_objectSpread({},
config, {},
Object(objection__WEBPACK_IMPORTED_MODULE_2__["knexSnakeCaseMappers"])({ upperCase: true })));


/* harmony default export */ __webpack_exports__["default"] = (knex);

/***/ }),

/***/ "./src/http/controllers/AccountOpeningBalance.js":
/*!*******************************************************!*\
  !*** ./src/http/controllers/AccountOpeningBalance.js ***!
  \*******************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! express-validator */ "express-validator");
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(express_validator__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! lodash */ "lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! moment */ "moment");
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(moment__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../middleware/asyncMiddleware */ "./src/http/middleware/asyncMiddleware.js");
/* harmony import */ var _http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/http/middleware/jwtAuth */ "./src/http/middleware/jwtAuth.js");
/* harmony import */ var _models_Account__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/models/Account */ "./src/models/Account.js");
/* harmony import */ var _services_Accounting_JournalPoster__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/services/Accounting/JournalPoster */ "./src/services/Accounting/JournalPoster.js");
/* harmony import */ var _services_Accounting_JournalEntry__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/services/Accounting/JournalEntry */ "./src/services/Accounting/JournalEntry.js");
/* harmony import */ var _models_ManualJournal__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/models/ManualJournal */ "./src/models/ManualJournal.js");
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}










/* harmony default export */ __webpack_exports__["default"] = ({
  /**
                  * Router constructor.
                  */
  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_3___default.a.Router();

    router.use(_http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_8__["default"]);

    router.post('/',
    this.openingBalnace.validation,
    Object(_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__["default"])(this.openingBalnace.handler));

    return router;
  },

  /**
      * Opening balance to the given account.
      * @param {Request} req -
      * @param {Response} res -
      */
  openingBalnace: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('date').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('note').optional().trim().escape(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('balance_adjustment_account').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('accounts').isArray({ min: 1 }),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('accounts.*.id').exists().isInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["oneOf"])([
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('accounts.*.debit').exists().isNumeric().toFloat(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('accounts.*.credit').exists().isNumeric().toFloat()])],


    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(req, res) {var validationErrors, accounts, user, form, date, accountsIds, storedAccounts, accountsCollection, accountsStoredIds, notFoundAccountsIds, errorReasons, ids, account, journalEntries, trial, entryModel, manualJournal;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context.next = 3;break;}return _context.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:



                accounts = req.body.accounts;
                user = req.user;
                form = _objectSpread({}, req.body);
                date = moment__WEBPACK_IMPORTED_MODULE_6___default()(form.date).format('YYYY-MM-DD');

                accountsIds = accounts.map(function (account) {return account.id;});_context.next = 10;return (
                  _models_Account__WEBPACK_IMPORTED_MODULE_9__["default"].query().
                  select(['id']).whereIn('id', accountsIds).
                  withGraphFetched('type'));case 10:storedAccounts = _context.sent;

                accountsCollection = new Map(storedAccounts.map(function (i) {return [i.id, i];}));

                // Get the stored accounts Ids and difference with submit accounts.
                accountsStoredIds = storedAccounts.map(function (account) {return account.id;});
                notFoundAccountsIds = Object(lodash__WEBPACK_IMPORTED_MODULE_5__["difference"])(accountsIds, accountsStoredIds);
                errorReasons = [];

                if (notFoundAccountsIds.length > 0) {
                  ids = notFoundAccountsIds.map(function (a) {return parseInt(a, 10);});
                  errorReasons.push({ type: 'NOT_FOUND_ACCOUNT', code: 100, ids: ids });
                }if (!
                form.balance_adjustment_account) {_context.next = 21;break;}_context.next = 19;return (
                  _models_Account__WEBPACK_IMPORTED_MODULE_9__["default"].query().findById(form.balance_adjustment_account));case 19:account = _context.sent;

                if (!account) {
                  errorReasons.push({ type: 'BALANCE.ADJUSTMENT.ACCOUNT.NOT.EXIST', code: 300 });
                }case 21:if (!(

                errorReasons.length > 0)) {_context.next = 23;break;}return _context.abrupt("return",
                res.boom.badData(null, { errors: errorReasons }));case 23:


                journalEntries = new _services_Accounting_JournalPoster__WEBPACK_IMPORTED_MODULE_10__["default"]();

                accounts.forEach(function (account) {
                  var storedAccount = accountsCollection.get(account.id);

                  // Can't continue in case the stored account was not found.
                  if (!storedAccount) {return;}

                  var entryModel = new _services_Accounting_JournalEntry__WEBPACK_IMPORTED_MODULE_11__["default"]({
                    referenceType: 'OpeningBalance',
                    account: account.id,
                    accountNormal: storedAccount.type.normal,
                    userId: user.id });

                  if (account.credit) {
                    entryModel.entry.credit = account.credit;
                    journalEntries.credit(entryModel);
                  } else if (account.debit) {
                    entryModel.entry.debit = account.debit;
                    journalEntries.debit(entryModel);
                  }
                });
                // Calculates the credit and debit balance of stacked entries.
                trial = journalEntries.getTrialBalance();

                if (trial.credit !== trial.debit) {
                  entryModel = new _services_Accounting_JournalEntry__WEBPACK_IMPORTED_MODULE_11__["default"]({
                    referenceType: 'OpeningBalance',
                    account: form.balance_adjustment_account,
                    accountNormal: 'credit',
                    userId: user.id });


                  if (trial.credit > trial.debit) {
                    entryModel.entry.credit = Math.abs(trial.credit);
                    journalEntries.credit(entryModel);

                  } else if (trial.credit < trial.debit) {
                    entryModel.entry.debit = Math.abs(trial.debit);
                    journalEntries.debit(entryModel);
                  }
                }_context.next = 29;return (
                  _models_ManualJournal__WEBPACK_IMPORTED_MODULE_12__["default"].query().insert({
                    amount: Math.max(trial.credit, trial.debit),
                    transaction_type: 'OpeningBalance',
                    date: date,
                    note: form.note,
                    user_id: user.id }));case 29:manualJournal = _context.sent;


                journalEntries.entries = journalEntries.entries.map(function (entry) {return _objectSpread({},
                  entry, {
                    referenceId: manualJournal.id });});_context.next = 33;return (

                  Promise.all([
                  journalEntries.saveEntries(),
                  journalEntries.saveBalance()]));case 33:return _context.abrupt("return",

                res.status(200).send({ id: manualJournal.id }));case 34:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() } });

/***/ }),

/***/ "./src/http/controllers/AccountTypes.js":
/*!**********************************************!*\
  !*** ./src/http/controllers/AccountTypes.js ***!
  \**********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @/http/middleware/jwtAuth */ "./src/http/middleware/jwtAuth.js");
/* harmony import */ var _http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/http/middleware/asyncMiddleware */ "./src/http/middleware/asyncMiddleware.js");
/* harmony import */ var _models_AccountType__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/models/AccountType */ "./src/models/AccountType.js");





/* harmony default export */ __webpack_exports__["default"] = ({
  /**
                  * Router constructor.
                  */
  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_2___default.a.Router();
    router.use(_http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_3__["default"]);

    router.get('/',
    this.getAccountTypesList.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_4__["default"])(this.getAccountTypesList.handler));

    return router;
  },

  /**
      * Retrieve accounts types list.
      */
  getAccountTypesList: {
    validation: [],
    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(req, res) {var accountTypes;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:_context.next = 2;return (
                  _models_AccountType__WEBPACK_IMPORTED_MODULE_5__["default"].query());case 2:accountTypes = _context.sent;return _context.abrupt("return",

                res.status(200).send({
                  account_types: accountTypes }));case 4:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() } });

/***/ }),

/***/ "./src/http/controllers/Accounting.js":
/*!********************************************!*\
  !*** ./src/http/controllers/Accounting.js ***!
  \********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! express-validator */ "express-validator");
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(express_validator__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! lodash */ "lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! moment */ "moment");
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(moment__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _models_Account__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/models/Account */ "./src/models/Account.js");
/* harmony import */ var _http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/http/middleware/asyncMiddleware */ "./src/http/middleware/asyncMiddleware.js");
/* harmony import */ var _http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/http/middleware/jwtAuth */ "./src/http/middleware/jwtAuth.js");
/* harmony import */ var _services_Accounting_JournalPoster__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/services/Accounting/JournalPoster */ "./src/services/Accounting/JournalPoster.js");
/* harmony import */ var _services_Accounting_JournalEntry__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/services/Accounting/JournalEntry */ "./src/services/Accounting/JournalEntry.js");
/* harmony import */ var _models_JournalEntry__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/models/JournalEntry */ "./src/models/JournalEntry.js");
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}










/* harmony default export */ __webpack_exports__["default"] = ({
  /**
                  * Router constructor.
                  */
  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_4___default.a.Router();
    router.use(_http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_9__["default"]);

    router.post('/make-journal-entries',
    this.makeJournalEntries.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_8__["default"])(this.makeJournalEntries.handler));

    router.post('/recurring-journal-entries',
    this.recurringJournalEntries.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_8__["default"])(this.recurringJournalEntries.handler));

    router.post('quick-journal-entries',
    this.quickJournalEntries.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_8__["default"])(this.quickJournalEntries.handler));

    return router;
  },

  /**
      * Make journal entrires.
      */
  makeJournalEntries: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('date').isISO8601(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('reference').exists(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('memo').optional().trim().escape(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('entries').isArray({ min: 1 }),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('entries.*.credit').optional({ nullable: true }).isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('entries.*.debit').optional({ nullable: true }).isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('entries.*.account_id').isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('entries.*.note').optional()],

    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(req, res) {var validationErrors, form, totalCredit, totalDebit, user, errorReasons, entries, formattedDate, accountsIds, accounts, storedAccountsIds, journalReference, manualJournal, journalPoster;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context.next = 3;break;}return _context.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                form = _objectSpread({
                  date: new Date() },
                req.body);


                totalCredit = 0;
                totalDebit = 0;

                user = req.user;
                errorReasons = [];
                entries = form.entries.filter(function (entry) {return entry.credit || entry.debit;});
                formattedDate = moment__WEBPACK_IMPORTED_MODULE_6___default()(form.date).format('YYYY-MM-DD');

                entries.forEach(function (entry) {
                  if (entry.credit > 0) {
                    totalCredit += entry.credit;
                  }
                  if (entry.debit > 0) {
                    totalDebit += entry.debit;
                  }
                });

                if (totalCredit <= 0 || totalDebit <= 0) {
                  errorReasons.push({
                    type: 'CREDIT.DEBIT.SUMATION.SHOULD.NOT.EQUAL.ZERO',
                    code: 400 });

                }
                if (totalCredit !== totalDebit) {
                  errorReasons.push({ type: 'CREDIT.DEBIT.NOT.EQUALS', code: 100 });
                }
                accountsIds = entries.map(function (entry) {return entry.account_id;});_context.next = 16;return (
                  _models_Account__WEBPACK_IMPORTED_MODULE_7__["default"].query().whereIn('id', accountsIds).
                  withGraphFetched('type'));case 16:accounts = _context.sent;

                storedAccountsIds = accounts.map(function (account) {return account.id;});

                if (Object(lodash__WEBPACK_IMPORTED_MODULE_5__["difference"])(accountsIds, storedAccountsIds).length > 0) {
                  errorReasons.push({ type: 'ACCOUNTS.IDS.NOT.FOUND', code: 200 });
                }_context.next = 21;return (

                  _models_JournalEntry__WEBPACK_IMPORTED_MODULE_12__["default"].query().where('reference', form.reference));case 21:journalReference = _context.sent;

                if (journalReference.length > 0) {
                  errorReasons.push({ type: 'REFERENCE.ALREADY.EXISTS', code: 300 });
                }if (!(
                errorReasons.length > 0)) {_context.next = 25;break;}return _context.abrupt("return",
                res.status(400).send({ errors: errorReasons }));case 25:_context.next = 27;return (



                  _models_JournalEntry__WEBPACK_IMPORTED_MODULE_12__["default"].query().insert({
                    reference: form.reference,
                    transaction_type: 'Journal',
                    amount: totalCredit,
                    date: formattedDate,
                    note: form.memo,
                    user_id: user.id }));case 27:manualJournal = _context.sent;

                journalPoster = new _services_Accounting_JournalPoster__WEBPACK_IMPORTED_MODULE_10__["default"]();

                entries.forEach(function (entry) {
                  var account = accounts.find(function (a) {return a.id === entry.account_id;});

                  var jouranlEntry = new _services_Accounting_JournalEntry__WEBPACK_IMPORTED_MODULE_11__["default"]({
                    debit: entry.debit,
                    credit: entry.credit,
                    account: account.id,
                    transactionType: 'Journal',
                    accountNormal: account.type.normal,
                    note: entry.note,
                    date: formattedDate,
                    userId: user.id });

                  if (entry.debit) {
                    journalPoster.debit(jouranlEntry);
                  } else {
                    journalPoster.credit(jouranlEntry);
                  }
                });

                // Saves the journal entries and accounts balance changes.
                _context.next = 32;return Promise.all([
                journalPoster.saveEntries(),
                journalPoster.saveBalance()]);case 32:return _context.abrupt("return",

                res.status(200).send({ id: manualJournal.id }));case 33:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                                      * Saves recurring journal entries template.
                                                                                                                                                                                                                      */
  recurringJournalEntries: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('template_name').exists(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('recurrence').exists(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('active').optional().isBoolean().toBoolean(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('entries').isArray({ min: 1 }),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('entries.*.credit').isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('entries.*.debit').isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('entries.*.account_id').isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('entries.*.note').optional()],

    handler: function () {var _handler2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(req, res) {var validationErrors;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context2.next = 3;break;}return _context2.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:case "end":return _context2.stop();}}}, _callee2);}));function handler(_x3, _x4) {return _handler2.apply(this, arguments);}return handler;}() },






  recurringJournalsList: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["query"])('page').optional().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["query"])('page_size').optional().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["query"])('template_name').optional()],

    handler: function () {var _handler3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(req, res) {var validationErrors;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context3.next = 3;break;}return _context3.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:case "end":return _context3.stop();}}}, _callee3);}));function handler(_x5, _x6) {return _handler3.apply(this, arguments);}return handler;}() },





  quickJournalEntries: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('date').exists().isISO8601(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('amount').exists().isNumeric().toFloat(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('credit_account_id').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('debit_account_id').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('transaction_type').exists(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('note').optional()],

    handler: function () {var _handler4 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(req, res) {var validationErrors, errorReasons, form, foundAccounts, creditAccount, debitAccount;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context4.next = 3;break;}return _context4.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                errorReasons = [];
                form = _objectSpread({}, req.body);_context4.next = 7;return (

                  _models_Account__WEBPACK_IMPORTED_MODULE_7__["default"].query().
                  where('id', form.credit_account_id).
                  orWhere('id', form.debit_account_id));case 7:foundAccounts = _context4.sent;

                creditAccount = foundAccounts.find(function (a) {return a.id === form.credit_account_id;});
                debitAccount = foundAccounts.find(function (a) {return a.id === form.debit_account_id;});

                if (!creditAccount) {
                  errorReasons.push({ type: 'CREDIT_ACCOUNT.NOT.EXIST', code: 100 });
                }
                if (!debitAccount) {
                  errorReasons.push({ type: 'DEBIT_ACCOUNT.NOT.EXIST', code: 200 });
                }if (!(
                errorReasons.length > 0)) {_context4.next = 14;break;}return _context4.abrupt("return",
                res.status(400).send({ errors: errorReasons }));case 14:return _context4.abrupt("return",









                res.status(200).send());case 15:case "end":return _context4.stop();}}}, _callee4);}));function handler(_x7, _x8) {return _handler4.apply(this, arguments);}return handler;}() } });

/***/ }),

/***/ "./src/http/controllers/Accounts.js":
/*!******************************************!*\
  !*** ./src/http/controllers/Accounts.js ***!
  \******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/toConsumableArray */ "@babel/runtime/helpers/toConsumableArray");
/* harmony import */ var _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "@babel/runtime/helpers/slicedToArray");
/* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! express-validator */ "express-validator");
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(express_validator__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/http/middleware/asyncMiddleware */ "./src/http/middleware/asyncMiddleware.js");
/* harmony import */ var _models_Account__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/models/Account */ "./src/models/Account.js");
/* harmony import */ var _models_AccountType__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/models/AccountType */ "./src/models/AccountType.js");
/* harmony import */ var _models_AccountTransaction__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/models/AccountTransaction */ "./src/models/AccountTransaction.js");
/* harmony import */ var _services_Accounting_JournalPoster__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/services/Accounting/JournalPoster */ "./src/services/Accounting/JournalPoster.js");
/* harmony import */ var _models_AccountBalance__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/models/AccountBalance */ "./src/models/AccountBalance.js");
/* harmony import */ var _models_Resource__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @/models/Resource */ "./src/models/Resource.js");
/* harmony import */ var _models_View__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @/models/View */ "./src/models/View.js");
/* harmony import */ var _http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @/http/middleware/jwtAuth */ "./src/http/middleware/jwtAuth.js");
/* harmony import */ var _collection_NestedSet__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../collection/NestedSet */ "./src/collection/NestedSet/index.js");
/* harmony import */ var _lib_ViewRolesBuilder__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! @/lib/ViewRolesBuilder */ "./src/lib/ViewRolesBuilder/index.js");
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}













/* harmony default export */ __webpack_exports__["default"] = ({
  /**
                  * Router constructor method.
                  */
  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_5___default.a.Router();

    router.use(_http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_15__["default"]);
    router.post('/',
    this.newAccount.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__["default"])(this.newAccount.handler));

    router.post('/:id',
    this.editAccount.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__["default"])(this.editAccount.handler));

    router.get('/:id',
    this.getAccount.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__["default"])(this.getAccount.handler));

    router.get('/',
    this.getAccountsList.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__["default"])(this.getAccountsList.handler));

    router["delete"]('/:id',
    this.deleteAccount.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__["default"])(this.deleteAccount.handler));

    router.post('/:id/active',
    this.activeAccount.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__["default"])(this.activeAccount.handler));

    router.post('/:id/inactive',
    this.inactiveAccount.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__["default"])(this.inactiveAccount.handler));

    router.post('/:id/recalculate-balance',
    this.recalcualteBalanace.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__["default"])(this.recalcualteBalanace.handler));

    router.post('/:id/transfer_account/:toAccount',
    this.transferToAnotherAccount.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__["default"])(this.transferToAnotherAccount.handler));

    return router;
  },

  /**
      * Creates a new account.
      */
  newAccount: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('name').exists().isLength({ min: 3 }).trim().escape(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('code').exists().isLength({ max: 10 }).trim().escape(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('account_type_id').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('description').optional().trim().escape()],

    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee(req, res) {var validationErrors, form, foundAccountCodePromise, foundAccountTypePromise, _ref, _ref2, foundAccountCode, foundAccountType;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context.next = 3;break;}return _context.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                form = _objectSpread({}, req.body);

                foundAccountCodePromise = form.code ?
                _models_Account__WEBPACK_IMPORTED_MODULE_8__["default"].query().where('code', form.code) : null;

                foundAccountTypePromise = _models_AccountType__WEBPACK_IMPORTED_MODULE_9__["default"].query().
                findById(form.account_type_id);_context.next = 8;return (

                  Promise.all([
                  foundAccountCodePromise, foundAccountTypePromise]));case 8:_ref = _context.sent;_ref2 = _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2___default()(_ref, 2);foundAccountCode = _ref2[0];foundAccountType = _ref2[1];if (!(


                foundAccountCodePromise && foundAccountCode.length > 0)) {_context.next = 14;break;}return _context.abrupt("return",
                res.boom.badRequest(null, {
                  errors: [{ type: 'NOT_UNIQUE_CODE', code: 100 }] }));case 14:if (


                foundAccountType) {_context.next = 16;break;}return _context.abrupt("return",
                res.boom.badRequest(null, {
                  errors: [{ type: 'NOT_EXIST_ACCOUNT_TYPE', code: 200 }] }));case 16:_context.next = 18;return (


                  _models_Account__WEBPACK_IMPORTED_MODULE_8__["default"].query().insert(_objectSpread({}, form)));case 18:return _context.abrupt("return",

                res.status(200).send({ item: {} }));case 19:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                          * Edit the given account details.
                                                                                                                                                                                                          */
  editAccount: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["param"])('id').exists().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('name').exists().isLength({ min: 3 }).trim().escape(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('code').exists().isLength({ max: 10 }).trim().escape(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('account_type_id').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('description').optional().trim().escape()],

    handler: function () {var _handler2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee2(req, res) {var id, validationErrors, form, account, foundAccountCodePromise, foundAccountTypePromise, _ref3, _ref4, foundAccountCode, foundAccountType;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
                id = req.params.id;
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context2.next = 4;break;}return _context2.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 4:


                form = _objectSpread({}, req.body);_context2.next = 7;return (
                  _models_Account__WEBPACK_IMPORTED_MODULE_8__["default"].query().findById(id));case 7:account = _context2.sent;if (

                account) {_context2.next = 10;break;}return _context2.abrupt("return",
                res.boom.notFound());case 10:

                foundAccountCodePromise = form.code && form.code !== account.code ?
                _models_Account__WEBPACK_IMPORTED_MODULE_8__["default"].query().where('code', form.code).whereNot('id', account.id) : null;

                foundAccountTypePromise = form.account_type_id !== account.account_type_id ?
                _models_AccountType__WEBPACK_IMPORTED_MODULE_9__["default"].query().where('id', form.account_type_id) : null;_context2.next = 14;return (

                  Promise.all([
                  foundAccountCodePromise, foundAccountTypePromise]));case 14:_ref3 = _context2.sent;_ref4 = _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2___default()(_ref3, 2);foundAccountCode = _ref4[0];foundAccountType = _ref4[1];if (!(

                foundAccountCode.length > 0 && foundAccountCodePromise)) {_context2.next = 20;break;}return _context2.abrupt("return",
                res.boom.badRequest(null, {
                  errors: [{ type: 'NOT_UNIQUE_CODE', code: 100 }] }));case 20:if (!(


                foundAccountType.length <= 0 && foundAccountTypePromise)) {_context2.next = 22;break;}return _context2.abrupt("return",
                res.boom.badRequest(null, {
                  errors: [{ type: 'NOT_EXIST_ACCOUNT_TYPE', code: 110 }] }));case 22:_context2.next = 24;return (


                  account.patch(_objectSpread({}, form)));case 24:return _context2.abrupt("return",

                res.status(200).send());case 25:case "end":return _context2.stop();}}}, _callee2);}));function handler(_x3, _x4) {return _handler2.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                  * Get details of the given account.
                                                                                                                                                                                                  */
  getAccount: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["param"])('id').toInt()],

    handler: function () {var _handler3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee3(req, res) {var id, account;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
                id = req.params.id;_context3.next = 3;return (
                  _models_Account__WEBPACK_IMPORTED_MODULE_8__["default"].query().where('id', id).first());case 3:account = _context3.sent;if (

                account) {_context3.next = 6;break;}return _context3.abrupt("return",
                res.boom.notFound());case 6:return _context3.abrupt("return",

                res.status(200).send({ account: _objectSpread({}, account) }));case 7:case "end":return _context3.stop();}}}, _callee3);}));function handler(_x5, _x6) {return _handler3.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                                                        * Delete the given account.
                                                                                                                                                                                                                                        */
  deleteAccount: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["param"])('id').toInt()],

    handler: function () {var _handler4 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee4(req, res) {var id, account, accountTransactions;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:
                id = req.params.id;_context4.next = 3;return (
                  _models_Account__WEBPACK_IMPORTED_MODULE_8__["default"].query().findById(id));case 3:account = _context4.sent;if (

                account) {_context4.next = 6;break;}return _context4.abrupt("return",
                res.boom.notFound());case 6:_context4.next = 8;return (

                  _models_AccountTransaction__WEBPACK_IMPORTED_MODULE_10__["default"].query().
                  where('account_id', account.id));case 8:accountTransactions = _context4.sent;if (!(

                accountTransactions.length > 0)) {_context4.next = 11;break;}return _context4.abrupt("return",
                res.boom.badRequest(null, {
                  errors: [{ type: 'ACCOUNT.HAS.ASSOCIATED.TRANSACTIONS', code: 100 }] }));case 11:_context4.next = 13;return (


                  _models_Account__WEBPACK_IMPORTED_MODULE_8__["default"].query().deleteById(account.id));case 13:return _context4.abrupt("return",

                res.status(200).send());case 14:case "end":return _context4.stop();}}}, _callee4);}));function handler(_x7, _x8) {return _handler4.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                  * Retrieve accounts list.
                                                                                                                                                                                                  */
  getAccountsList: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["query"])('display_type').optional().isIn(['tree', 'flat']),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["query"])('account_types').optional().isArray(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["query"])('account_types.*').optional().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["query"])('custom_view_id').optional().isNumeric().toInt()],

    handler: function () {var _handler5 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee5(req, res) {var validationErrors, filter, errorReasons, viewConditionals, accountsResource, view, accounts, nestedAccounts, groupsAccounts, accountsList, flattenAccounts;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee5$(_context5) {while (1) {switch (_context5.prev = _context5.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context5.next = 3;break;}return _context5.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:



                filter = _objectSpread({
                  account_types: [],
                  display_type: 'tree' },
                req.query);

                errorReasons = [];
                viewConditionals = [];_context5.next = 8;return (
                  _models_Resource__WEBPACK_IMPORTED_MODULE_13__["default"].query().where('name', 'accounts').first());case 8:accountsResource = _context5.sent;if (

                accountsResource) {_context5.next = 11;break;}return _context5.abrupt("return",
                res.status(400).send({
                  errors: [{ type: 'ACCOUNTS_RESOURCE_NOT_FOUND', code: 200 }] }));case 11:_context5.next = 13;return (


                  _models_View__WEBPACK_IMPORTED_MODULE_14__["default"].query().onBuild(function (builder) {
                    if (filter.custom_view_id) {
                      builder.where('id', filter.custom_view_id);
                    } else {
                      builder.where('favourite', true);
                    }
                    builder.where('resource_id', accountsResource.id);
                    builder.withGraphFetched('roles.field');
                    builder.withGraphFetched('columns');
                    builder.first();
                  }));case 13:view = _context5.sent;

                if (view && view.roles.length > 0) {
                  viewConditionals.push.apply(viewConditionals, _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0___default()(
                  Object(_lib_ViewRolesBuilder__WEBPACK_IMPORTED_MODULE_17__["mapViewRolesToConditionals"])(view.roles)));

                  if (!Object(_lib_ViewRolesBuilder__WEBPACK_IMPORTED_MODULE_17__["validateViewRoles"])(viewConditionals, view.rolesLogicExpression)) {
                    errorReasons.push({ type: 'VIEW.LOGIC.EXPRESSION.INVALID', code: 400 });
                  }
                }if (!(
                errorReasons.length > 0)) {_context5.next = 17;break;}return _context5.abrupt("return",
                res.status(400).send({ errors: errorReasons }));case 17:_context5.next = 19;return (

                  _models_Account__WEBPACK_IMPORTED_MODULE_8__["default"].query().onBuild(function (builder) {
                    builder.modify('filterAccountTypes', filter.account_types);
                    builder.withGraphFetched('type');

                    if (viewConditionals.length) {
                      builder.modify('viewRolesBuilder', viewConditionals, view.rolesLogicExpression);
                    }
                  }));case 19:accounts = _context5.sent;

                nestedAccounts = new _collection_NestedSet__WEBPACK_IMPORTED_MODULE_16__["default"](accounts, { parentId: 'parentAccountId' });
                groupsAccounts = nestedAccounts.toTree();
                accountsList = [];

                if (filter.display_type === 'tree') {
                  accountsList.push.apply(accountsList, _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0___default()(groupsAccounts));
                } else if (filter.display_type === 'flat') {
                  flattenAccounts = nestedAccounts.flattenTree(function (account, parentAccount) {
                    if (parentAccount) {
                      account.name = "".concat(parentAccount.name, " \u2015 ").concat(account.name);
                    }
                    return account;
                  });
                  accountsList.push.apply(accountsList, _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0___default()(flattenAccounts));
                }return _context5.abrupt("return",
                res.status(200).send(_objectSpread({
                  accounts: accountsList },
                view ? {
                  customViewId: view.id } :
                {})));case 25:case "end":return _context5.stop();}}}, _callee5);}));function handler(_x9, _x10) {return _handler5.apply(this, arguments);}return handler;}() },




  /**
                                                                                                                                                                                 * Re-calculates balance of the given account.
                                                                                                                                                                                 */
  recalcualteBalanace: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["param"])('id').isNumeric().toInt()],

    handler: function () {var _handler6 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee6(req, res) {var id, account, accountTransactions, journalEntries;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee6$(_context6) {while (1) {switch (_context6.prev = _context6.next) {case 0:
                id = req.params.id;_context6.next = 3;return (
                  _models_Account__WEBPACK_IMPORTED_MODULE_8__["default"].findById(id));case 3:account = _context6.sent;if (

                account) {_context6.next = 6;break;}return _context6.abrupt("return",
                res.status(400).send({
                  errors: [{ type: 'ACCOUNT.NOT.FOUND', code: 100 }] }));case 6:


                accountTransactions = _models_AccountTransaction__WEBPACK_IMPORTED_MODULE_10__["default"].query().
                where('account_id', account.id);

                journalEntries = new _services_Accounting_JournalPoster__WEBPACK_IMPORTED_MODULE_11__["default"]();
                journalEntries.loadFromCollection(accountTransactions);

                // Delete the balance of the given account id.
                _context6.next = 11;return _models_AccountBalance__WEBPACK_IMPORTED_MODULE_12__["default"].query().where('account_id', account.id)["delete"]();case 11:_context6.next = 13;return (


                  journalEntries.saveBalance());case 13:return _context6.abrupt("return",

                res.status(200).send());case 14:case "end":return _context6.stop();}}}, _callee6);}));function handler(_x11, _x12) {return _handler6.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                    * Active the given account.
                                                                                                                                                                                                    */
  activeAccount: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["param"])('id').exists().isNumeric().toInt()],

    handler: function () {var _handler7 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee7(req, res) {var id, account;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee7$(_context7) {while (1) {switch (_context7.prev = _context7.next) {case 0:
                id = req.params.id;_context7.next = 3;return (
                  _models_Account__WEBPACK_IMPORTED_MODULE_8__["default"].findById(id));case 3:account = _context7.sent;if (

                account) {_context7.next = 6;break;}return _context7.abrupt("return",
                res.status(400).send({
                  errors: [{ type: 'ACCOUNT.NOT.FOUND', code: 100 }] }));case 6:_context7.next = 8;return (


                  account.patch({ active: true }));case 8:return _context7.abrupt("return",

                res.status(200).send({ id: account.id }));case 9:case "end":return _context7.stop();}}}, _callee7);}));function handler(_x13, _x14) {return _handler7.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                                     * Inactive the given account.
                                                                                                                                                                                                                     */
  inactiveAccount: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["param"])('id').exists().isNumeric().toInt()],

    handler: function () {var _handler8 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee8(req, res) {var id, account;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee8$(_context8) {while (1) {switch (_context8.prev = _context8.next) {case 0:
                id = req.params.id;_context8.next = 3;return (
                  _models_Account__WEBPACK_IMPORTED_MODULE_8__["default"].findById(id));case 3:account = _context8.sent;if (

                account) {_context8.next = 6;break;}return _context8.abrupt("return",
                res.status(400).send({
                  errors: [{ type: 'ACCOUNT.NOT.FOUND', code: 100 }] }));case 6:_context8.next = 8;return (


                  account.patch({ active: false }));case 8:return _context8.abrupt("return",

                res.status(200).send({ id: account.id }));case 9:case "end":return _context8.stop();}}}, _callee8);}));function handler(_x15, _x16) {return _handler8.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                                     * Transfer all journal entries of the given account to another account.
                                                                                                                                                                                                                     */
  transferToAnotherAccount: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["param"])('id').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["param"])('toAccount').exists().isNumeric().toInt()],

    handler: function () {var _handler9 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee9(req, res) {var validationErrors;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee9$(_context9) {while (1) {switch (_context9.prev = _context9.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context9.next = 3;break;}return _context9.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:case "end":return _context9.stop();}}}, _callee9);}));function handler(_x17, _x18) {return _handler9.apply(this, arguments);}return handler;}() } });

/***/ }),

/***/ "./src/http/controllers/Authentication.js":
/*!************************************************!*\
  !*** ./src/http/controllers/Authentication.js ***!
  \************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(__dirname) {/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! express-validator */ "express-validator");
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(express_validator__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! path */ "path");
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! fs */ "fs");
/* harmony import */ var fs__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(fs__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var mustache__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! mustache */ "mustache");
/* harmony import */ var mustache__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(mustache__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var jsonwebtoken__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! jsonwebtoken */ "jsonwebtoken");
/* harmony import */ var jsonwebtoken__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(jsonwebtoken__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../middleware/asyncMiddleware */ "./src/http/middleware/asyncMiddleware.js");
/* harmony import */ var _models_User__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/models/User */ "./src/models/User.js");
/* harmony import */ var _models_PasswordReset__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/models/PasswordReset */ "./src/models/PasswordReset.js");
/* harmony import */ var _services_mail__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/services/mail */ "./src/services/mail.js");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @/utils */ "./src/utils/index.js");
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}












/* harmony default export */ __webpack_exports__["default"] = ({
  /**
                  * Constructor method.
                  */
  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_3___default.a.Router();

    router.post('/login',
    this.login.validation,
    Object(_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_9__["default"])(this.login.handler));

    router.post('/send_reset_password',
    this.sendResetPassword.validation,
    Object(_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_9__["default"])(this.sendResetPassword.handler));

    router.post('/reset/:token',
    this.resetPassword.validation,
    Object(_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_9__["default"])(this.resetPassword.handler));

    return router;
  },

  /**
      * User login authentication request.
      */
  login: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('crediential').exists().isEmail(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('password').exists().isLength({ min: 4 })],

    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(req, res) {var validationErrors, _req$body, crediential, password, JWT_SECRET_KEY, user, token;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context.next = 3;break;}return _context.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:_req$body =


                req.body, crediential = _req$body.crediential, password = _req$body.password;
                JWT_SECRET_KEY = process.env.JWT_SECRET_KEY;_context.next = 7;return (

                  _models_User__WEBPACK_IMPORTED_MODULE_10__["default"].query().
                  where('email', crediential).
                  orWhere('phone_number', crediential).
                  first());case 7:user = _context.sent;if (

                user) {_context.next = 10;break;}return _context.abrupt("return",
                res.boom.badRequest(null, {
                  errors: [{ type: 'INVALID_DETAILS', code: 100 }] }));case 10:if (


                user.verifyPassword(password)) {_context.next = 12;break;}return _context.abrupt("return",
                res.boom.badRequest(null, {
                  errors: [{ type: 'INVALID_DETAILS', code: 100 }] }));case 12:if (


                user.active) {_context.next = 14;break;}return _context.abrupt("return",
                res.boom.badRequest(null, {
                  errors: [{ type: 'USER_INACTIVE', code: 110 }] }));case 14:


                // user.update({ last_login_at: new Date() });

                token = jsonwebtoken__WEBPACK_IMPORTED_MODULE_8___default.a.sign({
                  email: user.email,
                  _id: user.id },
                JWT_SECRET_KEY, {
                  expiresIn: '1d' });return _context.abrupt("return",

                res.status(200).send({ token: token, user: user }));case 16:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                                          * Send reset password link via email or SMS.
                                                                                                                                                                                                                          */
  sendResetPassword: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('email').exists().isEmail()],

    // eslint-disable-next-line consistent-return
    handler: function () {var _handler2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(req, res) {var validationErrors, email, user, passwordReset, filePath, template, rendered, mailOptions;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context2.next = 3;break;}return _context2.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                email = req.body.email;_context2.next = 6;return (
                  _models_User__WEBPACK_IMPORTED_MODULE_10__["default"].where('email', email).fetch());case 6:user = _context2.sent;if (

                user) {_context2.next = 9;break;}return _context2.abrupt("return",
                res.status(422).send());case 9:_context2.next = 11;return (


                  _models_PasswordReset__WEBPACK_IMPORTED_MODULE_11__["default"].where({ email: email }).destroy({ require: false }));case 11:

                passwordReset = _models_PasswordReset__WEBPACK_IMPORTED_MODULE_11__["default"].forge({
                  email: email,
                  token: '123123' });_context2.next = 14;return (

                  passwordReset.save());case 14:

                filePath = path__WEBPACK_IMPORTED_MODULE_5___default.a.join(__dirname, '../../views/mail/ResetPassword.html');
                template = fs__WEBPACK_IMPORTED_MODULE_6___default.a.readFileSync(filePath, 'utf8');
                rendered = mustache__WEBPACK_IMPORTED_MODULE_7___default.a.render(template, {
                  url: "".concat(req.protocol, "://").concat(req.hostname, "/reset/").concat(passwordReset.attributes.token),
                  first_name: user.attributes.first_name,
                  last_name: user.attributes.last_name,
                  contact_us_email: process.env.CONTACT_US_EMAIL });


                mailOptions = {
                  to: user.attributes.email,
                  from: "".concat(process.env.MAIL_FROM_NAME, " ").concat(process.env.MAIL_FROM_ADDRESS),
                  subject: 'Ratteb Password Reset',
                  html: rendered };


                // eslint-disable-next-line consistent-return
                _services_mail__WEBPACK_IMPORTED_MODULE_12__["default"].sendMail(mailOptions, function (error) {
                  if (error) {
                    return res.status(400).send();
                  }
                  res.status(200).send({ data: { email: passwordReset.attributes.email } });
                });case 19:case "end":return _context2.stop();}}}, _callee2);}));function handler(_x3, _x4) {return _handler2.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                             * Reset password.
                                                                                                                                                                             */
  resetPassword: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('password').exists().isLength({ min: 5 }).custom(function (value, _ref) {var req = _ref.req;
      if (value !== req.body.confirm_password) {
        throw new Error("Passwords don't match");
      } else {
        return value;
      }
    })],

    handler: function () {var _handler3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(req, res) {var validationErrors, token, password, tokenModel, user, hashedPassword;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context3.next = 3;break;}return _context3.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'VALIDATION_ERROR' }, validationErrors)));case 3:


                token = req.params.token;
                password = req.body.password;_context3.next = 7;return (

                  _models_PasswordReset__WEBPACK_IMPORTED_MODULE_11__["default"].query().
                  where('token', token).
                  where('created_at', '>=', Date.now() - 3600000).
                  first());case 7:tokenModel = _context3.sent;if (

                tokenModel) {_context3.next = 10;break;}return _context3.abrupt("return",
                res.boom.badRequest(null, {
                  errors: [{ type: 'TOKEN_INVALID', code: 100 }] }));case 10:_context3.next = 12;return (


                  _models_User__WEBPACK_IMPORTED_MODULE_10__["default"].where({
                    email: tokenModel.email }));case 12:user = _context3.sent;if (

                user) {_context3.next = 15;break;}return _context3.abrupt("return",
                res.boom.badRequest(null, {
                  errors: [{ type: 'USER_NOT_FOUND', code: 120 }] }));case 15:_context3.next = 17;return (


                  Object(_utils__WEBPACK_IMPORTED_MODULE_13__["hashPassword"])(password));case 17:hashedPassword = _context3.sent;

                user.password = hashedPassword;_context3.next = 21;return (
                  user.save());case 21:_context3.next = 23;return (

                  _models_PasswordReset__WEBPACK_IMPORTED_MODULE_11__["default"].where('email', user.get('email')).destroy({ require: false }));case 23:return _context3.abrupt("return",

                res.status(200).send({}));case 24:case "end":return _context3.stop();}}}, _callee3);}));function handler(_x5, _x6) {return _handler3.apply(this, arguments);}return handler;}() } });
/* WEBPACK VAR INJECTION */}.call(this, "/"))

/***/ }),

/***/ "./src/http/controllers/Bills.js":
/*!***************************************!*\
  !*** ./src/http/controllers/Bills.js ***!
  \***************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_0__);


/* harmony default export */ __webpack_exports__["default"] = ({

  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_0___default.a.Router();

    return router;
  } });

/***/ }),

/***/ "./src/http/controllers/Budget.js":
/*!****************************************!*\
  !*** ./src/http/controllers/Budget.js ***!
  \****************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "@babel/runtime/helpers/slicedToArray");
/* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! express-validator */ "express-validator");
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(express_validator__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! lodash */ "lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/http/middleware/asyncMiddleware */ "./src/http/middleware/asyncMiddleware.js");
/* harmony import */ var _http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/http/middleware/jwtAuth */ "./src/http/middleware/jwtAuth.js");
/* harmony import */ var _models_Budget__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/models/Budget */ "./src/models/Budget.js");
/* harmony import */ var _models_BudgetEntry__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/models/BudgetEntry */ "./src/models/BudgetEntry.js");
/* harmony import */ var _models_Account__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/models/Account */ "./src/models/Account.js");
/* harmony import */ var _services_Moment__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/services/Moment */ "./src/services/Moment/index.js");
/* harmony import */ var _collection_BudgetEntriesSet__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @/collection/BudgetEntriesSet */ "./src/collection/BudgetEntriesSet.js");
/* harmony import */ var _models_AccountType__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @/models/AccountType */ "./src/models/AccountType.js");
/* harmony import */ var _collection_NestedSet__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @/collection/NestedSet */ "./src/collection/NestedSet/index.js");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! @/utils */ "./src/utils/index.js");
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}














/* harmony default export */ __webpack_exports__["default"] = ({
  /**
                  * Router constructor.
                  */
  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_4___default.a.Router();

    router.use(_http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_8__["default"]);

    router.post('/',
    this.newBudget.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__["default"])(this.newBudget.handler));

    router.get('/:id',
    this.getBudget.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__["default"])(this.getBudget.handler));

    router.get('/:id',
    this.deleteBudget.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__["default"])(this.deleteBudget.handler));

    router.get('/',
    this.listBudgets.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__["default"])(this.listBudgets.handler));

    return router;
  },

  /**
      * Retrieve budget details of the given id.
      */
  getBudget: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["param"])('id').exists().isNumeric().toInt()],

    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(req, res) {var validationErrors, id, budget, accountTypes, _ref, _ref2, budgetEntries, accounts, accountsNestedSet, columns, fromDate, toDate, dateRange, dateRangeCollection, budgetEntriesSet;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context.next = 3;break;}return _context.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                id = req.params.id;_context.next = 6;return (
                  _models_Budget__WEBPACK_IMPORTED_MODULE_9__["default"].query().findById(id));case 6:budget = _context.sent;if (

                budget) {_context.next = 9;break;}return _context.abrupt("return",
                res.status(404).send({
                  errors: [{ type: 'budget.not.found', code: 100 }] }));case 9:_context.next = 11;return (


                  _models_AccountType__WEBPACK_IMPORTED_MODULE_14__["default"].query().where('balance_sheet', true));case 11:accountTypes = _context.sent;_context.next = 14;return (

                  Promise.all([
                  _models_BudgetEntry__WEBPACK_IMPORTED_MODULE_10__["default"].query().where('budget_id', budget.id),
                  _models_Account__WEBPACK_IMPORTED_MODULE_11__["default"].query().whereIn('account_type_id', accountTypes.map(function (a) {return a.id;}))]));case 14:_ref = _context.sent;_ref2 = _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_1___default()(_ref, 2);budgetEntries = _ref2[0];accounts = _ref2[1];


                accountsNestedSet = new _collection_NestedSet__WEBPACK_IMPORTED_MODULE_15__["default"](accounts);

                columns = [];
                fromDate = Object(_services_Moment__WEBPACK_IMPORTED_MODULE_12__["default"])(budget.year).startOf('year').
                add(budget.rangeOffset, budget.rangeBy).toDate();

                toDate = Object(_services_Moment__WEBPACK_IMPORTED_MODULE_12__["default"])(budget.year).endOf('year').toDate();

                dateRange = _services_Moment__WEBPACK_IMPORTED_MODULE_12__["default"].range(fromDate, toDate);
                dateRangeCollection = Array.from(dateRange.by(budget.rangeBy, {
                  step: budget.rangeIncrement, excludeEnd: false, excludeStart: false }));


                dateRangeCollection.forEach(function (date) {
                  columns.push(date.format(Object(_utils__WEBPACK_IMPORTED_MODULE_16__["dateRangeFormat"])(budget.rangeBy)));
                });
                budgetEntriesSet = _collection_BudgetEntriesSet__WEBPACK_IMPORTED_MODULE_13__["default"].from(budgetEntries, {
                  orderSize: columns.length });

                budgetEntriesSet.setZeroPlaceholder();
                budgetEntriesSet.calcTotalSummary();return _context.abrupt("return",

                res.status(200).send({
                  columns: columns,
                  accounts: budgetEntriesSet.toArray(),
                  total: budgetEntriesSet.toArrayTotalSummary() }));case 29:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() },




  /**
                                                                                                                                                                                                                          * Delete the given budget.
                                                                                                                                                                                                                          */
  deleteBudget: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["param"])('id').exists()],

    handler: function () {var _handler2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(req, res) {var validationErrors, id, budget;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context2.next = 3;break;}return _context2.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:



                id = req.params.id;_context2.next = 6;return (
                  _models_Budget__WEBPACK_IMPORTED_MODULE_9__["default"].query().findById(id));case 6:budget = _context2.sent;if (

                budget) {_context2.next = 9;break;}return _context2.abrupt("return",
                res.status(404).send({
                  errors: [{ type: 'budget.not.found', code: 100 }] }));case 9:_context2.next = 11;return (


                  _models_BudgetEntry__WEBPACK_IMPORTED_MODULE_10__["default"].query().where('budget_id', budget.id)["delete"]());case 11:_context2.next = 13;return (
                  budget["delete"]());case 13:return _context2.abrupt("return",

                res.status(200).send());case 14:case "end":return _context2.stop();}}}, _callee2);}));function handler(_x3, _x4) {return _handler2.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                  * Saves the new budget.
                                                                                                                                                                                                  */
  newBudget: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('name').exists(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('fiscal_year').exists(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('period').exists().isIn(['year', 'month', 'quarter', 'half-year']),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('accounts_type').exists().isIn(['balance_sheet', 'profit_loss']),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('accounts').isArray(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('accounts.*.account_id').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('accounts.*.entries').exists().isArray(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('accounts.*.entries.*.amount').exists().isNumeric().toFloat(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('accounts.*.entries.*.order').exists().isNumeric().toInt()],

    handler: function () {var _handler3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(req, res) {var validationErrors, form, submitAccountsIds, storedAccounts, storedAccountsIds, errorReasons, notFoundAccountsIds, budget, promiseOpers;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context3.next = 3;break;}return _context3.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:



                form = _objectSpread({}, req.body);
                submitAccountsIds = form.accounts.map(function (a) {return a.account_id;});_context3.next = 7;return (
                  _models_Account__WEBPACK_IMPORTED_MODULE_11__["default"].query().whereIn('id', submitAccountsIds));case 7:storedAccounts = _context3.sent;
                storedAccountsIds = storedAccounts.map(function (a) {return a.id;});

                errorReasons = [];
                notFoundAccountsIds = Object(lodash__WEBPACK_IMPORTED_MODULE_6__["difference"])(submitAccountsIds, storedAccountsIds);

                if (notFoundAccountsIds.length > 0) {
                  errorReasons.push({
                    type: 'ACCOUNT.NOT.FOUND', code: 200, accounts: notFoundAccountsIds });

                }if (!(
                errorReasons.length > 0)) {_context3.next = 14;break;}return _context3.abrupt("return",
                res.status(400).send({ errors: errorReasons }));case 14:_context3.next = 16;return (


                  _models_Budget__WEBPACK_IMPORTED_MODULE_9__["default"].query().insert(_objectSpread({},
                  Object(lodash__WEBPACK_IMPORTED_MODULE_6__["pick"])(form, ['name', 'fiscal_year', 'period', 'accounts_type']))));case 16:budget = _context3.sent;


                promiseOpers = [];

                form.accounts.forEach(function (account) {
                  account.entries.forEach(function (entry) {
                    var budgetEntry = _models_BudgetEntry__WEBPACK_IMPORTED_MODULE_10__["default"].query().insert({
                      account_id: account.account_id,
                      amount: entry.amount,
                      order: entry.order });

                    promiseOpers.push(budgetEntry);
                  });
                });_context3.next = 21;return (
                  Promise.all(promiseOpers));case 21:return _context3.abrupt("return",

                res.status(200).send({ id: budget.id }));case 22:case "end":return _context3.stop();}}}, _callee3);}));function handler(_x5, _x6) {return _handler3.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                                   * List of paginated budgets items.
                                                                                                                                                                                                                   */
  listBudgets: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('year').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('income_statement').optional().isBoolean().toBoolean(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('profit_loss').optional().isBoolean().toBoolean(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('page').optional().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('page_size').isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('custom_view_id').optional().isNumeric().toInt()],

    handler: function () {var _handler4 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(req, res) {var validationErrors, filter, budgets;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context4.next = 3;break;}return _context4.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:



                filter = _objectSpread({
                  page_size: 10,
                  page: 1 },
                req.query);_context4.next = 6;return (

                  _models_Budget__WEBPACK_IMPORTED_MODULE_9__["default"].query().runBefore(function (result, q) {
                    if (filter.profit_loss) {
                      q.modify('filterByYear', filter.year);
                    }
                    if (filter.income_statement) {
                      q.modify('filterByIncomeStatement', filter.income_statement);
                    }
                    if (filter.profit_loss) {
                      q.modify('filterByProfitLoss', filter.profit_loss);
                    }
                    q.page(filter.page, filter.page_size);
                    return result;
                  }));case 6:budgets = _context4.sent;return _context4.abrupt("return",
                res.status(200).send({
                  items: budgets.items }));case 8:case "end":return _context4.stop();}}}, _callee4);}));function handler(_x7, _x8) {return _handler4.apply(this, arguments);}return handler;}() } });

/***/ }),

/***/ "./src/http/controllers/BudgetReports.js":
/*!***********************************************!*\
  !*** ./src/http/controllers/BudgetReports.js ***!
  \***********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! express-validator */ "express-validator");
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(express_validator__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! moment */ "moment");
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(moment__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/http/middleware/jwtAuth */ "./src/http/middleware/jwtAuth.js");
/* harmony import */ var _http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/http/middleware/asyncMiddleware */ "./src/http/middleware/asyncMiddleware.js");
/* harmony import */ var _models_Budget__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/models/Budget */ "./src/models/Budget.js");
/* harmony import */ var _models_Account__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/models/Account */ "./src/models/Account.js");
/* harmony import */ var _models_AccountType__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/models/AccountType */ "./src/models/AccountType.js");
/* harmony import */ var _collection_NestedSet__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/collection/NestedSet */ "./src/collection/NestedSet/index.js");
/* harmony import */ var _models_BudgetEntry__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/models/BudgetEntry */ "./src/models/BudgetEntry.js");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @/utils */ "./src/utils/index.js");
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}











/* harmony default export */ __webpack_exports__["default"] = ({

  /**
                  * Router constructor.
                  */
  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_3___default.a.Router();

    router.use(_http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_6__["default"]);

    router.get('/budget_verses_actual/:reportId',
    this.budgetVersesActual.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__["default"])(this.budgetVersesActual.handler));

    return router;
  },

  budgetVersesActual: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["query"])('basis').optional().isIn(['cash', 'accural']),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["query"])('period').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["query"])('active_accounts').optional().toBoolean()],

    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(req, res) {var validationErrors, reportId, form, errorReasons, budget, budgetEntries, accountTypes, accounts, fromDate, toDate, dateRange, dateRangeCollection;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context.next = 3;break;}return _context.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                reportId = req.params.reportId;
                form = _objectSpread({}, req.body);
                errorReasons = [];_context.next = 8;return (

                  _models_Budget__WEBPACK_IMPORTED_MODULE_8__["default"].query().findById(reportId));case 8:budget = _context.sent;

                if (!budget) {
                  errorReasons.push({ type: 'BUDGET_NOT_FOUND', code: 100 });
                }_context.next = 12;return (
                  _models_BudgetEntry__WEBPACK_IMPORTED_MODULE_12__["default"].query().where('budget_id', budget.id));case 12:budgetEntries = _context.sent;if (!(

                errorReasons.length > 0)) {_context.next = 15;break;}return _context.abrupt("return",
                res.status(400).send({ errors: errorReasons }));case 15:_context.next = 17;return (

                  _models_AccountType__WEBPACK_IMPORTED_MODULE_10__["default"].query().
                  where('balance_sheet', budget.accountTypes === 'balance_sheet').
                  where('income_sheet', budget.accountTypes === 'profit_losss'));case 17:accountTypes = _context.sent;_context.next = 20;return (

                  _models_Account__WEBPACK_IMPORTED_MODULE_9__["default"].query().runBefore(function (result, q) {
                    var accountTypesIds = accountTypes.map(function (t) {return t.id;});

                    if (accountTypesIds.length > 0) {
                      q.whereIn('account_type_id', accountTypesIds);
                    }
                    q.where('active', form.active_accounts === true);
                    q.withGraphFetched('transactions');
                  }));case 20:accounts = _context.sent;

                // const accountsNestedSet = NestedSet.from(accounts);

                fromDate = moment__WEBPACK_IMPORTED_MODULE_5___default()(budget.year).startOf('year').
                add(budget.rangeOffset, budget.rangeBy).toDate();

                toDate = moment__WEBPACK_IMPORTED_MODULE_5___default()(budget.year).endOf('year').toDate();

                dateRange = moment__WEBPACK_IMPORTED_MODULE_5___default.a.range(fromDate, toDate);
                dateRangeCollection = Array.from(dateRange.by(budget.rangeBy, {
                  step: budget.rangeIncrement, excludeEnd: false, excludeStart: false }));


                //   // const accounts = {
                //   //   assets: [
                //   //     {
                //   //       name: '',
                //   //       code: '',
                //   //       totalEntries: [
                //   //         {

                //   //         }
                //   //       ],
                //   //       children: [
                //   //         {
                //   //           name: '',
                //   //           code: '',
                //   //           entries: [
                //   //             {

                //   //             }
                //   //           ]
                //   //         }
                //   //       ]
                //   //     }
                //   //   ]
                //   // }
                return _context.abrupt("return",
                res.status(200).send({
                  columns: dateRangeCollection.map(function (d) {return d.format(Object(_utils__WEBPACK_IMPORTED_MODULE_13__["dateRangeFormat"])(budget.rangeBy));})
                  // accounts: {
                  //   asset: [],
                  //   liabilities: [],
                  //   equaity: [],

                  //   income: [],
                  //   expenses: [],
                  // }
                }));case 26:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() } });

/***/ }),

/***/ "./src/http/controllers/Currencies.js":
/*!********************************************!*\
  !*** ./src/http/controllers/Currencies.js ***!
  \********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! express-validator */ "express-validator");
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(express_validator__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/http/middleware/asyncMiddleware */ "./src/http/middleware/asyncMiddleware.js");




/* harmony default export */ __webpack_exports__["default"] = ({

  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_2___default.a.Router();

    router.get('/all',
    this.all.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_4__["default"])(this.all.handler));

    router.get('/registered',
    this.registered.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_4__["default"])(this.registered.handler));

    return router;
  },

  all: {
    validation: [],
    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(req, res) {return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:return _context.abrupt("return",

                res.status(200).send({
                  currencies: [
                  { currency_code: 'USD', currency_sign: '$' },
                  { currency_code: 'LYD', currency_sign: '' }] }));case 1:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() },





  registered: {
    validation: [],
    handler: function () {var _handler2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(req, res) {return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:return _context2.abrupt("return",

                res.status(200).send({
                  currencies: [
                  { currency_code: 'USD', currency_sign: '$' },
                  { currency_code: 'LYD', currency_sign: '' }] }));case 1:case "end":return _context2.stop();}}}, _callee2);}));function handler(_x3, _x4) {return _handler2.apply(this, arguments);}return handler;}() } });

/***/ }),

/***/ "./src/http/controllers/CurrencyAdjustment.js":
/*!****************************************************!*\
  !*** ./src/http/controllers/CurrencyAdjustment.js ***!
  \****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);

/* harmony default export */ __webpack_exports__["default"] = ({


  router: function router() {

  },

  addExchangePrice: {
    validation: {},


    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(req, res) {return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() } });

/***/ }),

/***/ "./src/http/controllers/Customers.js":
/*!*******************************************!*\
  !*** ./src/http/controllers/Customers.js ***!
  \*******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! express-validator */ "express-validator");
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(express_validator__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/http/middleware/asyncMiddleware */ "./src/http/middleware/asyncMiddleware.js");




/* harmony default export */ __webpack_exports__["default"] = ({

  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_2___default.a.Router();

    router.post('/',
    this.newCustomer.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_4__["default"])(this.newCustomer.handler));

    router.post('/:id',
    this.editCustomer.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_4__["default"])(this.editCustomer.handler));

    return router;
  },

  newCustomer: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('custom_type').exists().trim().escape(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('first_name').exists().trim().escape(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('last_name'),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('company_name'),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('email'),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('work_phone'),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('personal_phone'),

    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('billing_address.country'),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('billing_address.address'),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('billing_address.city'),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('billing_address.phone'),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('billing_address.zip_code'),

    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('shiping_address.country'),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('shiping_address.address'),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('shiping_address.city'),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('shiping_address.phone'),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('shiping_address.zip_code'),

    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('contact.additional_phone'),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('contact.additional_email'),

    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('custom_fields').optional().isArray({ min: 1 }),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('custom_fields.*.key').exists().trim().escape(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('custom_fields.*.value').exists(),

    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["check"])('inactive').optional().isBoolean().toBoolean()],


    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(req, res) {return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() },




  editCustomer: {
    validation: [],


    handler: function () {var _handler2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(req, res) {return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:case "end":return _context2.stop();}}}, _callee2);}));function handler(_x3, _x4) {return _handler2.apply(this, arguments);}return handler;}() } });

/***/ }),

/***/ "./src/http/controllers/Expenses.js":
/*!******************************************!*\
  !*** ./src/http/controllers/Expenses.js ***!
  \******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/toConsumableArray */ "@babel/runtime/helpers/toConsumableArray");
/* harmony import */ var _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "@babel/runtime/helpers/slicedToArray");
/* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! express-validator */ "express-validator");
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(express_validator__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! moment */ "moment");
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(moment__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! lodash */ "lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_8__);
/* harmony import */ var _http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/http/middleware/asyncMiddleware */ "./src/http/middleware/asyncMiddleware.js");
/* harmony import */ var _models_Expense__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/models/Expense */ "./src/models/Expense.js");
/* harmony import */ var _models_Account__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/models/Account */ "./src/models/Account.js");
/* harmony import */ var _services_Accounting_JournalPoster__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/services/Accounting/JournalPoster */ "./src/services/Accounting/JournalPoster.js");
/* harmony import */ var _services_Accounting_JournalEntry__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @/services/Accounting/JournalEntry */ "./src/services/Accounting/JournalEntry.js");
/* harmony import */ var _http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @/http/middleware/jwtAuth */ "./src/http/middleware/jwtAuth.js");
/* harmony import */ var _models_AccountTransaction__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @/models/AccountTransaction */ "./src/models/AccountTransaction.js");
/* harmony import */ var _models_View__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! @/models/View */ "./src/models/View.js");
/* harmony import */ var _models_Resource__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../../models/Resource */ "./src/models/Resource.js");
/* harmony import */ var _services_CustomFields_ResourceCustomFieldRepository__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! @/services/CustomFields/ResourceCustomFieldRepository */ "./src/services/CustomFields/ResourceCustomFieldRepository.js");
/* harmony import */ var _lib_ViewRolesBuilder__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! @/lib/ViewRolesBuilder */ "./src/lib/ViewRolesBuilder/index.js");
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}















/* harmony default export */ __webpack_exports__["default"] = ({
  /**
                  * Router constructor.
                  */
  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_5___default.a.Router();
    router.use(_http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_14__["default"]);

    router.post('/',
    this.newExpense.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_9__["default"])(this.newExpense.handler));

    router.post('/:id/publish',
    this.publishExpense.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_9__["default"])(this.publishExpense.handler));

    router["delete"]('/:id',
    this.deleteExpense.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_9__["default"])(this.deleteExpense.handler));

    router.post('/bulk',
    this.bulkAddExpenses.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_9__["default"])(this.bulkAddExpenses.handler));

    router.post('/:id',
    this.updateExpense.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_9__["default"])(this.updateExpense.handler));

    router.get('/',
    this.listExpenses.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_9__["default"])(this.listExpenses.handler));

    // router.get('/:id',
    //   this.getExpense.validation,
    //   asyncMiddleware(this.getExpense.handler));

    return router;
  },

  /**
      * Saves a new expense.
      */
  newExpense: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('date').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('payment_account_id').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('expense_account_id').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('description').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('amount').exists().isNumeric().toFloat(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('currency_code').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('exchange_rate').optional().isNumeric().toFloat(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('publish').optional().isBoolean().toBoolean(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('custom_fields').optional().isArray({ min: 1 }),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('custom_fields.*.key').exists().trim().escape(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('custom_fields.*.value').exists()],

    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default.a.mark(function _callee(req, res) {var validationErrors, form, errorReasons, paymentAccount, expenseAccount, expenseTransaction, journalEntries, creditEntry, debitEntry;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context.next = 3;break;}return _context.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                form = _objectSpread({
                  date: new Date(),
                  published: false,
                  custom_fields: [] },
                req.body);

                // Convert the date to the general format.
                form.date = moment__WEBPACK_IMPORTED_MODULE_7___default()(form.date).format('YYYY-MM-DD');

                errorReasons = [];_context.next = 8;return (
                  _models_Account__WEBPACK_IMPORTED_MODULE_11__["default"].query().
                  findById(form.payment_account_id).first());case 8:paymentAccount = _context.sent;

                if (!paymentAccount) {
                  errorReasons.push({ type: 'PAYMENT.ACCOUNT.NOT.FOUND', code: 100 });
                }_context.next = 12;return (
                  _models_Account__WEBPACK_IMPORTED_MODULE_11__["default"].query().findById(form.expense_account_id).first());case 12:expenseAccount = _context.sent;

                if (!expenseAccount) {
                  errorReasons.push({ type: 'EXPENSE.ACCOUNT.NOT.FOUND', code: 200 });
                }
                // const customFields = new ResourceCustomFieldRepository(Expense);
                // await customFields.load();

                // if (customFields.validateExistCustomFields()) {
                //   errorReasons.push({ type: 'CUSTOM.FIELDS.SLUGS.NOT.EXISTS', code: 400 });
                // }
                if (!(errorReasons.length > 0)) {_context.next = 16;break;}return _context.abrupt("return",
                res.status(400).send({ errors: errorReasons }));case 16:_context.next = 18;return (

                  _models_Expense__WEBPACK_IMPORTED_MODULE_10__["default"].query().insertAndFetch(_objectSpread({},
                  Object(lodash__WEBPACK_IMPORTED_MODULE_8__["omit"])(form, ['custom_fields']))));case 18:expenseTransaction = _context.sent;

                // customFields.fillCustomFields(expenseTransaction.id, form.custom_fields);

                journalEntries = new _services_Accounting_JournalPoster__WEBPACK_IMPORTED_MODULE_12__["default"]();
                creditEntry = new _services_Accounting_JournalEntry__WEBPACK_IMPORTED_MODULE_13__["default"]({
                  credit: form.amount,
                  referenceId: expenseTransaction.id,
                  referenceType: _models_Expense__WEBPACK_IMPORTED_MODULE_10__["default"].referenceType,
                  date: form.date,
                  account: expenseAccount.id,
                  accountNormal: 'debit',
                  draft: !form.published });

                debitEntry = new _services_Accounting_JournalEntry__WEBPACK_IMPORTED_MODULE_13__["default"]({
                  debit: form.amount,
                  referenceId: expenseTransaction.id,
                  referenceType: _models_Expense__WEBPACK_IMPORTED_MODULE_10__["default"].referenceType,
                  date: form.date,
                  account: paymentAccount.id,
                  accountNormal: 'debit',
                  draft: !form.published });

                journalEntries.credit(creditEntry);
                journalEntries.debit(debitEntry);_context.next = 26;return (

                  Promise.all([
                  // customFields.saveCustomFields(expenseTransaction.id),
                  journalEntries.saveEntries(),
                  journalEntries.saveBalance()]));case 26:return _context.abrupt("return",

                res.status(200).send({ id: expenseTransaction.id }));case 27:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                                           * Bulk add expneses to the given accounts.
                                                                                                                                                                                                                           */
  bulkAddExpenses: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('expenses').exists().isArray({ min: 1 }),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('expenses.*.date').optional().isISO8601(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('expenses.*.payment_account_id').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('expenses.*.expense_account_id').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('expenses.*.description').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('expenses.*.amount').exists().isNumeric().toFloat(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('expenses.*.currency_code').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('expenses.*.exchange_rate').optional().isNumeric().toFloat()],

    handler: function () {var _handler2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default.a.mark(function _callee3(req, res) {var validationErrors, form, errorReasons, paymentAccountsIds, expenseAccountsIds, _ref, _ref2, expensesAccounts, paymentAccounts, storedExpensesAccountsIds, storedPaymentAccountsIds, notFoundPaymentAccountsIds, notFoundExpenseAccountsIds, expenseSaveOpers, journalPoster, savedExpenseTransactions;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default.a.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context3.next = 3;break;}return _context3.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                form = _objectSpread({}, req.body);
                errorReasons = [];

                paymentAccountsIds = Object(lodash__WEBPACK_IMPORTED_MODULE_8__["chain"])(form.expenses).
                map(function (e) {return e.payment_account_id;}).uniq().value();
                expenseAccountsIds = Object(lodash__WEBPACK_IMPORTED_MODULE_8__["chain"])(form.expenses).
                map(function (e) {return e.expense_account_id;}).uniq().value();_context3.next = 9;return (

                  Promise.all([
                  _models_Account__WEBPACK_IMPORTED_MODULE_11__["default"].query().whereIn('id', expenseAccountsIds),
                  _models_Account__WEBPACK_IMPORTED_MODULE_11__["default"].query().whereIn('id', paymentAccountsIds)]));case 9:_ref = _context3.sent;_ref2 = _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_1___default()(_ref, 2);expensesAccounts = _ref2[0];paymentAccounts = _ref2[1];

                storedExpensesAccountsIds = expensesAccounts.map(function (a) {return a.id;});
                storedPaymentAccountsIds = paymentAccounts.map(function (a) {return a.id;});

                notFoundPaymentAccountsIds = Object(lodash__WEBPACK_IMPORTED_MODULE_8__["difference"])(expenseAccountsIds, storedExpensesAccountsIds);
                notFoundExpenseAccountsIds = Object(lodash__WEBPACK_IMPORTED_MODULE_8__["difference"])(paymentAccountsIds, storedPaymentAccountsIds);

                if (notFoundPaymentAccountsIds.length > 0) {
                  errorReasons.push({
                    type: 'PAYMENY.ACCOUNTS.NOT.FOUND',
                    code: 100,
                    accounts: notFoundPaymentAccountsIds });

                }
                if (notFoundExpenseAccountsIds.length > 0) {
                  errorReasons.push({
                    type: 'EXPENSE.ACCOUNTS.NOT.FOUND',
                    code: 200,
                    accounts: notFoundExpenseAccountsIds });

                }if (!(
                errorReasons.length > 0)) {_context3.next = 21;break;}return _context3.abrupt("return",
                res.boom.badRequest(null, { reasons: errorReasons }));case 21:

                expenseSaveOpers = [];
                journalPoster = new _services_Accounting_JournalPoster__WEBPACK_IMPORTED_MODULE_12__["default"]();

                form.expenses.forEach( /*#__PURE__*/function () {var _ref3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default.a.mark(function _callee2(expense) {var expenseSaveOper;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default.a.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
                            expenseSaveOper = _models_Expense__WEBPACK_IMPORTED_MODULE_10__["default"].query().insert(_objectSpread({}, expense));
                            expenseSaveOpers.push(expenseSaveOper);case 2:case "end":return _context2.stop();}}}, _callee2);}));return function (_x5) {return _ref3.apply(this, arguments);};}());

                // Wait unit save all expense transactions.
                _context3.next = 26;return Promise.all(expenseSaveOpers);case 26:savedExpenseTransactions = _context3.sent;

                savedExpenseTransactions.forEach(function (expense) {
                  var date = moment__WEBPACK_IMPORTED_MODULE_7___default()(expense.date).format('YYYY-DD-MM');

                  var debit = new _services_Accounting_JournalEntry__WEBPACK_IMPORTED_MODULE_13__["default"]({
                    debit: expense.amount,
                    referenceId: expense.id,
                    referenceType: _models_Expense__WEBPACK_IMPORTED_MODULE_10__["default"].referenceType,
                    account: expense.payment_account_id,
                    accountNormal: 'debit',
                    date: date });

                  var credit = new _services_Accounting_JournalEntry__WEBPACK_IMPORTED_MODULE_13__["default"]({
                    credit: expense.amount,
                    referenceId: expense.id,
                    referenceType: _models_Expense__WEBPACK_IMPORTED_MODULE_10__["default"].referenceId,
                    account: expense.expense_account_id,
                    accountNormal: 'debit',
                    date: date });

                  journalPoster.credit(credit);
                  journalPoster.debit(debit);
                });

                // Save expense journal entries and balance change.
                _context3.next = 30;return Promise.all([
                journalPoster.saveEntries(),
                journalPoster.saveBalance()]);case 30:return _context3.abrupt("return",

                res.status(200).send());case 31:case "end":return _context3.stop();}}}, _callee3);}));function handler(_x3, _x4) {return _handler2.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                  * Publish the given expense id.
                                                                                                                                                                                                  */
  publishExpense: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["param"])('id').exists().isNumeric().toInt()],

    handler: function () {var _handler3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default.a.mark(function _callee4(req, res) {var validationErrors, id, errorReasons, expense;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default.a.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context4.next = 3;break;}return _context4.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:



                id = req.params.id;
                errorReasons = [];_context4.next = 7;return (
                  _models_Expense__WEBPACK_IMPORTED_MODULE_10__["default"].query().findById(id));case 7:expense = _context4.sent;

                if (!expense) {
                  errorReasons.push({ type: 'EXPENSE.NOT.FOUND', code: 100 });
                }if (!(
                errorReasons.length > 0)) {_context4.next = 11;break;}return _context4.abrupt("return",
                res.status(400).send({ errors: errorReasons }));case 11:


                if (expense.published) {
                  errorReasons.push({ type: 'EXPENSE.ALREADY.PUBLISHED', code: 200 });
                }if (!(
                errorReasons.length > 0)) {_context4.next = 14;break;}return _context4.abrupt("return",
                res.status(400).send({ errors: errorReasons }));case 14:_context4.next = 16;return (


                  _models_AccountTransaction__WEBPACK_IMPORTED_MODULE_15__["default"].query().
                  where('reference_id', expense.id).
                  where('reference_type', 'Expense').
                  patch({
                    draft: false }));case 16:_context4.next = 18;return (


                  _models_Expense__WEBPACK_IMPORTED_MODULE_10__["default"].query().
                  where('id', expense.id).
                  update({ published: true }));case 18:return _context4.abrupt("return",

                res.status(200).send());case 19:case "end":return _context4.stop();}}}, _callee4);}));function handler(_x6, _x7) {return _handler3.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                  * Retrieve paginated expenses list.
                                                                                                                                                                                                  */
  listExpenses: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["query"])('expense_account_id').optional().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["query"])('payment_account_id').optional().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["query"])('note').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["query"])('range_from').optional().isNumeric().toFloat(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["query"])('range_to').optional().isNumeric().toFloat(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["query"])('date_from').optional().isISO8601(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["query"])('date_to').optional().isISO8601(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["query"])('column_sort_order').optional().isIn(['created_at', 'date', 'amount']),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["query"])('sort_order').optional().isIn(['desc', 'asc']),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["query"])('page').optional().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["query"])('page_size').optional().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["query"])('custom_view_id').optional().isNumeric().toInt()],

    handler: function () {var _handler4 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default.a.mark(function _callee5(req, res) {var validationErrors, filter, errorReasons, expenseResource, view, viewConditionals, expenses;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default.a.wrap(function _callee5$(_context5) {while (1) {switch (_context5.prev = _context5.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context5.next = 3;break;}return _context5.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                filter = _objectSpread({
                  page_size: 10,
                  page: 1 },
                req.query);

                errorReasons = [];_context5.next = 7;return (
                  _models_Resource__WEBPACK_IMPORTED_MODULE_17__["default"].query().where('name', 'expenses').first());case 7:expenseResource = _context5.sent;

                if (!expenseResource) {
                  errorReasons.push({ type: 'EXPENSE_RESOURCE_NOT_FOUND', code: 300 });
                }if (!(
                errorReasons.length > 0)) {_context5.next = 11;break;}return _context5.abrupt("return",
                res.status(400).send({ errors: errorReasons }));case 11:_context5.next = 13;return (

                  _models_View__WEBPACK_IMPORTED_MODULE_16__["default"].query().onBuild(function (builder) {
                    if (filter.custom_view_id) {
                      builder.where('id', filter.custom_view_id);
                    } else {
                      builder.where('favourite', true);
                    }
                    builder.where('resource_id', expenseResource.id);
                    builder.withGraphFetched('viewRoles.field');
                    builder.withGraphFetched('columns');

                    builder.first();
                  }));case 13:view = _context5.sent;
                viewConditionals = [];

                if (view && view.viewRoles.length > 0) {
                  viewConditionals = Object(_lib_ViewRolesBuilder__WEBPACK_IMPORTED_MODULE_19__["mapViewRolesToConditionals"])(view.viewRoles);

                  if (!Object(_lib_ViewRolesBuilder__WEBPACK_IMPORTED_MODULE_19__["validateViewRoles"])(viewConditionals, view.rolesLogicExpression)) {
                    errorReasons.push({ type: 'VIEW.LOGIC.EXPRESSION.INVALID', code: 400 });
                  }
                }
                if (!view && filter.custom_view_id) {
                  errorReasons.push({ type: 'VIEW_NOT_FOUND', code: 100 });
                }if (!(
                errorReasons.length > 0)) {_context5.next = 19;break;}return _context5.abrupt("return",
                res.boom.badRequest(null, { errors: errorReasons }));case 19:_context5.next = 21;return (


                  _models_Expense__WEBPACK_IMPORTED_MODULE_10__["default"].query().onBuild(function (builder) {
                    builder.withGraphFetched('paymentAccount');
                    builder.withGraphFetched('expenseAccount');
                    builder.withGraphFetched('user');

                    if (viewConditionals.length) {
                      builder.modify('viewRolesBuilder', viewConditionals, view.rolesLogicExpression);
                    }
                    builder.modify('filterByAmountRange', filter.range_from, filter.to_range);
                    builder.modify('filterByDateRange', filter.date_from, filter.date_to);
                    builder.modify('filterByExpenseAccount', filter.expense_account_id);
                    builder.modify('filterByPaymentAccount', filter.payment_account_id);
                    builder.modify('orderBy', filter.column_sort_order, filter.sort_order);
                  }).page(filter.page - 1, filter.page_size));case 21:expenses = _context5.sent;return _context5.abrupt("return",

                res.status(200).send(_objectSpread({},
                view ? {
                  customViewId: view.id,
                  viewColumns: view.columns,
                  viewConditionals: viewConditionals } :
                {}, {
                  expenses: expenses })));case 23:case "end":return _context5.stop();}}}, _callee5);}));function handler(_x8, _x9) {return _handler4.apply(this, arguments);}return handler;}() },




  /**
                                                                                                                                                                                                    * Delete the given account.
                                                                                                                                                                                                    */
  deleteExpense: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["param"])('id').isNumeric().toInt()],

    handler: function () {var _handler5 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default.a.mark(function _callee6(req, res) {var validationErrors, id, expenseTransaction, expenseEntries, expenseEntriesCollect;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default.a.wrap(function _callee6$(_context6) {while (1) {switch (_context6.prev = _context6.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context6.next = 3;break;}return _context6.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                id = req.params.id;_context6.next = 6;return (
                  _models_Expense__WEBPACK_IMPORTED_MODULE_10__["default"].query().findById(id));case 6:expenseTransaction = _context6.sent;if (

                expenseTransaction) {_context6.next = 9;break;}return _context6.abrupt("return",
                res.status(404).send({
                  errors: [{ type: 'EXPENSE.TRANSACTION.NOT.FOUND', code: 100 }] }));case 9:_context6.next = 11;return (


                  _models_AccountTransaction__WEBPACK_IMPORTED_MODULE_15__["default"].query().
                  where('reference_type', 'Expense').
                  where('reference_id', expenseTransaction.id));case 11:expenseEntries = _context6.sent;

                expenseEntriesCollect = new _services_Accounting_JournalPoster__WEBPACK_IMPORTED_MODULE_12__["default"]();
                expenseEntriesCollect.loadEntries(expenseEntries);
                expenseEntriesCollect.reverseEntries();_context6.next = 17;return (

                  Promise.all([
                  _models_Expense__WEBPACK_IMPORTED_MODULE_10__["default"].query().findById(expenseTransaction.id)["delete"](),
                  expenseEntriesCollect.deleteEntries(),
                  expenseEntriesCollect.saveBalance()]));case 17:return _context6.abrupt("return",

                res.status(200).send());case 18:case "end":return _context6.stop();}}}, _callee6);}));function handler(_x10, _x11) {return _handler5.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                    * Update details of the given account.
                                                                                                                                                                                                    */
  updateExpense: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["param"])('id').isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('date').optional().isISO8601(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('payment_account_id').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('expense_account_id').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('description').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('amount').exists().isNumeric().toFloat(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('currency_code').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('exchange_rate').optional().isNumeric().toFloat()],

    handler: function () {var _handler6 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default.a.mark(function _callee7(req, res) {var validationErrors, id, expenseTransaction;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default.a.wrap(function _callee7$(_context7) {while (1) {switch (_context7.prev = _context7.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context7.next = 3;break;}return _context7.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                id = req.params.id;_context7.next = 6;return (
                  _models_Expense__WEBPACK_IMPORTED_MODULE_10__["default"].query().findById(id));case 6:expenseTransaction = _context7.sent;if (

                expenseTransaction) {_context7.next = 9;break;}return _context7.abrupt("return",
                res.status(404).send({
                  errors: [{ type: 'EXPENSE.TRANSACTION.NOT.FOUND', code: 100 }] }));case 9:case "end":return _context7.stop();}}}, _callee7);}));function handler(_x12, _x13) {return _handler6.apply(this, arguments);}return handler;}() },





  /**
                                                                                                                                                                                                                                                * Retrieve details of the given expense id.
                                                                                                                                                                                                                                                */
  getExpense: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["param"])('id').exists().isNumeric().toInt()],

    handler: function () {var _handler7 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default.a.mark(function _callee8(req, res) {var validationErrors, id, expenseTransaction, expenseCFMetadataRepo, expenseCusFieldsMetadata;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_2___default.a.wrap(function _callee8$(_context8) {while (1) {switch (_context8.prev = _context8.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context8.next = 3;break;}return _context8.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                id = req.params.id;_context8.next = 6;return (
                  _models_Expense__WEBPACK_IMPORTED_MODULE_10__["default"].query().findById(id));case 6:expenseTransaction = _context8.sent;if (

                expenseTransaction) {_context8.next = 9;break;}return _context8.abrupt("return",
                res.status(404).send({
                  errors: [{ type: 'EXPENSE.TRANSACTION.NOT.FOUND', code: 100 }] }));case 9:



                expenseCFMetadataRepo = new _services_CustomFields_ResourceCustomFieldRepository__WEBPACK_IMPORTED_MODULE_18__["default"](_models_Expense__WEBPACK_IMPORTED_MODULE_10__["default"]);_context8.next = 12;return (
                  expenseCFMetadataRepo.load());case 12:_context8.next = 14;return (
                  expenseCFMetadataRepo.fetchCustomFieldsMetadata(expenseTransaction.id));case 14:

                expenseCusFieldsMetadata = expenseCFMetadataRepo.getMetadata(expenseTransaction.id);return _context8.abrupt("return",

                res.status(200).send(_objectSpread({},
                expenseTransaction, {
                  custom_fields: _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0___default()(
                  expenseCusFieldsMetadata.toArray()) })));case 16:case "end":return _context8.stop();}}}, _callee8);}));function handler(_x14, _x15) {return _handler7.apply(this, arguments);}return handler;}() } });

/***/ }),

/***/ "./src/http/controllers/Fields.js":
/*!****************************************!*\
  !*** ./src/http/controllers/Fields.js ***!
  \****************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! express-validator */ "express-validator");
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(express_validator__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _models_ResourceField__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/models/ResourceField */ "./src/models/ResourceField.js");
/* harmony import */ var _models_Resource__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/models/Resource */ "./src/models/Resource.js");
/* harmony import */ var _middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../middleware/asyncMiddleware */ "./src/http/middleware/asyncMiddleware.js");
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}





/**
                                                              * Types of the custom fields.
                                                              */
var TYPES = ['text', 'email', 'number', 'url', 'percentage', 'checkbox', 'radio', 'textarea'];

/* harmony default export */ __webpack_exports__["default"] = ({
  /**
                  * Router constructor method.
                  */
  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_3___default.a.Router();

    router.post('/resource/:resource_name',
    this.addNewField.validation,
    Object(_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__["default"])(this.addNewField.handler));

    router.post('/:field_id',
    this.editField.validation,
    Object(_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__["default"])(this.editField.handler));

    router.post('/status/:field_id',
    this.changeStatus.validation,
    Object(_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_7__["default"])(this.changeStatus.handler));

    // router.get('/:field_id',
    //   asyncMiddleware(this.getField.handler));

    // router.delete('/:field_id',
    //   asyncMiddleware(this.deleteField.handler));

    return router;
  },

  /**
      * Adds a new field control to the given resource.
      * @param {Request} req -
      * @param {Response} res -
      */
  addNewField: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["param"])('resource_name').exists().trim().escape(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('label').exists().escape().trim(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('data_type').exists().isIn(TYPES),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('help_text').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('default').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('options').optional().isArray(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('options.*.key').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('options.*.value').exists()],

    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(req, res) {var resourceName, validationErrors, resource, form, choices, storedResource;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
                resourceName = req.params.resource_name;
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context.next = 4;break;}return _context.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 4:_context.next = 6;return (


                  _models_Resource__WEBPACK_IMPORTED_MODULE_6__["default"].query().where('name', resourceName).first());case 6:resource = _context.sent;if (

                resource) {_context.next = 9;break;}return _context.abrupt("return",
                res.boom.notFound(null, {
                  errors: [{ type: 'RESOURCE_NOT_FOUND', code: 100 }] }));case 9:


                form = _objectSpread({ options: [] }, req.body);
                choices = form.options.map(function (option) {return { key: option.key, value: option.value };});_context.next = 13;return (

                  _models_ResourceField__WEBPACK_IMPORTED_MODULE_5__["default"].query().insertAndFetch({
                    data_type: form.data_type,
                    label_name: form.label,
                    help_text: form.help_text,
                    "default": form["default"],
                    resource_id: resource.id,
                    options: choices,
                    index: -1 }));case 13:storedResource = _context.sent;return _context.abrupt("return",

                res.status(200).send({ id: storedResource.id }));case 15:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                                       * Edit details of the given field.
                                                                                                                                                                                                                       */
  editField: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["param"])('field_id').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('label').exists().escape().trim(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('data_type').exists().isIn(TYPES),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('help_text').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('default').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('options').optional().isArray(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('options.*.key').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('options.*.value').exists()],

    handler: function () {var _handler2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(req, res) {var fieldId, validationErrors, field, form, choices;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
                fieldId = req.params.field_id;
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context2.next = 4;break;}return _context2.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 4:_context2.next = 6;return (


                  _models_ResourceField__WEBPACK_IMPORTED_MODULE_5__["default"].query().findById(fieldId));case 6:field = _context2.sent;if (

                field) {_context2.next = 9;break;}return _context2.abrupt("return",
                res.boom.notFound(null, {
                  errors: [{ type: 'FIELD_NOT_FOUND', code: 100 }] }));case 9:


                // Sets the default value of optional fields.
                form = _objectSpread({ options: [] }, req.body);
                choices = form.options.map(function (option) {return { key: option.key, value: option.value };});_context2.next = 13;return (

                  _models_ResourceField__WEBPACK_IMPORTED_MODULE_5__["default"].query().findById(field.id).update({
                    data_type: form.data_type,
                    label_name: form.label,
                    help_text: form.help_text,
                    "default": form["default"],
                    options: choices }));case 13:return _context2.abrupt("return",

                res.status(200).send({ id: field.id }));case 14:case "end":return _context2.stop();}}}, _callee2);}));function handler(_x3, _x4) {return _handler2.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                                  * Retrieve the fields list of the given resource.
                                                                                                                                                                                                                  * @param {Request} req -
                                                                                                                                                                                                                  * @param {Response} res -
                                                                                                                                                                                                                  */
  fieldsList: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["param"])('resource_name').toInt()],

    handler: function () {var _handler3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(req, res) {var validationErrors, resourceName, resource, fields;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context3.next = 3;break;}return _context3.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                resourceName = req.params.resource_name;_context3.next = 6;return (
                  _models_Resource__WEBPACK_IMPORTED_MODULE_6__["default"].query().where('name', resourceName).first());case 6:resource = _context3.sent;if (

                resource) {_context3.next = 9;break;}return _context3.abrupt("return",
                res.boom.notFound(null, {
                  errors: [{ type: 'RESOURCE_NOT_FOUND', code: 100 }] }));case 9:_context3.next = 11;return (


                  _models_ResourceField__WEBPACK_IMPORTED_MODULE_5__["default"].where('resource_id', resource.id).fetchAll());case 11:fields = _context3.sent;return _context3.abrupt("return",

                res.status(200).send({ fields: fields.toJSON() }));case 13:case "end":return _context3.stop();}}}, _callee3);}));function handler(_x5, _x6) {return _handler3.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                                             * Change status of the given field.
                                                                                                                                                                                                                             */
  changeStatus: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["param"])('field_id').toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('active').isBoolean().toBoolean()],

    handler: function () {var _handler4 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(req, res) {var fieldId, field, active;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:
                fieldId = req.params.field_id;_context4.next = 3;return (
                  _models_ResourceField__WEBPACK_IMPORTED_MODULE_5__["default"].query().findById(fieldId));case 3:field = _context4.sent;if (

                field) {_context4.next = 6;break;}return _context4.abrupt("return",
                res.boom.notFound(null, {
                  errors: [{ type: 'NOT_FOUND_FIELD', code: 100 }] }));case 6:



                active = req.body.active;_context4.next = 9;return (
                  _models_ResourceField__WEBPACK_IMPORTED_MODULE_5__["default"].query().findById(field.id).patch({ active: active }));case 9:return _context4.abrupt("return",

                res.status(200).send({ id: field.id }));case 10:case "end":return _context4.stop();}}}, _callee4);}));function handler(_x7, _x8) {return _handler4.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                                  * Retrieve details of the given field.
                                                                                                                                                                                                                  */
  getField: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["param"])('field_id').toInt()],

    handler: function () {var _handler5 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5(req, res) {var id, field;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {while (1) {switch (_context5.prev = _context5.next) {case 0:
                id = req.params.field_id;_context5.next = 3;return (
                  _models_ResourceField__WEBPACK_IMPORTED_MODULE_5__["default"].where('id', id).fetch());case 3:field = _context5.sent;if (

                field) {_context5.next = 6;break;}return _context5.abrupt("return",
                res.boom.notFound());case 6:return _context5.abrupt("return",


                res.status(200).send({
                  field: field.toJSON() }));case 7:case "end":return _context5.stop();}}}, _callee5);}));function handler(_x9, _x10) {return _handler5.apply(this, arguments);}return handler;}() },




  /**
                                                                                                                                                                                                      * Delete the given field.
                                                                                                                                                                                                      */
  deleteField: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["param"])('field_id').toInt()],

    handler: function () {var _handler6 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee6(req, res) {var id, field;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee6$(_context6) {while (1) {switch (_context6.prev = _context6.next) {case 0:
                id = req.params.field_id;_context6.next = 3;return (
                  _models_ResourceField__WEBPACK_IMPORTED_MODULE_5__["default"].where('id', id).fetch());case 3:field = _context6.sent;if (

                field) {_context6.next = 6;break;}return _context6.abrupt("return",
                res.boom.notFound());case 6:if (!

                field.attributes.predefined) {_context6.next = 8;break;}return _context6.abrupt("return",
                res.boom.badRequest(null, {
                  errors: [{ type: 'PREDEFINED_FIELD', code: 100 }] }));case 8:_context6.next = 10;return (


                  field.destroy());case 10:return _context6.abrupt("return",

                res.status(200).send({ id: field.get('id') }));case 11:case "end":return _context6.stop();}}}, _callee6);}));function handler(_x11, _x12) {return _handler6.apply(this, arguments);}return handler;}() } });

/***/ }),

/***/ "./src/http/controllers/FinancialStatements.js":
/*!*****************************************************!*\
  !*** ./src/http/controllers/FinancialStatements.js ***!
  \*****************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/toConsumableArray */ "@babel/runtime/helpers/toConsumableArray");
/* harmony import */ var _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! express-validator */ "express-validator");
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(express_validator__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! moment */ "moment");
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(moment__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! lodash */ "lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/http/middleware/asyncMiddleware */ "./src/http/middleware/asyncMiddleware.js");
/* harmony import */ var _models_AccountTransaction__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/models/AccountTransaction */ "./src/models/AccountTransaction.js");
/* harmony import */ var _http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/http/middleware/jwtAuth */ "./src/http/middleware/jwtAuth.js");
/* harmony import */ var _models_AccountType__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/models/AccountType */ "./src/models/AccountType.js");
/* harmony import */ var _models_Account__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/models/Account */ "./src/models/Account.js");
/* harmony import */ var _services_Accounting_JournalPoster__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @/services/Accounting/JournalPoster */ "./src/services/Accounting/JournalPoster.js");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @/utils */ "./src/utils/index.js");
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}











var formatNumberClosure = function formatNumberClosure(filter) {return function (balance) {
    var formattedBalance = parseFloat(balance);

    if (filter.no_cents) {
      formattedBalance = parseInt(formattedBalance, 10);
    }
    if (filter.divide_1000) {
      formattedBalance /= 1000;
    }
    return formattedBalance;
  };};

/* harmony default export */ __webpack_exports__["default"] = ({
  /**
                  * Router constructor.
                  */
  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_4___default.a.Router();
    router.use(_http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_10__["default"]);

    router.get('/ledger',
    this.ledger.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_8__["default"])(this.ledger.handler));

    router.get('/general_ledger',
    this.generalLedger.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_8__["default"])(this.generalLedger.handler));

    router.get('/balance_sheet',
    this.balanceSheet.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_8__["default"])(this.balanceSheet.handler));

    router.get('/trial_balance_sheet',
    this.trialBalanceSheet.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_8__["default"])(this.trialBalanceSheet.handler));

    router.get('/profit_loss_sheet',
    this.profitLossSheet.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_8__["default"])(this.profitLossSheet.handler));

    router.get('/cash_flow_statement',
    this.cashFlowStatement.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_8__["default"])(this.cashFlowStatement.handler));

    return router;
  },

  /**
      * Retrieve the ledger report of the given account.
      */
  ledger: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('from_date').optional().isISO8601(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('to_date').optional().isISO8601(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('transaction_types').optional().isArray({ min: 1 }),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('account_ids').optional().isArray({ min: 1 }),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('account_ids.*').optional().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('from_range').optional().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('to_range').optional().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('number_format.no_cents').optional().isBoolean().toBoolean(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('number_format.divide_1000').optional().isBoolean().toBoolean()],

    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee(req, res) {var validationErrors, filter, accountsJournalEntries, formatNumber;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context.next = 3;break;}return _context.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                filter = _objectSpread({
                  from_range: null,
                  to_range: null,
                  account_ids: [],
                  transaction_types: [],
                  number_format: {
                    no_cents: false,
                    divide_1000: false } },

                req.query);_context.next = 6;return (

                  _models_AccountTransaction__WEBPACK_IMPORTED_MODULE_9__["default"].query().
                  modify('filterDateRange', filter.from_date, filter.to_date).
                  modify('filterAccounts', filter.account_ids).
                  modify('filterTransactionTypes', filter.transaction_types).
                  modify('filterAmountRange', filter.from_range, filter.to_range).
                  withGraphFetched('account'));case 6:accountsJournalEntries = _context.sent;

                formatNumber = formatNumberClosure(filter.number_format);return _context.abrupt("return",

                res.status(200).send({
                  meta: _objectSpread({}, filter),
                  items: accountsJournalEntries.map(function (entry) {return _objectSpread({},
                    entry, {
                      credit: formatNumber(entry.credit),
                      debit: formatNumber(entry.debit) });}) }));case 9:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() },





  /**
                                                                                                                                                                                                                      * Retrieve the general ledger financial statement.
                                                                                                                                                                                                                      */
  generalLedger: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('from_date').optional().isISO8601(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('to_date').optional().isISO8601(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('basis').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('number_format.no_cents').optional().isBoolean().toBoolean(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('number_format.divide_1000').optional().isBoolean().toBoolean(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('none_zero').optional().isBoolean().toBoolean()],

    handler: function () {var _handler2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee2(req, res) {var validationErrors, filter, accounts, openingBalanceTransactions, closingBalanceTransactions, opeingBalanceCollection, closingBalanceCollection, formatNumber, items;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context2.next = 3;break;}return _context2.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                filter = _objectSpread({
                  from_date: moment__WEBPACK_IMPORTED_MODULE_6___default()().startOf('year').format('YYYY-MM-DD'),
                  to_date: moment__WEBPACK_IMPORTED_MODULE_6___default()().endOf('year').format('YYYY-MM-DD'),
                  number_format: {
                    no_cents: false,
                    divide_1000: false },

                  none_zero: false },
                req.query);_context2.next = 6;return (

                  _models_Account__WEBPACK_IMPORTED_MODULE_12__["default"].query().
                  orderBy('index', 'DESC').
                  withGraphFetched('transactions').
                  modifyGraph('transactions', function (builder) {
                    builder.modify('filterDateRange', filter.from_date, filter.to_date);
                  }));case 6:accounts = _context2.sent;_context2.next = 9;return (

                  _models_AccountTransaction__WEBPACK_IMPORTED_MODULE_9__["default"].query().
                  modify('filterDateRange', null, filter.from_date).
                  modify('sumationCreditDebit').
                  withGraphFetched('account.type'));case 9:openingBalanceTransactions = _context2.sent;_context2.next = 12;return (

                  _models_AccountTransaction__WEBPACK_IMPORTED_MODULE_9__["default"].query().
                  modify('filterDateRange', null, filter.to_date).
                  modify('sumationCreditDebit').
                  withGraphFetched('account.type'));case 12:closingBalanceTransactions = _context2.sent;

                opeingBalanceCollection = new _services_Accounting_JournalPoster__WEBPACK_IMPORTED_MODULE_13__["default"]();
                closingBalanceCollection = new _services_Accounting_JournalPoster__WEBPACK_IMPORTED_MODULE_13__["default"]();

                opeingBalanceCollection.loadEntries(openingBalanceTransactions);
                closingBalanceCollection.loadEntries(closingBalanceTransactions);

                // Transaction amount formatter based on the given query.
                formatNumber = formatNumberClosure(filter.number_format);

                items = _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0___default()(
                accounts.
                filter(function (account) {return (
                    account.transactions.length > 0 || !filter.none_zero);}).

                map(function (account) {return _objectSpread({},
                  Object(lodash__WEBPACK_IMPORTED_MODULE_7__["pick"])(account, ['id', 'name', 'code', 'index']), {
                    transactions: _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0___default()(
                    account.transactions.map(function (transaction) {return _objectSpread({},
                      transaction, {
                        credit: formatNumber(transaction.credit),
                        debit: formatNumber(transaction.debit) });})),


                    opening: {
                      date: filter.from_date,
                      balance: opeingBalanceCollection.getClosingBalance(account.id) },

                    closing: {
                      date: filter.to_date,
                      balance: closingBalanceCollection.getClosingBalance(account.id) } });}));return _context2.abrupt("return",



                res.status(200).send({
                  meta: _objectSpread({}, filter),
                  accounts: items }));case 20:case "end":return _context2.stop();}}}, _callee2);}));function handler(_x3, _x4) {return _handler2.apply(this, arguments);}return handler;}() },




  /**
                                                                                                                                                                                                * Retrieve the balance sheet.
                                                                                                                                                                                                */
  balanceSheet: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('accounting_method').optional().isIn(['cash', 'accural']),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('from_date').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('to_date').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('display_columns_by').optional().isIn(['total', 'year', 'month', 'week', 'day', 'quarter']),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('number_format.no_cents').optional().isBoolean().toBoolean(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('number_format.divide_1000').optional().isBoolean().toBoolean(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('none_zero').optional().isBoolean().toBoolean()],

    handler: function () {var _handler3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee3(req, res) {var validationErrors, filter, balanceSheetTypes, accounts, journalEntriesCollected, journalEntries, balanceFormatter, filterDateType, dateRangeSet, assets, liabilitiesEquity;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context3.next = 3;break;}return _context3.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                filter = _objectSpread({
                  display_columns_by: 'total',
                  from_date: moment__WEBPACK_IMPORTED_MODULE_6___default()().startOf('year').format('YYYY-MM-DD'),
                  to_date: moment__WEBPACK_IMPORTED_MODULE_6___default()().endOf('year').format('YYYY-MM-DD'),
                  number_format: {
                    no_cents: false,
                    divide_1000: false },

                  none_zero: false,
                  basis: 'cash' },
                req.query);_context3.next = 6;return (


                  _models_AccountType__WEBPACK_IMPORTED_MODULE_11__["default"].query().where('balance_sheet', true));case 6:balanceSheetTypes = _context3.sent;_context3.next = 9;return (


                  _models_Account__WEBPACK_IMPORTED_MODULE_12__["default"].query().
                  whereIn('account_type_id', balanceSheetTypes.map(function (a) {return a.id;})).
                  withGraphFetched('type').
                  withGraphFetched('transactions').
                  modifyGraph('transactions', function (builder) {
                    builder.modify('filterDateRange', null, filter.to_date);
                  }));case 9:accounts = _context3.sent;

                journalEntriesCollected = _models_Account__WEBPACK_IMPORTED_MODULE_12__["default"].collectJournalEntries(accounts);
                journalEntries = new _services_Accounting_JournalPoster__WEBPACK_IMPORTED_MODULE_13__["default"]();
                journalEntries.loadEntries(journalEntriesCollected);

                // Account balance formmatter based on the given query.
                balanceFormatter = formatNumberClosure(filter.number_format);
                filterDateType = filter.display_columns_by === 'total' ?
                'day' : filter.display_columns_by;

                // Gets the date range set from start to end date.
                dateRangeSet = Object(_utils__WEBPACK_IMPORTED_MODULE_14__["dateRangeCollection"])(
                filter.from_date,
                filter.to_date,
                filterDateType);


                // Retrieve the asset balance sheet.
                assets = accounts.
                filter(function (account) {return (
                    account.type.normal === 'debit' && (
                    account.transactions.length > 0 || !filter.none_zero));}).

                map(function (account) {
                  // Calculates the closing balance to the given date.
                  var closingBalance = journalEntries.getClosingBalance(account.id, filter.to_date);
                  var type = filter.display_columns_by;

                  return _objectSpread({},
                  Object(lodash__WEBPACK_IMPORTED_MODULE_7__["pick"])(account, ['id', 'index', 'name', 'code']), {},
                  type !== 'total' ? {
                    periods_balance: dateRangeSet.map(function (date) {
                      var balance = journalEntries.getClosingBalance(account.id, date, filterDateType);

                      return {
                        date: date,
                        formatted_amount: balanceFormatter(balance),
                        amount: balance };

                    }) } :
                  {}, {
                    balance: {
                      formatted_amount: balanceFormatter(closingBalance),
                      amount: closingBalance,
                      date: filter.to_date } });


                });

                // Retrieve liabilities and equity balance sheet.
                liabilitiesEquity = accounts.
                filter(function (account) {return (
                    account.type.normal === 'credit' && (
                    account.transactions.length > 0 || !filter.none_zero));}).

                map(function (account) {
                  // Calculates the closing balance to the given date.
                  var closingBalance = journalEntries.getClosingBalance(account.id, filter.to_date);
                  var type = filter.display_columns_by;

                  return _objectSpread({},
                  Object(lodash__WEBPACK_IMPORTED_MODULE_7__["pick"])(account, ['id', 'index', 'name', 'code']), {},
                  type !== 'total' ? {
                    periods_balance: dateRangeSet.map(function (date) {
                      var balance = journalEntries.getClosingBalance(account.id, date, filterDateType);

                      return {
                        date: date,
                        formatted_amount: balanceFormatter(balance),
                        amount: balance };

                    }) } :
                  {}, {
                    balance: {
                      formattedAmount: balanceFormatter(closingBalance),
                      amount: closingBalance,
                      date: filter.to_date } });


                });return _context3.abrupt("return",

                res.status(200).send({
                  query: _objectSpread({}, filter),
                  columns: _objectSpread({}, dateRangeSet),
                  balance_sheet: {
                    assets: {
                      title: 'Assets',
                      accounts: _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0___default()(assets) },

                    liabilities_equity: {
                      title: 'Liabilities & Equity',
                      accounts: _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0___default()(liabilitiesEquity) } } }));case 19:case "end":return _context3.stop();}}}, _callee3);}));function handler(_x5, _x6) {return _handler3.apply(this, arguments);}return handler;}() },






  /**
                                                                                                                                                                                                                                        * Retrieve the trial balance sheet.
                                                                                                                                                                                                                                        */
  trialBalanceSheet: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('basis').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('from_date').optional().isISO8601(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('to_date').optional().isISO8601(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('number_format.no_cents').optional().isBoolean(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('number_format.1000_divide').optional().isBoolean(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('basis').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('none_zero').optional()],

    handler: function () {var _handler4 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee4(req, res) {var validationErrors, filter, accounts, journalEntriesCollect, journalEntries, balanceFormatter, items;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context4.next = 3;break;}return _context4.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                filter = _objectSpread({
                  from_date: moment__WEBPACK_IMPORTED_MODULE_6___default()().startOf('year').format('YYYY-MM-DD'),
                  to_date: moment__WEBPACK_IMPORTED_MODULE_6___default()().endOf('year').format('YYYY-MM-DD'),
                  number_format: {
                    no_cents: false,
                    divide_1000: false },

                  basis: 'accural',
                  none_zero: false },
                req.query);_context4.next = 6;return (


                  _models_Account__WEBPACK_IMPORTED_MODULE_12__["default"].query().
                  withGraphFetched('type').
                  withGraphFetched('transactions').
                  modifyGraph('transactions', function (builder) {
                    builder.modify('sumationCreditDebit');
                    builder.modify('filterDateRange', filter.from_date, filter.to_date);
                  }));case 6:accounts = _context4.sent;

                journalEntriesCollect = _models_Account__WEBPACK_IMPORTED_MODULE_12__["default"].collectJournalEntries(accounts);
                journalEntries = new _services_Accounting_JournalPoster__WEBPACK_IMPORTED_MODULE_13__["default"]();
                journalEntries.loadEntries(journalEntriesCollect);

                // Account balance formmatter based on the given query.
                balanceFormatter = formatNumberClosure(filter.number_format);

                items = accounts.
                filter(function (account) {return (
                    account.transactions.length > 0 || !filter.none_zero);}).

                map(function (account) {
                  var trial = journalEntries.getTrialBalance(account.id);
                  return {
                    account_id: account.id,
                    code: account.code,
                    accountNormal: account.type.normal,
                    credit: balanceFormatter(trial.credit),
                    debit: balanceFormatter(trial.debit),
                    balance: balanceFormatter(trial.balance) };

                });return _context4.abrupt("return",
                res.status(200).send({
                  query: _objectSpread({}, filter),
                  items: _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_0___default()(items) }));case 13:case "end":return _context4.stop();}}}, _callee4);}));function handler(_x7, _x8) {return _handler4.apply(this, arguments);}return handler;}() },




  /**
                                                                                                                                                                                                                 * Retrieve profit/loss financial statement.
                                                                                                                                                                                                                 */
  profitLossSheet: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('basis').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('from_date').optional().isISO8601(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('to_date').optional().isISO8601(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('number_format.no_cents').optional().isBoolean(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('number_format.divide_1000').optional().isBoolean(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('basis').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('none_zero').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('display_columns_by').optional().isIn(['year', 'month', 'week', 'day', 'quarter']),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('accounts').optional().isArray()],

    handler: function () {var _handler5 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee5(req, res) {var validationErrors, filter, incomeStatementTypes, accounts, filteredAccounts, journalEntriesCollected, journalEntries, numberFormatter, dateRangeSet, accountsIncome, accountsExpenses, totalAccountsIncome, totalAccountsExpenses, netIncome;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee5$(_context5) {while (1) {switch (_context5.prev = _context5.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context5.next = 3;break;}return _context5.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                filter = _objectSpread({
                  from_date: moment__WEBPACK_IMPORTED_MODULE_6___default()().startOf('year').format('YYYY-MM-DD'),
                  to_date: moment__WEBPACK_IMPORTED_MODULE_6___default()().endOf('year').format('YYYY-MM-DD'),
                  number_format: {
                    no_cents: false,
                    divide_1000: false },

                  basis: 'accural',
                  none_zero: false,
                  display_columns_by: 'month' },
                req.query);_context5.next = 6;return (

                  _models_AccountType__WEBPACK_IMPORTED_MODULE_11__["default"].query().where('income_sheet', true));case 6:incomeStatementTypes = _context5.sent;_context5.next = 9;return (

                  _models_Account__WEBPACK_IMPORTED_MODULE_12__["default"].query().
                  whereIn('account_type_id', incomeStatementTypes.map(function (t) {return t.id;})).
                  withGraphFetched('type').
                  withGraphFetched('transactions'));case 9:accounts = _context5.sent;

                filteredAccounts = accounts.filter(function (account) {
                  return account.transactions.length > 0 || !filter.none_zero;
                });
                journalEntriesCollected = _models_Account__WEBPACK_IMPORTED_MODULE_12__["default"].collectJournalEntries(accounts);
                journalEntries = new _services_Accounting_JournalPoster__WEBPACK_IMPORTED_MODULE_13__["default"]();
                journalEntries.loadEntries(journalEntriesCollected);

                // Account balance formmatter based on the given query.
                numberFormatter = formatNumberClosure(filter.number_format);

                // Gets the date range set from start to end date.
                dateRangeSet = Object(_utils__WEBPACK_IMPORTED_MODULE_14__["dateRangeCollection"])(
                filter.from_date,
                filter.to_date,
                filter.display_columns_by);

                accountsIncome = filteredAccounts.
                filter(function (account) {return account.type.normal === 'credit';}).
                map(function (account) {return _objectSpread({},
                  Object(lodash__WEBPACK_IMPORTED_MODULE_7__["pick"])(account, ['id', 'index', 'name', 'code']), {
                    dates: dateRangeSet.map(function (date) {
                      var type = filter.display_columns_by;
                      var amount = journalEntries.getClosingBalance(account.id, date, type);

                      return { date: date, rawAmount: amount, amount: numberFormatter(amount) };
                    }) });});


                accountsExpenses = filteredAccounts.
                filter(function (account) {return account.type.normal === 'debit';}).
                map(function (account) {return _objectSpread({},
                  Object(lodash__WEBPACK_IMPORTED_MODULE_7__["pick"])(account, ['id', 'index', 'name', 'code']), {
                    dates: dateRangeSet.map(function (date) {
                      var type = filter.display_columns_by;
                      var amount = journalEntries.getClosingBalance(account.id, date, type);

                      return { date: date, rawAmount: amount, amount: numberFormatter(amount) };
                    }) });});


                // Calculates the total income of income accounts.
                totalAccountsIncome = dateRangeSet.reduce(function (acc, date, index) {
                  var amount = 0;
                  accountsIncome.forEach(function (account) {
                    var currentDate = account.dates[index];
                    amount += currentDate.rawAmount || 0;
                  });
                  acc[date] = { date: date, rawAmount: amount, amount: numberFormatter(amount) };
                  return acc;
                }, {});

                // Calculates the total expenses of expenses accounts.
                totalAccountsExpenses = dateRangeSet.reduce(function (acc, date, index) {
                  var amount = 0;
                  accountsExpenses.forEach(function (account) {
                    var currentDate = account.dates[index];
                    amount += currentDate.rawAmount || 0;
                  });
                  acc[date] = { date: date, rawAmount: amount, amount: numberFormatter(amount) };
                  return acc;
                }, {});

                // Total income(date) - Total expenses(date) = Net income(date)
                netIncome = dateRangeSet.map(function (date) {
                  var totalIncome = totalAccountsIncome[date];
                  var totalExpenses = totalAccountsExpenses[date];

                  var amount = totalIncome.rawAmount || 0;
                  amount -= totalExpenses.rawAmount || 0;
                  return { date: date, rawAmount: amount, amount: numberFormatter(amount) };
                });return _context5.abrupt("return",

                res.status(200).send({
                  meta: _objectSpread({}, filter),
                  income: {
                    entry_normal: 'credit',
                    accounts: accountsIncome },

                  expenses: {
                    entry_normal: 'debit',
                    accounts: accountsExpenses },

                  total_income: Object.values(totalAccountsIncome),
                  total_expenses: Object.values(totalAccountsExpenses),
                  total_net_income: netIncome }));case 22:case "end":return _context5.stop();}}}, _callee5);}));function handler(_x9, _x10) {return _handler5.apply(this, arguments);}return handler;}() },




  cashFlowStatement: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('date_from').optional(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('date_to').optional()],

    handler: function () {var _handler6 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee6(req, res) {return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee6$(_context6) {while (1) {switch (_context6.prev = _context6.next) {case 0:return _context6.abrupt("return",

                res.status(200).send({
                  meta: {},
                  operating: [],
                  financing: [],
                  investing: [] }));case 1:case "end":return _context6.stop();}}}, _callee6);}));function handler(_x11, _x12) {return _handler6.apply(this, arguments);}return handler;}() } });

/***/ }),

/***/ "./src/http/controllers/ItemCategories.js":
/*!************************************************!*\
  !*** ./src/http/controllers/ItemCategories.js ***!
  \************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! express-validator */ "express-validator");
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(express_validator__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../middleware/asyncMiddleware */ "./src/http/middleware/asyncMiddleware.js");
/* harmony import */ var _models_ItemCategory__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/models/ItemCategory */ "./src/models/ItemCategory.js");
/* harmony import */ var _http_middleware_authorization__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/http/middleware/authorization */ "./src/http/middleware/authorization.js");
/* harmony import */ var _http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/http/middleware/jwtAuth */ "./src/http/middleware/jwtAuth.js");
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}






/* harmony default export */ __webpack_exports__["default"] = ({
  /**
                  * Router constructor method.
                  */
  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_3___default.a.Router();
    var permit = Object(_http_middleware_authorization__WEBPACK_IMPORTED_MODULE_7__["default"])('items_categories');

    router.use(_http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_8__["default"]);

    router.post('/:id',
    permit('create', 'edit'),
    this.editCategory.validation,
    Object(_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_5__["default"])(this.editCategory.handler));

    router.post('/',
    permit('create'),
    this.newCategory.validation,
    Object(_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_5__["default"])(this.newCategory.handler));

    router["delete"]('/:id',
    permit('create', 'edit', 'delete'),
    this.deleteItem.validation,
    Object(_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_5__["default"])(this.deleteItem.handler));

    router.get('/:id',
    permit('view'),
    this.getCategory.validation,
    Object(_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_5__["default"])(this.getCategory.handler));

    router.get('/',
    permit('view'),
    this.getList.validation,
    Object(_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_5__["default"])(this.getList.validation));

    return router;
  },

  /**
      * Creates a new item category.
      */
  newCategory: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('name').exists({ checkFalsy: true }).trim().escape(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('parent_category_id').optional().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('description').optional().trim().escape()],

    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(req, res) {var validationErrors, _req$body, name, parentCategoryId, description, foundParentCategory, category;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context.next = 3;break;}return _context.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:_req$body =



                req.body, name = _req$body.name, parentCategoryId = _req$body.parent_category_id, description = _req$body.description;if (!

                parentCategoryId) {_context.next = 10;break;}_context.next = 7;return (
                  _models_ItemCategory__WEBPACK_IMPORTED_MODULE_6__["default"].where('id', parentCategoryId).fetch());case 7:foundParentCategory = _context.sent;if (

                foundParentCategory) {_context.next = 10;break;}return _context.abrupt("return",
                res.boom.notFound('The parent category ID is not found.', {
                  errors: [{ type: 'PARENT_CATEGORY_NOT_FOUND', code: 100 }] }));case 10:_context.next = 12;return (



                  _models_ItemCategory__WEBPACK_IMPORTED_MODULE_6__["default"].forge({
                    label: name,
                    parent_category_id: parentCategoryId,
                    description: description }));case 12:category = _context.sent;_context.next = 15;return (


                  category.save());case 15:return _context.abrupt("return",
                res.status(200).send({ id: category.get('id') }));case 16:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                                        * Edit details of the given category item.
                                                                                                                                                                                                                        */
  editCategory: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["param"])('id').toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('name').exists({ checkFalsy: true }).trim().escape(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('parent_category_id').optional().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('description').optional().trim().escape()],

    handler: function () {var _handler2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(req, res) {var id, validationErrors, _req$body2, name, parentCategoryId, description, itemCategory, foundParentCategory;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
                id = req.params.id;
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context2.next = 4;break;}return _context2.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 4:_req$body2 =


                req.body, name = _req$body2.name, parentCategoryId = _req$body2.parent_category_id, description = _req$body2.description;_context2.next = 7;return (
                  _models_ItemCategory__WEBPACK_IMPORTED_MODULE_6__["default"].where('id', id).fetch());case 7:itemCategory = _context2.sent;if (

                itemCategory) {_context2.next = 10;break;}return _context2.abrupt("return",
                res.boom.notFound());case 10:if (!(

                parentCategoryId && parentCategoryId !== itemCategory.attributes.parent_category_id)) {_context2.next = 16;break;}_context2.next = 13;return (
                  _models_ItemCategory__WEBPACK_IMPORTED_MODULE_6__["default"].where('id', parentCategoryId).fetch());case 13:foundParentCategory = _context2.sent;if (

                foundParentCategory) {_context2.next = 16;break;}return _context2.abrupt("return",
                res.boom.notFound('The parent category ID is not found.', {
                  errors: [{ type: 'PARENT_CATEGORY_NOT_FOUND', code: 100 }] }));case 16:_context2.next = 18;return (



                  itemCategory.save({
                    label: name,
                    description: description,
                    parent_category_id: parentCategoryId }));case 18:return _context2.abrupt("return",


                res.status(200).send({ id: itemCategory.id }));case 19:case "end":return _context2.stop();}}}, _callee2);}));function handler(_x3, _x4) {return _handler2.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                                         * Delete the give item category.
                                                                                                                                                                                                                         */
  deleteItem: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["param"])('id').toInt()],

    handler: function () {var _handler3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(req, res) {var id, itemCategory;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
                id = req.params.id;_context3.next = 3;return (
                  _models_ItemCategory__WEBPACK_IMPORTED_MODULE_6__["default"].where('id', id).fetch());case 3:itemCategory = _context3.sent;if (

                itemCategory) {_context3.next = 6;break;}return _context3.abrupt("return",
                res.boom.notFound());case 6:_context3.next = 8;return (

                  itemCategory.destroy());case 8:return _context3.abrupt("return",
                res.status(200).send());case 9:case "end":return _context3.stop();}}}, _callee3);}));function handler(_x5, _x6) {return _handler3.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                 * Retrieve the list of items.
                                                                                                                                                                                                 */
  getList: {
    validation: [],
    handler: function () {var _handler4 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(req, res) {var items;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:_context4.next = 2;return (
                  _models_ItemCategory__WEBPACK_IMPORTED_MODULE_6__["default"].fetch());case 2:items = _context4.sent;if (

                items) {_context4.next = 5;break;}return _context4.abrupt("return",
                res.boom.notFound());case 5:return _context4.abrupt("return",

                res.status(200).send({ items: items.toJSON() }));case 6:case "end":return _context4.stop();}}}, _callee4);}));function handler(_x7, _x8) {return _handler4.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                                          * Retrieve details of the given category.
                                                                                                                                                                                                                          */
  getCategory: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["param"])('category_id').toInt()],

    handler: function () {var _handler5 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5(req, res) {var categoryId, item;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {while (1) {switch (_context5.prev = _context5.next) {case 0:
                categoryId = req.params.category_id;_context5.next = 3;return (
                  _models_ItemCategory__WEBPACK_IMPORTED_MODULE_6__["default"].where('id', categoryId).fetch());case 3:item = _context5.sent;if (

                item) {_context5.next = 6;break;}return _context5.abrupt("return",
                res.boom.notFound(null, {
                  errors: [{ type: 'CATEGORY_NOT_FOUND', code: 100 }] }));case 6:return _context5.abrupt("return",



                res.status(200).send({ category: item.toJSON() }));case 7:case "end":return _context5.stop();}}}, _callee5);}));function handler(_x9, _x10) {return _handler5.apply(this, arguments);}return handler;}() } });

/***/ }),

/***/ "./src/http/controllers/Items.js":
/*!***************************************!*\
  !*** ./src/http/controllers/Items.js ***!
  \***************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "@babel/runtime/helpers/slicedToArray");
/* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! express-validator */ "express-validator");
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(express_validator__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! moment */ "moment");
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(moment__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! lodash */ "lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/http/middleware/asyncMiddleware */ "./src/http/middleware/asyncMiddleware.js");
/* harmony import */ var _http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/http/middleware/jwtAuth */ "./src/http/middleware/jwtAuth.js");
/* harmony import */ var _models_Item__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/models/Item */ "./src/models/Item.js");
/* harmony import */ var _models_Account__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/models/Account */ "./src/models/Account.js");
/* harmony import */ var _models_ItemCategory__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/models/ItemCategory */ "./src/models/ItemCategory.js");
/* harmony import */ var _models_Resource__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @/models/Resource */ "./src/models/Resource.js");
/* harmony import */ var _models_ResourceField__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @/models/ResourceField */ "./src/models/ResourceField.js");
/* harmony import */ var _http_middleware_authorization__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @/http/middleware/authorization */ "./src/http/middleware/authorization.js");
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}












/* harmony default export */ __webpack_exports__["default"] = ({

  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_4___default.a.Router();
    var permit = Object(_http_middleware_authorization__WEBPACK_IMPORTED_MODULE_15__["default"])('items');

    router.use(_http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_9__["default"]);

    router.post('/:id',
    this.editItem.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_8__["default"])(this.editItem.handler));

    router.post('/',
    // permit('create'),
    this.newItem.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_8__["default"])(this.newItem.handler));

    router["delete"]('/:id',
    this.deleteItem.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_8__["default"])(this.deleteItem.handler));

    // router.get('/:id',
    //   this.getCategory.validation,
    //   asyncMiddleware(this.getCategory.handler));

    // router.get('/',
    //   this.categoriesList.validation,
    //   asyncMiddleware(this.categoriesList.validation));

    return router;
  },

  /**
      * Creates a new item.
      */
  newItem: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('name').exists(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('type').exists().trim().escape().isIn(['service', 'product']),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('cost_price').exists().isNumeric(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('sell_price').exists().isNumeric(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('cost_account_id').exists().isInt().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('sell_account_id').exists().isInt().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('category_id').optional().isInt().toInt(),

    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('custom_fields').optional().isArray({ min: 1 }),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('custom_fields.*.key').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('custom_fields.*.value').exists(),

    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('note').optional()],

    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(req, res) {var validationErrors, form, errorReasons, costAccountPromise, sellAccountPromise, itemCategoryPromise, customFieldsKeys, resource, fields, storedFieldsKey, notFoundFields, _ref, _ref2, costAccount, sellAccount, itemCategory, item;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context.next = 3;break;}return _context.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                form = _objectSpread({
                  custom_fields: [] },
                req.body);

                errorReasons = [];

                costAccountPromise = _models_Account__WEBPACK_IMPORTED_MODULE_11__["default"].query().findById(form.cost_account_id);
                sellAccountPromise = _models_Account__WEBPACK_IMPORTED_MODULE_11__["default"].query().findById(form.sell_account_id);
                itemCategoryPromise = form.category_id ?
                _models_ItemCategory__WEBPACK_IMPORTED_MODULE_12__["default"].query().findById(form.category_id) : null;

                // Validate the custom fields key and value type.
                if (!(form.custom_fields.length > 0)) {_context.next = 19;break;}
                customFieldsKeys = form.custom_fields.map(function (field) {return field.key;});

                // Get resource id than get all resource fields.
                _context.next = 12;return _models_Resource__WEBPACK_IMPORTED_MODULE_13__["default"].where('name', 'items').fetch();case 12:resource = _context.sent;_context.next = 15;return (
                  _models_ResourceField__WEBPACK_IMPORTED_MODULE_14__["default"].query(function (query) {
                    query.where('resource_id', resource.id);
                    query.whereIn('key', customFieldsKeys);
                  }).fetchAll());case 15:fields = _context.sent;

                storedFieldsKey = fields.map(function (f) {return f.attributes.key;});

                // Get all not defined resource fields.
                notFoundFields = Object(lodash__WEBPACK_IMPORTED_MODULE_7__["difference"])(customFieldsKeys, storedFieldsKey);

                if (notFoundFields.length > 0) {
                  errorReasons.push({ type: 'FIELD_KEY_NOT_FOUND', code: 150, fields: notFoundFields });
                }case 19:_context.next = 21;return (

                  Promise.all([
                  costAccountPromise, sellAccountPromise, itemCategoryPromise]));case 21:_ref = _context.sent;_ref2 = _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_1___default()(_ref, 3);costAccount = _ref2[0];sellAccount = _ref2[1];itemCategory = _ref2[2];

                if (!costAccount) {
                  errorReasons.push({ type: 'COST_ACCOUNT_NOT_FOUND', code: 100 });
                }
                if (!sellAccount) {
                  errorReasons.push({ type: 'SELL_ACCOUNT_NOT_FOUND', code: 120 });
                }
                if (!itemCategory && form.category_id) {
                  errorReasons.push({ type: 'ITEM_CATEGORY_NOT_FOUND', code: 140 });
                }if (!(
                errorReasons.length > 0)) {_context.next = 31;break;}return _context.abrupt("return",
                res.boom.badRequest(null, { errors: errorReasons }));case 31:_context.next = 33;return (

                  _models_Item__WEBPACK_IMPORTED_MODULE_10__["default"].query().insertAndFetch({
                    name: form.name,
                    type: form.type,
                    cost_price: form.cost_price,
                    sell_price: form.sell_price,
                    sell_account_id: form.sell_account_id,
                    cost_account_id: form.cost_account_id,
                    currency_code: form.currency_code,
                    note: form.note }));case 33:item = _context.sent;return _context.abrupt("return",

                res.status(200).send({ id: item.id }));case 35:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                             * Edit the given item.
                                                                                                                                                                                                             */
  editItem: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('name').exists(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('type').exists().trim().escape().isIn(['product', 'service']),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('cost_price').exists().isNumeric(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('sell_price').exists().isNumeric(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('cost_account_id').exists().isInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('sell_account_id').exists().isInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('category_id').optional().isInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('note').optional()],

    handler: function () {var _handler2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(req, res) {var validationErrors, id, form, item, errorReasons, costAccountPromise, sellAccountPromise, itemCategoryPromise, _ref3, _ref4, costAccount, sellAccount, itemCategory, updatedItem;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context2.next = 3;break;}return _context2.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:



                id = req.params.id;
                form = _objectSpread({
                  custom_fields: [] },
                req.body);_context2.next = 7;return (

                  _models_Item__WEBPACK_IMPORTED_MODULE_10__["default"].query().findById(id));case 7:item = _context2.sent;if (

                item) {_context2.next = 10;break;}return _context2.abrupt("return",
                res.boom.notFound(null, { errors: [
                  { type: 'ITEM.NOT.FOUND', code: 100 }] }));case 10:


                errorReasons = [];

                costAccountPromise = _models_Account__WEBPACK_IMPORTED_MODULE_11__["default"].query().findById(form.cost_account_id);
                sellAccountPromise = _models_Account__WEBPACK_IMPORTED_MODULE_11__["default"].query().findById(form.sell_account_id);
                itemCategoryPromise = form.category_id ?
                _models_ItemCategory__WEBPACK_IMPORTED_MODULE_12__["default"].query().findById(form.category_id) : null;_context2.next = 16;return (

                  Promise.all([
                  costAccountPromise, sellAccountPromise, itemCategoryPromise]));case 16:_ref3 = _context2.sent;_ref4 = _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_1___default()(_ref3, 3);costAccount = _ref4[0];sellAccount = _ref4[1];itemCategory = _ref4[2];

                if (!costAccount) {
                  errorReasons.push({ type: 'COST_ACCOUNT_NOT_FOUND', code: 100 });
                }
                if (!sellAccount) {
                  errorReasons.push({ type: 'SELL_ACCOUNT_NOT_FOUND', code: 120 });
                }
                if (!itemCategory && form.category_id) {
                  errorReasons.push({ type: 'ITEM_CATEGORY_NOT_FOUND', code: 140 });
                }if (!(
                errorReasons.length > 0)) {_context2.next = 26;break;}return _context2.abrupt("return",
                res.boom.badRequest(null, { errors: errorReasons }));case 26:_context2.next = 28;return (


                  _models_Item__WEBPACK_IMPORTED_MODULE_10__["default"].query().findById(id).patch({
                    name: form.name,
                    type: form.type,
                    cost_price: form.cost_price,
                    sell_price: form.sell_price,
                    currency_code: form.currency_code,
                    sell_account_id: form.sell_account_id,
                    cost_account_id: form.cost_account_id,
                    category_id: form.category_id,
                    note: form.note }));case 28:updatedItem = _context2.sent;return _context2.abrupt("return",

                res.status(200).send({ id: updatedItem.id }));case 30:case "end":return _context2.stop();}}}, _callee2);}));function handler(_x3, _x4) {return _handler2.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                                        * Delete the given item from the storage.
                                                                                                                                                                                                                        */
  deleteItem: {
    validation: [],
    handler: function () {var _handler3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(req, res) {var id, item;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
                id = req.params.id;_context3.next = 3;return (
                  _models_Item__WEBPACK_IMPORTED_MODULE_10__["default"].query().findById(id));case 3:item = _context3.sent;if (

                item) {_context3.next = 6;break;}return _context3.abrupt("return",
                res.boom.notFound(null, {
                  errors: [{ type: 'ITEM_NOT_FOUND', code: 100 }] }));case 6:_context3.next = 8;return (




                  _models_Item__WEBPACK_IMPORTED_MODULE_10__["default"].query().findById(item.id)["delete"]());case 8:return _context3.abrupt("return",

                res.status(200).send());case 9:case "end":return _context3.stop();}}}, _callee3);}));function handler(_x5, _x6) {return _handler3.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                 * Retrive the list items with pagination meta.
                                                                                                                                                                                                 */
  listItems: {
    validation: [],
    handler: function () {var _handler4 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_3___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(req, res) {var filter, items;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:
                filter = _objectSpread({
                  name: '',
                  description: '',
                  SKU: '',
                  account_id: null,
                  page_size: 10,
                  page: 1,
                  start_date: null,
                  end_date: null },
                req.query);_context4.next = 3;return (


                  _models_Item__WEBPACK_IMPORTED_MODULE_10__["default"].query(function (query) {
                    if (filter.description) {
                      query.where('description', 'like', "%".concat(filter.description, "%"));
                    }
                    if (filter.description) {
                      query.where('SKU', filter.SKY);
                    }
                    if (filter.name) {
                      query.where('name', filter.name);
                    }
                    if (filter.start_date) {
                      var startDateFormatted = moment__WEBPACK_IMPORTED_MODULE_6___default()(filter.start_date).format('YYYY-MM-DD HH:mm:SS');
                      query.where('created_at', '>=', startDateFormatted);
                    }
                    if (filter.end_date) {
                      var endDateFormatted = moment__WEBPACK_IMPORTED_MODULE_6___default()(filter.end_date).format('YYYY-MM-DD HH:mm:SS');
                      query.where('created_at', '<=', endDateFormatted);
                    }
                  }).fetchPage({
                    page_size: filter.page_size,
                    page: filter.page }));case 3:items = _context4.sent;return _context4.abrupt("return",


                res.status(200).send({
                  items: items.toJSON(),
                  pagination: items.pagination }));case 5:case "end":return _context4.stop();}}}, _callee4);}));function handler(_x7, _x8) {return _handler4.apply(this, arguments);}return handler;}() } });

/***/ }),

/***/ "./src/http/controllers/Options.js":
/*!*****************************************!*\
  !*** ./src/http/controllers/Options.js ***!
  \*****************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! express-validator */ "express-validator");
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(express_validator__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/http/middleware/asyncMiddleware */ "./src/http/middleware/asyncMiddleware.js");
/* harmony import */ var _models_Option__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/models/Option */ "./src/models/Option.js");
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}




/* harmony default export */ __webpack_exports__["default"] = ({
  /**
                  * Router constructor.
                  */
  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_3___default.a.Router();

    router.post('/',
    this.saveOptions.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_5__["default"])(this.saveOptions.handler));

    router.get('/',
    this.getOptions.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_5__["default"])(this.getSettings));

    return router;
  },

  /**
      * Saves the given options to the storage.
      */
  saveOptions: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["body"])('options').isArray(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["body"])('options.*.key').exists(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["body"])('options.*.value').exists(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["body"])('options.*.group').exists()],

    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(req, res) {var validationErrors, form, optionsCollections;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context.next = 3;break;}return _context.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'VALIDATION_ERROR' }, validationErrors)));case 3:


                form = _objectSpread({}, req.body);_context.next = 6;return (
                  _models_Option__WEBPACK_IMPORTED_MODULE_6__["default"].query());case 6:optionsCollections = _context.sent;

                form.options.forEach(function (option) {
                  optionsCollections.setMeta(option.key, option.value, option.group);
                });_context.next = 10;return (
                  optionsCollections.saveMeta());case 10:return _context.abrupt("return",

                res.status(200).send());case 11:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                              * Retrieve the application options from the storage.
                                                                                                                                                                                              */
  getOptions: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["query"])('key').optional()],

    handler: function () {var _handler2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(req, res) {var validationErrors, options;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context2.next = 3;break;}return _context2.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'VALIDATION_ERROR' }, validationErrors)));case 3:_context2.next = 5;return (


                  _models_Option__WEBPACK_IMPORTED_MODULE_6__["default"].query());case 5:options = _context2.sent;return _context2.abrupt("return",

                res.status(200).sends({ options: options }));case 7:case "end":return _context2.stop();}}}, _callee2);}));function handler(_x3, _x4) {return _handler2.apply(this, arguments);}return handler;}() } });

/***/ }),

/***/ "./src/http/controllers/Resources.js":
/*!*******************************************!*\
  !*** ./src/http/controllers/Resources.js ***!
  \*******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! express-validator */ "express-validator");
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(express_validator__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/http/middleware/asyncMiddleware */ "./src/http/middleware/asyncMiddleware.js");
/* harmony import */ var _http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/http/middleware/jwtAuth */ "./src/http/middleware/jwtAuth.js");
/* harmony import */ var _models_Resource__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/models/Resource */ "./src/models/Resource.js");






/* harmony default export */ __webpack_exports__["default"] = ({
  /**
                  * Router constructor.
                  */
  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_2___default.a.Router();

    router.use(_http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_5__["default"]);

    router.get('/:resource_slug/columns',
    this.resourceColumns.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_4__["default"])(this.resourceColumns.handler));

    router.get('/:resource_slug/fields',
    this.resourceFields.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_4__["default"])(this.resourceFields.handler));

    return router;
  },

  /**
      * Retrieve resource columns of the given resource.
      */
  resourceColumns: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["param"])('resource_slug').trim().escape().exists()],

    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(req, res) {var resourceSlug, resource, resourceFields;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
                resourceSlug = req.params.resource_slug;_context.next = 3;return (

                  _models_Resource__WEBPACK_IMPORTED_MODULE_6__["default"].query().
                  where('name', resourceSlug).
                  withGraphFetched('fields').
                  first());case 3:resource = _context.sent;if (

                resource) {_context.next = 6;break;}return _context.abrupt("return",
                res.status(400).send({
                  errors: [{ type: 'RESOURCE.SLUG.NOT.FOUND', code: 200 }] }));case 6:


                resourceFields = resource.fields.
                filter(function (field) {return field.columnable;}).
                map(function (field) {return {
                    id: field.id,
                    label: field.labelName,
                    key: field.key };});return _context.abrupt("return",


                res.status(200).send({
                  resource_columns: resourceFields,
                  resource_slug: resourceSlug }));case 8:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() },




  /**
                                                                                                                                                                                                       * Retrieve resource fields of the given resource.
                                                                                                                                                                                                       */
  resourceFields: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["param"])('resource_slug').trim().escape().exists(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["query"])('predefined').optional().isBoolean().toBoolean(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_3__["query"])('builtin').optional().isBoolean().toBoolean()],

    handler: function () {var _handler2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(req, res) {var resourceSlug, resource;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
                resourceSlug = req.params.resource_slug;_context2.next = 3;return (

                  _models_Resource__WEBPACK_IMPORTED_MODULE_6__["default"].query().
                  where('name', resourceSlug).
                  withGraphFetched('fields').
                  first());case 3:resource = _context2.sent;if (

                resource) {_context2.next = 6;break;}return _context2.abrupt("return",
                res.status(400).send({
                  errors: [{ type: 'RESOURCE.SLUG.NOT.FOUND', code: 200 }] }));case 6:return _context2.abrupt("return",


                res.status(200).send({
                  resource_fields: resource.fields,
                  resource_slug: resourceSlug }));case 7:case "end":return _context2.stop();}}}, _callee2);}));function handler(_x3, _x4) {return _handler2.apply(this, arguments);}return handler;}() } });

/***/ }),

/***/ "./src/http/controllers/Roles.js":
/*!***************************************!*\
  !*** ./src/http/controllers/Roles.js ***!
  \***************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/toConsumableArray */ "@babel/runtime/helpers/toConsumableArray");
/* harmony import */ var _babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/slicedToArray */ "@babel/runtime/helpers/slicedToArray");
/* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! express-validator */ "express-validator");
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(express_validator__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! lodash */ "lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/http/middleware/asyncMiddleware */ "./src/http/middleware/asyncMiddleware.js");
/* harmony import */ var _models_Role__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/models/Role */ "./src/models/Role.js");
/* harmony import */ var _models_Permission__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/models/Permission */ "./src/models/Permission.js");
/* harmony import */ var _models_Resource__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/models/Resource */ "./src/models/Resource.js");
/* harmony import */ var _database_knex__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/database/knex */ "./src/database/knex.js");
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;} /* eslint-disable no-unused-vars */









var AccessControllSchema = [
{
  resource: 'items',
  label: 'products_services',
  permissions: ['create', 'edit', 'delete', 'view'],
  fullAccess: true,
  ownControl: true }];



var getResourceSchema = function getResourceSchema(resource) {return AccessControllSchema.
  find(function (schema) {return schema.resource === resource;});};

var getResourcePermissions = function getResourcePermissions(resource) {
  var foundResource = getResourceSchema(resource);
  return foundResource ? foundResource.permissions : [];
};

var findNotFoundResources = function findNotFoundResources(resourcesSlugs) {
  var schemaResourcesSlugs = AccessControllSchema.map(function (s) {return s.resource;});
  return Object(lodash__WEBPACK_IMPORTED_MODULE_7__["difference"])(resourcesSlugs, schemaResourcesSlugs);
};

var findNotFoundPermissions = function findNotFoundPermissions(permissions, resourceSlug) {
  var schemaPermissions = getResourcePermissions(resourceSlug);
  return Object(lodash__WEBPACK_IMPORTED_MODULE_7__["difference"])(permissions, schemaPermissions);
};

/* harmony default export */ __webpack_exports__["default"] = ({
  /**
                  * Router constructor method.
                  */
  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_5___default.a.Router();

    router.post('/',
    this.newRole.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_8__["default"])(this.newRole.handler));

    router.post('/:id',
    this.editRole.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_8__["default"])(this.editRole.handler.bind(this)));

    router["delete"]('/:id',
    this.deleteRole.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_8__["default"])(this.deleteRole.handler));

    return router;
  },

  /**
      * Creates a new role.
      */
  newRole: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('name').exists().trim().escape(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('description').optional().trim().escape(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('permissions').isArray({ min: 0 }),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('permissions.*.resource_slug').exists().whitelist('^[a-z0-9]+(?:-[a-z0-9]+)*$'),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('permissions.*.permissions').isArray({ min: 1 })],

    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(req, res) {var validationErrors, _req$body, name, description, permissions, resourcesSlugs, permissionsSlugs, resourcesNotFound, errorReasons, notFoundPermissions, _ref, _ref2, resourcesCollection, permsCollection, notStoredResources, notStoredPermissions, insertThread, _ref3, _ref4, storedPermissions, storedResources, storedResourcesSet, storedPermissionsSet, role, roleHasPerms;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context.next = 3;break;}return _context.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:_req$body =


                req.body, name = _req$body.name, description = _req$body.description, permissions = _req$body.permissions;

                resourcesSlugs = permissions.map(function (perm) {return perm.resource_slug;});
                permissionsSlugs = [];
                resourcesNotFound = findNotFoundResources(resourcesSlugs);

                errorReasons = [];
                notFoundPermissions = [];

                if (resourcesNotFound.length > 0) {
                  errorReasons.push({
                    type: 'RESOURCE_SLUG_NOT_FOUND', code: 100, resources: resourcesNotFound });

                }
                permissions.forEach(function (perm) {
                  var abilities = perm.permissions.map(function (ability) {return ability;});

                  // Gets the not found permissions in the schema.
                  var notFoundAbilities = findNotFoundPermissions(abilities, perm.resource_slug);

                  if (notFoundAbilities.length > 0) {
                    notFoundPermissions.push({
                      resource_slug: perm.resource_slug,
                      permissions: notFoundAbilities });

                  } else {
                    var perms = perm.permissions || [];
                    perms.forEach(function (permission) {
                      if (perms.indexOf(permission) !== -1) {
                        permissionsSlugs.push(permission);
                      }
                    });
                  }
                });
                if (notFoundPermissions.length > 0) {
                  errorReasons.push({
                    type: 'PERMISSIONS_SLUG_NOT_FOUND',
                    code: 200,
                    permissions: notFoundPermissions });

                }if (!(
                errorReasons.length > 0)) {_context.next = 14;break;}return _context.abrupt("return",
                res.boom.badRequest(null, { errors: errorReasons }));case 14:_context.next = 16;return (


                  Promise.all([
                  _models_Resource__WEBPACK_IMPORTED_MODULE_11__["default"].query(function (query) {query.whereIn('name', resourcesSlugs);}).fetchAll(),
                  _models_Permission__WEBPACK_IMPORTED_MODULE_10__["default"].query(function (query) {query.whereIn('name', permissionsSlugs);}).fetchAll()]));case 16:_ref = _context.sent;_ref2 = _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2___default()(_ref, 2);resourcesCollection = _ref2[0];permsCollection = _ref2[1];


                notStoredResources = Object(lodash__WEBPACK_IMPORTED_MODULE_7__["difference"])(
                resourcesSlugs, resourcesCollection.map(function (s) {return s.name;}));

                notStoredPermissions = Object(lodash__WEBPACK_IMPORTED_MODULE_7__["difference"])(
                permissionsSlugs, permsCollection.map(function (perm) {return perm.slug;}));


                insertThread = [];

                if (notStoredResources.length > 0) {
                  insertThread.push(Object(_database_knex__WEBPACK_IMPORTED_MODULE_12__["default"])('resources').insert(_babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_1___default()(
                  notStoredResources.map(function (resource) {return { name: resource };}))));

                }
                if (notStoredPermissions.length > 0) {
                  insertThread.push(Object(_database_knex__WEBPACK_IMPORTED_MODULE_12__["default"])('permissions').insert(_babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_1___default()(
                  notStoredPermissions.map(function (permission) {return { name: permission };}))));

                }_context.next = 27;return (

                  Promise.all(insertThread));case 27:_context.next = 29;return (

                  Promise.all([
                  _models_Permission__WEBPACK_IMPORTED_MODULE_10__["default"].query(function (q) {q.whereIn('name', permissionsSlugs);}).fetchAll(),
                  _models_Resource__WEBPACK_IMPORTED_MODULE_11__["default"].query(function (q) {q.whereIn('name', resourcesSlugs);}).fetchAll()]));case 29:_ref3 = _context.sent;_ref4 = _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2___default()(_ref3, 2);storedPermissions = _ref4[0];storedResources = _ref4[1];


                storedResourcesSet = new Map(storedResources.map(function (resource) {return [
                  resource.attributes.name, resource.attributes.id];}));

                storedPermissionsSet = new Map(storedPermissions.map(function (perm) {return [
                  perm.attributes.name, perm.attributes.id];}));

                role = _models_Role__WEBPACK_IMPORTED_MODULE_9__["default"].forge({ name: name, description: description });_context.next = 38;return (

                  role.save());case 38:

                roleHasPerms = permissions.map(function (resource) {return resource.permissions.map(function (perm) {return {
                      role_id: role.id,
                      resource_id: storedResourcesSet.get(resource.resource_slug),
                      permission_id: storedPermissionsSet.get(perm) };});});if (!(


                roleHasPerms.length > 0)) {_context.next = 42;break;}_context.next = 42;return (
                  Object(_database_knex__WEBPACK_IMPORTED_MODULE_12__["default"])('role_has_permissions').insert(roleHasPerms[0]));case 42:return _context.abrupt("return",

                res.status(200).send({ id: role.get('id') }));case 43:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                                    * Edit the give role.
                                                                                                                                                                                                                    */
  editRole: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('name').exists().trim().escape(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('description').optional().trim().escape(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('permissions').isArray({ min: 0 }),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('permissions.*.resource_slug').exists().whitelist('^[a-z0-9]+(?:-[a-z0-9]+)*$'),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["check"])('permissions.*.permissions').isArray({ min: 1 })],

    handler: function () {var _handler2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(req, res) {var validationErrors, id, role, permissions, errorReasons, permissionsSlugs, notFoundPermissions, resourcesSlugs, resourcesNotFound, _ref5, _ref6, resourcesCollection, permsCollection, notStoredResources, notStoredPermissions, insertThread, _ref7, _ref8, storedPermissions, storedResources, storedResourcesSet, storedPermissionsSet, savedRoleHasPerms;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_6__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context2.next = 3;break;}return _context2.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:



                id = req.params.id;_context2.next = 6;return (
                  _models_Role__WEBPACK_IMPORTED_MODULE_9__["default"].where('id', id).fetch());case 6:role = _context2.sent;if (

                role) {_context2.next = 9;break;}return _context2.abrupt("return",
                res.boom.notFound(null, {
                  errors: [{ type: 'ROLE_NOT_FOUND', code: 100 }] }));case 9:



                permissions = req.body.permissions;
                errorReasons = [];
                permissionsSlugs = [];
                notFoundPermissions = [];

                resourcesSlugs = permissions.map(function (perm) {return perm.resource_slug;});
                resourcesNotFound = findNotFoundResources(resourcesSlugs);

                if (resourcesNotFound.length > 0) {
                  errorReasons.push({
                    type: 'RESOURCE_SLUG_NOT_FOUND',
                    code: 100,
                    resources: resourcesNotFound });

                }

                permissions.forEach(function (perm) {
                  var abilities = perm.permissions.map(function (ability) {return ability;});
                  // Gets the not found permissions in the schema.
                  var notFoundAbilities = findNotFoundPermissions(abilities, perm.resource_slug);

                  if (notFoundAbilities.length > 0) {
                    notFoundPermissions.push({
                      resource_slug: perm.resource_slug, permissions: notFoundAbilities });

                  } else {
                    var perms = perm.permissions || [];
                    perms.forEach(function (permission) {
                      if (perms.indexOf(permission) !== -1) {
                        permissionsSlugs.push(permission);
                      }
                    });
                  }
                });

                if (notFoundPermissions.length > 0) {
                  errorReasons.push({
                    type: 'PERMISSIONS_SLUG_NOT_FOUND',
                    code: 200,
                    permissions: notFoundPermissions });

                }if (!(
                errorReasons.length > 0)) {_context2.next = 20;break;}return _context2.abrupt("return",
                res.boom.badRequest(null, { errors: errorReasons }));case 20:_context2.next = 22;return (



                  Promise.all([
                  _models_Resource__WEBPACK_IMPORTED_MODULE_11__["default"].query(function (query) {query.whereIn('name', resourcesSlugs);}).fetchAll(),
                  _models_Permission__WEBPACK_IMPORTED_MODULE_10__["default"].query(function (query) {query.whereIn('name', permissionsSlugs);}).fetchAll()]));case 22:_ref5 = _context2.sent;_ref6 = _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2___default()(_ref5, 2);resourcesCollection = _ref6[0];permsCollection = _ref6[1];


                notStoredResources = Object(lodash__WEBPACK_IMPORTED_MODULE_7__["difference"])(
                resourcesSlugs, resourcesCollection.map(function (s) {return s.name;}));

                notStoredPermissions = Object(lodash__WEBPACK_IMPORTED_MODULE_7__["difference"])(
                permissionsSlugs, permsCollection.map(function (perm) {return perm.slug;}));

                insertThread = [];

                if (notStoredResources.length > 0) {
                  insertThread.push(Object(_database_knex__WEBPACK_IMPORTED_MODULE_12__["default"])('resources').insert(_babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_1___default()(
                  notStoredResources.map(function (resource) {return { name: resource };}))));

                }
                if (notStoredPermissions.length > 0) {
                  insertThread.push(Object(_database_knex__WEBPACK_IMPORTED_MODULE_12__["default"])('permissions').insert(_babel_runtime_helpers_toConsumableArray__WEBPACK_IMPORTED_MODULE_1___default()(
                  notStoredPermissions.map(function (permission) {return { name: permission };}))));

                }_context2.next = 33;return (

                  Promise.all(insertThread));case 33:_context2.next = 35;return (

                  Promise.all([
                  _models_Permission__WEBPACK_IMPORTED_MODULE_10__["default"].query(function (q) {q.whereIn('name', permissionsSlugs);}).fetchAll(),
                  _models_Resource__WEBPACK_IMPORTED_MODULE_11__["default"].query(function (q) {q.whereIn('name', resourcesSlugs);}).fetchAll()]));case 35:_ref7 = _context2.sent;_ref8 = _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_2___default()(_ref7, 2);storedPermissions = _ref8[0];storedResources = _ref8[1];


                storedResourcesSet = new Map(storedResources.map(function (resource) {return [
                  resource.attributes.name, resource.attributes.id];}));

                storedPermissionsSet = new Map(storedPermissions.map(function (perm) {return [
                  perm.attributes.name, perm.attributes.id];}));_context2.next = 43;return (


                  role.save());case 43:_context2.next = 45;return (


                  Object(_database_knex__WEBPACK_IMPORTED_MODULE_12__["default"])('role_has_permissions').where({
                    role_id: role.id }));case 45:savedRoleHasPerms = _context2.sent;


                console.log(savedRoleHasPerms);

                // const roleHasPerms = permissions.map((resource) => resource.permissions.map((perm) => ({
                //   role_id: role.id,
                //   resource_id: storedResourcesSet.get(resource.resource_slug),
                //   permission_id: storedPermissionsSet.get(perm),
                // })));

                // if (roleHasPerms.length > 0) {
                //   await knex('role_has_permissions').insert(roleHasPerms[0]);
                // }
                return _context2.abrupt("return", res.status(200).send({ id: role.get('id') }));case 48:case "end":return _context2.stop();}}}, _callee2);}));function handler(_x3, _x4) {return _handler2.apply(this, arguments);}return handler;}() },



  deleteRole: {
    validation: [],
    handler: function () {var _handler3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_4___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(req, res) {var id, role;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
                id = req.params.id;_context3.next = 3;return (
                  _models_Role__WEBPACK_IMPORTED_MODULE_9__["default"].where('id', id).fetch());case 3:role = _context3.sent;if (

                role) {_context3.next = 6;break;}return _context3.abrupt("return",
                res.boom.notFound());case 6:if (!

                role.attributes.predefined) {_context3.next = 8;break;}return _context3.abrupt("return",
                res.boom.badRequest(null, {
                  errors: [{ type: 'ROLE_PREDEFINED', code: 100 }] }));case 8:_context3.next = 10;return (



                  Object(_database_knex__WEBPACK_IMPORTED_MODULE_12__["default"])('role_has_permissions').
                  where('role_id', role.id)["delete"]({ require: false }));case 10:_context3.next = 12;return (

                  role.destroy());case 12:return _context3.abrupt("return",

                res.status(200).send());case 13:case "end":return _context3.stop();}}}, _callee3);}));function handler(_x5, _x6) {return _handler3.apply(this, arguments);}return handler;}() },



  getRole: {
    validation: [],
    handler: function handler(req, res) {
      return res.status(200).send();
    } } });

/***/ }),

/***/ "./src/http/controllers/Suppliers.js":
/*!*******************************************!*\
  !*** ./src/http/controllers/Suppliers.js ***!
  \*******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_0__);


/* harmony default export */ __webpack_exports__["default"] = ({

  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_0___default.a.Router();

    return router;
  } });

/***/ }),

/***/ "./src/http/controllers/Users.js":
/*!***************************************!*\
  !*** ./src/http/controllers/Users.js ***!
  \***************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! express-validator */ "express-validator");
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(express_validator__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _models_User__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/models/User */ "./src/models/User.js");
/* harmony import */ var _http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/http/middleware/asyncMiddleware */ "./src/http/middleware/asyncMiddleware.js");
/* harmony import */ var _http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/http/middleware/jwtAuth */ "./src/http/middleware/jwtAuth.js");
/* harmony import */ var _http_middleware_authorization__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/http/middleware/authorization */ "./src/http/middleware/authorization.js");
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}






/* harmony default export */ __webpack_exports__["default"] = ({

  /**
                  * Router constructor.
                  */
  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_3___default.a.Router();
    // const permit = Authorization('users');

    router.use(_http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_7__["default"]);

    router.post('/',
    // permit('create'),
    this.newUser.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_6__["default"])(this.newUser.handler));

    router.post('/:id',
    // permit('create', 'edit'),
    this.editUser.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_6__["default"])(this.editUser.handler));

    router.get('/',
    // permit('view'),
    this.listUsers.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_6__["default"])(this.listUsers.handler));

    router.get('/:id',
    // permit('view'),
    this.getUser.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_6__["default"])(this.getUser.handler));

    router["delete"]('/:id',
    // permit('create', 'edit', 'delete'),
    this.deleteUser.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_6__["default"])(this.deleteUser.handler));

    return router;
  },

  /**
      * Creates a new user.
      */
  newUser: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('first_name').trim().escape().exists(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('last_name').trim().escape().exists(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('email').exists().isEmail(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('phone_number').optional().isMobilePhone(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('password').isLength({ min: 4 }).exists().custom(function (value, _ref) {var req = _ref.req;
      if (value !== req.body.confirm_password) {
        throw new Error("Passwords don't match");
      } else {
        return value;
      }
    }),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('status').exists().isBoolean().toBoolean()],

    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(req, res) {var validationErrors, _req$body, email, phoneNumber, foundUsers, foundUserEmail, foundUserPhone, errorReasons, user;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context.next = 3;break;}return _context.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:_req$body =


                req.body, email = _req$body.email, phoneNumber = _req$body.phone_number;_context.next = 6;return (

                  _models_User__WEBPACK_IMPORTED_MODULE_5__["default"].query().
                  where('email', email).
                  orWhere('phone_number', phoneNumber));case 6:foundUsers = _context.sent;

                foundUserEmail = foundUsers.find(function (u) {return u.email === email;});
                foundUserPhone = foundUsers.find(function (u) {return u.phoneNumber === phoneNumber;});

                errorReasons = [];

                if (foundUserEmail) {
                  errorReasons.push({ type: 'EMAIL_ALREADY_EXIST', code: 100 });
                }
                if (foundUserPhone) {
                  errorReasons.push({ type: 'PHONE_NUMBER_ALREADY_EXIST', code: 120 });
                }if (!(
                errorReasons.length > 0)) {_context.next = 14;break;}return _context.abrupt("return",
                res.boom.badRequest(null, { errors: errorReasons }));case 14:_context.next = 16;return (


                  _models_User__WEBPACK_IMPORTED_MODULE_5__["default"].query().insert({
                    first_name: req.body.first_name,
                    last_name: req.body.last_name,
                    email: req.body.email,
                    phone_number: req.body.phone_number,
                    active: req.body.status }));case 16:user = _context.sent;return _context.abrupt("return",


                res.status(200).send({ user: user }));case 18:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                            * Edit details of the given user.
                                                                                                                                                                                                            */
  editUser: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["param"])('id').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('first_name').exists(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('last_name').exists(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('email').exists().isEmail(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('phone_number').optional().isMobilePhone(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('password').isLength({ min: 4 }).exists().custom(function (value, _ref2) {var req = _ref2.req;
      if (value !== req.body.confirm_password) {
        throw new Error("Passwords don't match");
      } else {
        return value;
      }
    }),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["check"])('status').exists().isBoolean().toBoolean()],

    handler: function () {var _handler2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(req, res) {var id, validationErrors, user, _req$body2, email, phoneNumber, foundUsers, foundUserEmail, foundUserPhone, errorReasons;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
                id = req.params.id;
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context2.next = 4;break;}return _context2.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 4:_context2.next = 6;return (


                  _models_User__WEBPACK_IMPORTED_MODULE_5__["default"].query().where('id', id).first());case 6:user = _context2.sent;if (

                user) {_context2.next = 9;break;}return _context2.abrupt("return",
                res.boom.notFound());case 9:_req$body2 =

                req.body, email = _req$body2.email, phoneNumber = _req$body2.phone_number;_context2.next = 12;return (

                  _models_User__WEBPACK_IMPORTED_MODULE_5__["default"].query().
                  whereNot('id', id).
                  andWhere(function (q) {
                    q.where('email', email);
                    q.orWhere('phone_number', phoneNumber);
                  }));case 12:foundUsers = _context2.sent;

                foundUserEmail = foundUsers.find(function (u) {return u.email === email;});
                foundUserPhone = foundUsers.find(function (u) {return u.phoneNumber === phoneNumber;});

                errorReasons = [];

                if (foundUserEmail) {
                  errorReasons.push({ type: 'EMAIL_ALREADY_EXIST', code: 100 });
                }
                if (foundUserPhone) {
                  errorReasons.push({ type: 'PHONE_NUMBER_ALREADY_EXIST', code: 120 });
                }if (!(
                errorReasons.length > 0)) {_context2.next = 20;break;}return _context2.abrupt("return",
                res.boom.badRequest(null, { errors: errorReasons }));case 20:_context2.next = 22;return (


                  _models_User__WEBPACK_IMPORTED_MODULE_5__["default"].query().where('id', id).update({
                    first_name: req.body.first_name,
                    last_name: req.body.last_name,
                    email: req.body.email,
                    phone_number: req.body.phone_number,
                    active: req.body.status }));case 22:return _context2.abrupt("return",

                res.status(200).send());case 23:case "end":return _context2.stop();}}}, _callee2);}));function handler(_x3, _x4) {return _handler2.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                  * Soft deleting the given user.
                                                                                                                                                                                                  */
  deleteUser: {
    validation: [],
    handler: function () {var _handler3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(req, res) {var id, user;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
                id = req.params.id;_context3.next = 3;return (
                  _models_User__WEBPACK_IMPORTED_MODULE_5__["default"].query().where('id', id).first());case 3:user = _context3.sent;if (

                user) {_context3.next = 6;break;}return _context3.abrupt("return",
                res.boom.notFound(null, {
                  errors: [{ type: 'USER_NOT_FOUND', code: 100 }] }));case 6:_context3.next = 8;return (


                  _models_User__WEBPACK_IMPORTED_MODULE_5__["default"].query().where('id', id)["delete"]());case 8:return _context3.abrupt("return",

                res.status(200).send());case 9:case "end":return _context3.stop();}}}, _callee3);}));function handler(_x5, _x6) {return _handler3.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                 * Retrieve user details of the given user id.
                                                                                                                                                                                                 */
  getUser: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["param"])('id').exists().isNumeric().toInt()],

    handler: function () {var _handler4 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(req, res) {var id, user;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:
                id = req.params.id;_context4.next = 3;return (
                  _models_User__WEBPACK_IMPORTED_MODULE_5__["default"].query().where('id', id).first());case 3:user = _context4.sent;if (

                user) {_context4.next = 6;break;}return _context4.abrupt("return",
                res.boom.notFound());case 6:return _context4.abrupt("return",

                res.status(200).send({ user: user }));case 7:case "end":return _context4.stop();}}}, _callee4);}));function handler(_x7, _x8) {return _handler4.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                               * Retrieve the list of users.
                                                                                                                                                                                                               */
  listUsers: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["query"])('page_size').optional().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_4__["query"])('page').optional().isNumeric().toInt()],

    handler: function () {var _handler5 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5(req, res) {var filter, users;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {while (1) {switch (_context5.prev = _context5.next) {case 0:
                filter = _objectSpread({
                  first_name: '',
                  last_name: '',
                  email: '',
                  phone_number: '',

                  page_size: 10,
                  page: 1 },
                req.query);_context5.next = 3;return (


                  _models_User__WEBPACK_IMPORTED_MODULE_5__["default"].query().
                  page(filter.page - 1, filter.page_size));case 3:users = _context5.sent;return _context5.abrupt("return",

                res.status(200).send({ users: users }));case 5:case "end":return _context5.stop();}}}, _callee5);}));function handler(_x9, _x10) {return _handler5.apply(this, arguments);}return handler;}() } });

/***/ }),

/***/ "./src/http/controllers/Views.js":
/*!***************************************!*\
  !*** ./src/http/controllers/Views.js ***!
  \***************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! lodash */ "lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! express */ "express");
/* harmony import */ var express__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(express__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! express-validator */ "express-validator");
/* harmony import */ var express_validator__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(express_validator__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/http/middleware/asyncMiddleware */ "./src/http/middleware/asyncMiddleware.js");
/* harmony import */ var _http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/http/middleware/jwtAuth */ "./src/http/middleware/jwtAuth.js");
/* harmony import */ var _models_Resource__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/models/Resource */ "./src/models/Resource.js");
/* harmony import */ var _models_View__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/models/View */ "./src/models/View.js");
/* harmony import */ var _models_ViewRole__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/models/ViewRole */ "./src/models/ViewRole.js");
/* harmony import */ var _models_ViewColumn__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/models/ViewColumn */ "./src/models/ViewColumn.js");
/* harmony import */ var _lib_ViewRolesBuilder__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/lib/ViewRolesBuilder */ "./src/lib/ViewRolesBuilder/index.js");
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}










/* harmony default export */ __webpack_exports__["default"] = ({
  resource: 'items',

  /**
                      * Router constructor.
                      */
  router: function router() {
    var router = express__WEBPACK_IMPORTED_MODULE_4___default.a.Router();

    router.use(_http_middleware_jwtAuth__WEBPACK_IMPORTED_MODULE_7__["default"]);

    router.get('/',
    this.listViews.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_6__["default"])(this.listViews.handler));

    router.post('/',
    this.createView.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_6__["default"])(this.createView.handler));

    router.post('/:view_id',
    this.editView.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_6__["default"])(this.editView.handler));

    router["delete"]('/:view_id',
    this.deleteView.validation,
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_6__["default"])(this.deleteView.handler));

    router.get('/:view_id',
    Object(_http_middleware_asyncMiddleware__WEBPACK_IMPORTED_MODULE_6__["default"])(this.getView.handler));

    return router;
  },

  /**
      * List all views that associated with the given resource.
      */
  listViews: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["oneOf"])([
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('resource_name').exists().trim().escape()],
    [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["query"])('resource_id').exists().isNumeric().toInt()])],


    handler: function () {var _handler = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(req, res) {var filter, resource, views;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:
                filter = _objectSpread({}, req.query);_context.next = 3;return (

                  _models_Resource__WEBPACK_IMPORTED_MODULE_8__["default"].query().onBuild(function (builder) {
                    if (filter.resource_id) {
                      builder.where('id', filter.resource_id);
                    }
                    if (filter.resource_name) {
                      builder.where('name', filter.resource_name);
                    }
                    builder.first();
                  }));case 3:resource = _context.sent;_context.next = 6;return (

                  _models_View__WEBPACK_IMPORTED_MODULE_9__["default"].query().where('resource_id', resource.id));case 6:views = _context.sent;return _context.abrupt("return",

                res.status(200).send({ views: views }));case 8:case "end":return _context.stop();}}}, _callee);}));function handler(_x, _x2) {return _handler.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                             * Retrieve view details of the given view id.
                                                                                                                                                                                                             */
  getView: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["param"])('view_id').exists().isNumeric().toInt()],

    handler: function () {var _handler2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(req, res) {var viewId, view;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:
                viewId = req.params.view_id;_context2.next = 3;return (
                  _models_View__WEBPACK_IMPORTED_MODULE_9__["default"].query().
                  where('id', viewId).
                  withGraphFetched('resource').
                  withGraphFetched('columns').
                  withGraphFetched('roles.field').
                  first());case 3:view = _context2.sent;if (

                view) {_context2.next = 6;break;}return _context2.abrupt("return",
                res.boom.notFound(null, {
                  errors: [{ type: 'VIEW_NOT_FOUND', code: 100 }] }));case 6:return _context2.abrupt("return",


                res.status(200).send({ view: view.toJSON() }));case 7:case "end":return _context2.stop();}}}, _callee2);}));function handler(_x3, _x4) {return _handler2.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                                        * Delete the given view of the resource.
                                                                                                                                                                                                                        */
  deleteView: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["param"])('view_id').exists().isNumeric().toInt()],

    handler: function () {var _handler3 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(req, res) {var viewId, view;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
                viewId = req.params.view_id;_context3.next = 3;return (
                  _models_View__WEBPACK_IMPORTED_MODULE_9__["default"].query().findById(viewId));case 3:view = _context3.sent;if (

                view) {_context3.next = 6;break;}return _context3.abrupt("return",
                res.boom.notFound(null, {
                  errors: [{ type: 'VIEW_NOT_FOUND', code: 100 }] }));case 6:if (!


                view.predefined) {_context3.next = 8;break;}return _context3.abrupt("return",
                res.boom.badRequest(null, {
                  errors: [{ type: 'PREDEFINED_VIEW', code: 200 }] }));case 8:_context3.next = 10;return (


                  Promise.all([
                  view.$relatedQuery('roles')["delete"](),
                  view.$relatedQuery('columns')["delete"]()]));case 10:_context3.next = 12;return (

                  _models_View__WEBPACK_IMPORTED_MODULE_9__["default"].query().where('id', view.id)["delete"]());case 12:return _context3.abrupt("return",

                res.status(200).send({ id: view.id }));case 13:case "end":return _context3.stop();}}}, _callee3);}));function handler(_x5, _x6) {return _handler3.apply(this, arguments);}return handler;}() },



  /**
                                                                                                                                                                                                                 * Creates a new view.
                                                                                                                                                                                                                 */
  createView: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('resource_name').exists().escape().trim(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('name').exists().escape().trim(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('logic_expression').exists().trim().escape(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('roles').isArray({ min: 1 }),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('roles.*.field_key').exists().escape().trim(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('roles.*.comparator').exists(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('roles.*.value').exists(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('roles.*.index').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('columns').exists().isArray({ min: 1 }),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('columns.*.key').exists().escape().trim(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('columns.*.index').exists().isNumeric().toInt()],

    handler: function () {var _handler4 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(req, res) {var validationErrors, form, resource, errorReasons, fieldsSlugs, resourceFields, resourceFieldsKeys, resourceFieldsKeysMap, columnsKeys, notFoundFields, notFoundColumns, view, saveViewRolesOpers;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context4.next = 3;break;}return _context4.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 3:


                form = _objectSpread({}, req.body);_context4.next = 6;return (
                  _models_Resource__WEBPACK_IMPORTED_MODULE_8__["default"].query().where('name', form.resource_name).first());case 6:resource = _context4.sent;if (

                resource) {_context4.next = 9;break;}return _context4.abrupt("return",
                res.boom.notFound(null, {
                  errors: [{ type: 'RESOURCE_NOT_FOUND', code: 100 }] }));case 9:


                errorReasons = [];
                fieldsSlugs = form.roles.map(function (role) {return role.field_key;});_context4.next = 13;return (

                  resource.$relatedQuery('fields'));case 13:resourceFields = _context4.sent;
                resourceFieldsKeys = resourceFields.map(function (f) {return f.key;});
                resourceFieldsKeysMap = new Map(resourceFields.map(function (field) {return [field.key, field];}));
                columnsKeys = form.columns.map(function (c) {return c.key;});

                // The difference between the stored resource fields and submit fields keys.
                notFoundFields = Object(lodash__WEBPACK_IMPORTED_MODULE_3__["difference"])(fieldsSlugs, resourceFieldsKeys);

                if (notFoundFields.length > 0) {
                  errorReasons.push({ type: 'RESOURCE_FIELDS_NOT_EXIST', code: 100, fields: notFoundFields });
                }
                // The difference between the stored resource fields and the submit columns keys.
                notFoundColumns = Object(lodash__WEBPACK_IMPORTED_MODULE_3__["difference"])(columnsKeys, resourceFieldsKeys);

                if (notFoundColumns.length > 0) {
                  errorReasons.push({ type: 'COLUMNS_NOT_EXIST', code: 200, columns: notFoundColumns });
                }
                // Validates the view conditional logic expression.
                if (!Object(_lib_ViewRolesBuilder__WEBPACK_IMPORTED_MODULE_12__["validateViewLogicExpression"])(form.logic_expression, form.roles.map(function (r) {return r.index;}))) {
                  errorReasons.push({ type: 'VIEW.ROLES.LOGIC.EXPRESSION.INVALID', code: 400 });
                }if (!(
                errorReasons.length > 0)) {_context4.next = 24;break;}return _context4.abrupt("return",
                res.boom.badRequest(null, { errors: errorReasons }));case 24:_context4.next = 26;return (



                  _models_View__WEBPACK_IMPORTED_MODULE_9__["default"].query().insert({
                    name: form.name,
                    predefined: false,
                    resource_id: resource.id,
                    roles_logic_expression: form.logic_expression }));case 26:view = _context4.sent;

                // Save view roles async operations.
                saveViewRolesOpers = [];

                form.roles.forEach(function (role) {
                  var fieldModel = resourceFieldsKeysMap.get(role.field_key);

                  var saveViewRoleOper = _models_ViewRole__WEBPACK_IMPORTED_MODULE_10__["default"].query().insert(_objectSpread({},
                  Object(lodash__WEBPACK_IMPORTED_MODULE_3__["pick"])(role, ['comparator', 'value', 'index']), {
                    field_id: fieldModel.id,
                    view_id: view.id }));

                  saveViewRolesOpers.push(saveViewRoleOper);
                });

                form.columns.forEach(function (column) {
                  var fieldModel = resourceFieldsKeysMap.get(column.key);

                  var saveViewColumnOper = _models_ViewColumn__WEBPACK_IMPORTED_MODULE_11__["default"].query().insert({
                    field_id: fieldModel.id,
                    view_id: view.id,
                    index: column.index });

                  saveViewRolesOpers.push(saveViewColumnOper);
                });_context4.next = 32;return (
                  Promise.all(saveViewRolesOpers));case 32:return _context4.abrupt("return",

                res.status(200).send({ id: view.id }));case 33:case "end":return _context4.stop();}}}, _callee4);}));function handler(_x7, _x8) {return _handler4.apply(this, arguments);}return handler;}() },



  editView: {
    validation: [
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["param"])('view_id').exists().isNumeric().toInt(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('label').exists().escape().trim(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('columns').isArray({ min: 3 }),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('roles').isArray(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('roles.*.field').exists().escape().trim(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('roles.*.comparator').exists(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('roles.*.value').exists(),
    Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["check"])('roles.*.index').exists().isNumeric().toInt()],

    handler: function () {var _handler5 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5(req, res) {var viewId, validationErrors, view;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {while (1) {switch (_context5.prev = _context5.next) {case 0:
                viewId = req.params.view_id;
                validationErrors = Object(express_validator__WEBPACK_IMPORTED_MODULE_5__["validationResult"])(req);if (

                validationErrors.isEmpty()) {_context5.next = 4;break;}return _context5.abrupt("return",
                res.boom.badData(null, _objectSpread({
                  code: 'validation_error' }, validationErrors)));case 4:_context5.next = 6;return (


                  _models_View__WEBPACK_IMPORTED_MODULE_9__["default"].where('id', viewId).fetch());case 6:view = _context5.sent;if (

                view) {_context5.next = 9;break;}return _context5.abrupt("return",
                res.boom.notFound(null, {
                  errors: [{ type: 'ROLE_NOT_FOUND', code: 100 }] }));case 9:return _context5.abrupt("return",


                res.status(200).send());case 10:case "end":return _context5.stop();}}}, _callee5);}));function handler(_x9, _x10) {return _handler5.apply(this, arguments);}return handler;}() } });

/***/ }),

/***/ "./src/http/index.js":
/*!***************************!*\
  !*** ./src/http/index.js ***!
  \***************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _http_controllers_Authentication__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @/http/controllers/Authentication */ "./src/http/controllers/Authentication.js");
/* harmony import */ var _http_controllers_Users__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @/http/controllers/Users */ "./src/http/controllers/Users.js");
/* harmony import */ var _http_controllers_Roles__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @/http/controllers/Roles */ "./src/http/controllers/Roles.js");
/* harmony import */ var _http_controllers_Items__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @/http/controllers/Items */ "./src/http/controllers/Items.js");
/* harmony import */ var _http_controllers_ItemCategories__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/http/controllers/ItemCategories */ "./src/http/controllers/ItemCategories.js");
/* harmony import */ var _http_controllers_Accounts__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/http/controllers/Accounts */ "./src/http/controllers/Accounts.js");
/* harmony import */ var _http_controllers_AccountTypes__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/http/controllers/AccountTypes */ "./src/http/controllers/AccountTypes.js");
/* harmony import */ var _http_controllers_AccountOpeningBalance__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/http/controllers/AccountOpeningBalance */ "./src/http/controllers/AccountOpeningBalance.js");
/* harmony import */ var _http_controllers_Views__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/http/controllers/Views */ "./src/http/controllers/Views.js");
/* harmony import */ var _http_controllers_Fields__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/http/controllers/Fields */ "./src/http/controllers/Fields.js");
/* harmony import */ var _http_controllers_Accounting__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/http/controllers/Accounting */ "./src/http/controllers/Accounting.js");
/* harmony import */ var _http_controllers_FinancialStatements__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @/http/controllers/FinancialStatements */ "./src/http/controllers/FinancialStatements.js");
/* harmony import */ var _http_controllers_Expenses__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! @/http/controllers/Expenses */ "./src/http/controllers/Expenses.js");
/* harmony import */ var _http_controllers_Options__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @/http/controllers/Options */ "./src/http/controllers/Options.js");
/* harmony import */ var _http_controllers_Budget__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! @/http/controllers/Budget */ "./src/http/controllers/Budget.js");
/* harmony import */ var _http_controllers_BudgetReports__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @/http/controllers/BudgetReports */ "./src/http/controllers/BudgetReports.js");
/* harmony import */ var _http_controllers_Currencies__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! @/http/controllers/Currencies */ "./src/http/controllers/Currencies.js");
/* harmony import */ var _http_controllers_Customers__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! @/http/controllers/Customers */ "./src/http/controllers/Customers.js");
/* harmony import */ var _http_controllers_Suppliers__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! @/http/controllers/Suppliers */ "./src/http/controllers/Suppliers.js");
/* harmony import */ var _http_controllers_Bills__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! @/http/controllers/Bills */ "./src/http/controllers/Bills.js");
/* harmony import */ var _controllers_CurrencyAdjustment__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./controllers/CurrencyAdjustment */ "./src/http/controllers/CurrencyAdjustment.js");
/* harmony import */ var _controllers_Resources__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./controllers/Resources */ "./src/http/controllers/Resources.js");
// import OAuth2 from '@/http/controllers/OAuth2';






















// import SalesReports from '@/http/controllers/SalesReports';
// import PurchasesReports from '@/http/controllers/PurchasesReports';

/* harmony default export */ __webpack_exports__["default"] = (function (app) {
  // app.use('/api/oauth2', OAuth2.router());
  app.use('/api/auth', _http_controllers_Authentication__WEBPACK_IMPORTED_MODULE_0__["default"].router());
  app.use('/api/currencies', _http_controllers_Currencies__WEBPACK_IMPORTED_MODULE_16__["default"].router());
  app.use('/api/users', _http_controllers_Users__WEBPACK_IMPORTED_MODULE_1__["default"].router());
  app.use('/api/roles', _http_controllers_Roles__WEBPACK_IMPORTED_MODULE_2__["default"].router());
  app.use('/api/accounts', _http_controllers_Accounts__WEBPACK_IMPORTED_MODULE_5__["default"].router());
  app.use('/api/account_types', _http_controllers_AccountTypes__WEBPACK_IMPORTED_MODULE_6__["default"].router());
  app.use('/api/accounting', _http_controllers_Accounting__WEBPACK_IMPORTED_MODULE_10__["default"].router());
  app.use('/api/accounts_opening_balances', _http_controllers_AccountOpeningBalance__WEBPACK_IMPORTED_MODULE_7__["default"].router());
  app.use('/api/views', _http_controllers_Views__WEBPACK_IMPORTED_MODULE_8__["default"].router());
  app.use('/api/fields', _http_controllers_Fields__WEBPACK_IMPORTED_MODULE_9__["default"].router());
  app.use('/api/items', _http_controllers_Items__WEBPACK_IMPORTED_MODULE_3__["default"].router());
  app.use('/api/item_categories', _http_controllers_ItemCategories__WEBPACK_IMPORTED_MODULE_4__["default"].router());
  app.use('/api/expenses', _http_controllers_Expenses__WEBPACK_IMPORTED_MODULE_12__["default"].router());
  app.use('/api/financial_statements', _http_controllers_FinancialStatements__WEBPACK_IMPORTED_MODULE_11__["default"].router());
  app.use('/api/options', _http_controllers_Options__WEBPACK_IMPORTED_MODULE_13__["default"].router());
  app.use('/api/budget_reports', _http_controllers_BudgetReports__WEBPACK_IMPORTED_MODULE_15__["default"].router());
  // app.use('/api/customers', Customers.router());
  // app.use('/api/suppliers', Suppliers.router());
  // app.use('/api/bills', Bills.router());
  app.use('/api/budget', _http_controllers_Budget__WEBPACK_IMPORTED_MODULE_14__["default"].router());
  app.use('/api/resources', _controllers_Resources__WEBPACK_IMPORTED_MODULE_21__["default"].router());
  // app.use('/api/currency_adjustment', CurrencyAdjustment.router());
  // app.use('/api/reports/sales', SalesReports.router());
  // app.use('/api/reports/purchases', PurchasesReports.router());
});

/***/ }),

/***/ "./src/http/middleware/asyncMiddleware.js":
/*!************************************************!*\
  !*** ./src/http/middleware/asyncMiddleware.js ***!
  \************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
var asyncMiddleware = function asyncMiddleware(fn) {return function (req, res, next) {
    Promise.resolve(fn(req, res, next))["catch"](
    function (error) {
      console.log(error);
      next(error);
    });
  };};

/* harmony default export */ __webpack_exports__["default"] = (asyncMiddleware);

/***/ }),

/***/ "./src/http/middleware/authorization.js":
/*!**********************************************!*\
  !*** ./src/http/middleware/authorization.js ***!
  \**********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* eslint-disable consistent-return */
var authorization = function authorization(resourceName) {return function () {for (var _len = arguments.length, permissions = new Array(_len), _key = 0; _key < _len; _key++) {permissions[_key] = arguments[_key];}return function (req, res, next) {var
      user = req.user;
      var onError = function onError() {
        res.boom.unauthorized();
      };
      user.hasPermissions(resourceName, permissions).
      then(function (authorized) {
        if (!authorized) {
          return onError();
        }
        next();
      })["catch"](onError);
    };};};

/* harmony default export */ __webpack_exports__["default"] = (authorization);

/***/ }),

/***/ "./src/http/middleware/jwtAuth.js":
/*!****************************************!*\
  !*** ./src/http/middleware/jwtAuth.js ***!
  \****************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var jsonwebtoken__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! jsonwebtoken */ "jsonwebtoken");
/* harmony import */ var jsonwebtoken__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(jsonwebtoken__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _models_User__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @/models/User */ "./src/models/User.js");
 /* eslint-disable consistent-return */


// import Auth from '@/models/Auth';

var authMiddleware = function authMiddleware(req, res, next) {var
  JWT_SECRET_KEY = process.env.JWT_SECRET_KEY;
  var token = req.headers['x-access-token'] || req.query.token;

  var onError = function onError() {
    // Auth.loggedOut();
    res.status(401).send({
      success: false,
      message: 'unauthorized' });

  };

  if (!token) {
    return onError();
  }

  var verify = new Promise(function (resolve, reject) {
    jsonwebtoken__WEBPACK_IMPORTED_MODULE_2___default.a.verify(token, JWT_SECRET_KEY, /*#__PURE__*/function () {var _ref = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(error, decoded) {return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:if (!
                error) {_context.next = 4;break;}
                reject(error);_context.next = 10;break;case 4:_context.next = 6;return (


                  _models_User__WEBPACK_IMPORTED_MODULE_3__["default"].query().findById(decoded._id));case 6:req.user = _context.sent;if (


                req.user) {_context.next = 9;break;}return _context.abrupt("return",
                onError());case 9:

                resolve(decoded);case 10:case "end":return _context.stop();}}}, _callee);}));return function (_x, _x2) {return _ref.apply(this, arguments);};}());


  });

  verify.then(function () {next();})["catch"](onError);
};
/* harmony default export */ __webpack_exports__["default"] = (authMiddleware);

/***/ }),

/***/ "./src/lib/LogicEvaluation/Lexer.js":
/*!******************************************!*\
  !*** ./src/lib/LogicEvaluation/Lexer.js ***!
  \******************************************/
/*! exports provided: Lexer, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Lexer", function() { return Lexer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return token; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);

var OperationType = {
  LOGIC: 'LOGIC',
  STRING: 'STRING',
  COMPARISON: 'COMPARISON',
  MATH: 'MATH' };


var Lexer = /*#__PURE__*/function () {_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Lexer, null, [{ key: "optable",
    // operation table
    get: function get() {
      return {
        '=': OperationType.LOGIC,
        '&': OperationType.LOGIC,
        '|': OperationType.LOGIC,
        '?': OperationType.LOGIC,
        ':': OperationType.LOGIC,

        '\'': OperationType.STRING,
        '"': OperationType.STRING,

        '!': OperationType.COMPARISON,
        '>': OperationType.COMPARISON,
        '<': OperationType.COMPARISON,

        '(': OperationType.MATH,
        ')': OperationType.MATH,
        '+': OperationType.MATH,
        '-': OperationType.MATH,
        '*': OperationType.MATH,
        '/': OperationType.MATH,
        '%': OperationType.MATH };

    }

    /**
       * Constructor
       * @param {*} expression -
       */ }]);
  function Lexer(expression) {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Lexer);
    this.currentIndex = 0;
    this.input = expression;
    this.tokenList = [];
  }_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Lexer, [{ key: "getTokens", value: function getTokens()

    {
      var tok;
      do {
        // read current token, so step should be -1
        tok = this.pickNext(-1);
        var pos = this.currentIndex;
        switch (Lexer.optable[tok]) {
          case OperationType.LOGIC:
            // == && || ===
            this.readLogicOpt(tok);
            break;

          case OperationType.STRING:
            this.readString(tok);
            break;

          case OperationType.COMPARISON:
            this.readCompare(tok);
            break;

          case OperationType.MATH:
            this.receiveToken();
            break;

          default:
            this.readValue(tok);}


        // if the pos not changed, this loop will go into a infinite loop, every step of while loop,
        // we must move the pos forward
        // so here we should throw error, for example `1 & 2`
        if (pos === this.currentIndex && tok !== undefined) {
          var err = new Error("unkonw token ".concat(tok, " from input string ").concat(this.input));
          err.name = 'UnknowToken';
          throw err;
        }
      } while (tok !== undefined);

      return this.tokenList;
    }

    /**
       * read next token, the index param can set next step, default go foward 1 step
       *
       * @param index next postion
       */ }, { key: "pickNext", value: function pickNext()
    {var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
      return this.input[index + this.currentIndex + 1];
    }

    /**
       * Store token into result tokenList, and move the pos index
       *
       * @param index
       */ }, { key: "receiveToken", value: function receiveToken()
    {var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
      var tok = this.input.slice(this.currentIndex, this.currentIndex + index).trim();
      // skip empty string
      if (tok) {
        this.tokenList.push(tok);
      }

      this.currentIndex += index;
    }

    // ' or "
  }, { key: "readString", value: function readString(tok) {
      var next;
      var index = 0;
      do {
        next = this.pickNext(index);
        index += 1;
      } while (next !== tok && next !== undefined);
      this.receiveToken(index + 1);
    }

    // > or < or >= or <= or !==
    // tok in (>, <, !)
  }, { key: "readCompare", value: function readCompare(tok) {
      if (this.pickNext() !== '=') {
        this.receiveToken(1);
        return;
      }
      // !==
      if (tok === '!' && this.pickNext(1) === '=') {
        this.receiveToken(3);
        return;
      }
      this.receiveToken(2);
    }

    // === or ==
    // && ||
  }, { key: "readLogicOpt", value: function readLogicOpt(tok) {
      if (this.pickNext() === tok) {
        // ===
        if (tok === '=' && this.pickNext(1) === tok) {
          return this.receiveToken(3);
        }
        // == && ||
        return this.receiveToken(2);
      }
      // handle as &&
      // a ? b : c is equal to a && b || c
      if (tok === '?' || tok === ':') {
        return this.receiveToken(1);
      }
    } }, { key: "readValue", value: function readValue(

    tok) {
      if (!tok) {
        return;
      }

      var index = 0;
      while (!Lexer.optable[tok] && tok !== undefined) {
        tok = this.pickNext(index);
        index += 1;
      }
      this.receiveToken(index);
    } }]);return Lexer;}();


function token(expression) {
  var lexer = new Lexer(expression);
  return lexer.getTokens();
}

/***/ }),

/***/ "./src/lib/LogicEvaluation/Parser.js":
/*!*******************************************!*\
  !*** ./src/lib/LogicEvaluation/Parser.js ***!
  \*******************************************/
/*! exports provided: OPERATION, default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OPERATION", function() { return OPERATION; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Parser; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
var OPERATION = {
  '!': 5,
  '*': 4,
  '/': 4,
  '%': 4,
  '+': 3,
  '-': 3,
  '>': 2,
  '<': 2,
  '>=': 2,
  '<=': 2,
  '===': 2,
  '!==': 2,
  '==': 2,
  '!=': 2,
  '&&': 1,
  '||': 1,
  '?': 1,
  ':': 1 };


// export interface Node {
//   left: Node | string | null;
//   right: Node | string | null;
//   operation: string;
//   grouped?: boolean;
// };
var
Parser = /*#__PURE__*/function () {

  function Parser(token) {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Parser);
    this.index = -1;
    this.blockLevel = 0;
    this.token = token;
  }

  /**
     * 
     * @return {Node | string} =- 
     */_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Parser, [{ key: "parse", value: function parse()
    {
      var tok;
      var root = {
        left: null,
        right: null,
        operation: null };


      do {
        tok = this.parseStatement();

        if (tok === null || tok === undefined) {
          break;
        }

        if (root.left === null) {
          root.left = tok;
          root.operation = this.nextToken();

          if (!root.operation) {
            return tok;
          }

          root.right = this.parseStatement();
        } else {
          if (typeof tok !== 'string') {
            throw new Error('operation must be string, but get ' + JSON.stringify(tok));
          }
          root = this.addNode(tok, this.parseStatement(), root);
        }
      } while (tok);

      return root;
    } }, { key: "nextToken", value: function nextToken()

    {
      this.index += 1;
      return this.token[this.index];
    } }, { key: "prevToken", value: function prevToken()

    {
      return this.token[this.index - 1];
    }

    /**
       * 
       * @param {string} operation 
       * @param {Node|String|null} right 
       * @param {Node} root 
       */ }, { key: "addNode", value: function addNode(
    operation, right, root) {
      var pre = root;

      if (this.compare(pre.operation, operation) < 0 && !pre.grouped) {

        while (pre.right !== null &&
        typeof pre.right !== 'string' &&
        this.compare(pre.right.operation, operation) < 0 && !pre.right.grouped) {
          pre = pre.right;
        }

        pre.right = {
          operation: operation,
          left: pre.right,
          right: right };

        return root;
      }
      return {
        left: pre,
        right: right,
        operation: operation };

    }

    /**
       * 
       * @param {String} a 
       * @param {String} b 
       */ }, { key: "compare", value: function compare(
    a, b) {
      if (!OPERATION.hasOwnProperty(a) || !OPERATION.hasOwnProperty(b)) {
        throw new Error("unknow operation ".concat(a, " or ").concat(b));
      }
      return OPERATION[a] - OPERATION[b];
    }

    /**
       * @return string | Node | null
       */ }, { key: "parseStatement", value: function parseStatement()
    {
      var token = this.nextToken();
      if (token === '(') {
        this.blockLevel += 1;
        var node = this.parse();
        this.blockLevel -= 1;

        if (typeof node !== 'string') {
          node.grouped = true;
        }
        return node;
      }

      if (token === ')') {
        return null;
      }

      if (token === '!') {
        return { left: null, operation: token, right: this.parseStatement() };
      }

      // 3 > -12 or -12 + 10
      if (token === '-' && (OPERATION[this.prevToken()] > 0 || this.prevToken() === undefined)) {
        return { left: '0', operation: token, right: this.parseStatement(), grouped: true };
      }

      return token;
    } }]);return Parser;}();

/***/ }),

/***/ "./src/lib/LogicEvaluation/QueryParser.js":
/*!************************************************!*\
  !*** ./src/lib/LogicEvaluation/QueryParser.js ***!
  \************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return QueryParser; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _Parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Parser */ "./src/lib/LogicEvaluation/Parser.js");
var

QueryParser = /*#__PURE__*/function () {

  function QueryParser(tree, queries) {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, QueryParser);
    this.tree = tree;
    this.queries = queries;
    this.query = null;
  }_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(QueryParser, [{ key: "setQuery", value: function setQuery(

    query) {
      this.query = query.clone();
    } }, { key: "parse", value: function parse()

    {
      return this.parseNode(this.tree);
    } }, { key: "parseNode", value: function parseNode(

    node) {
      if (typeof node === 'string') {
        var nodeQuery = this.getQuery(node);
        return function (query) {nodeQuery(query);};
      }
      if (_Parser__WEBPACK_IMPORTED_MODULE_2__["OPERATION"][node.operation] === undefined) {
        throw new Error("unknow expression ".concat(node.operation));
      }
      var leftQuery = this.getQuery(node.left);
      var rightQuery = this.getQuery(node.right);

      switch (node.operation) {
        case '&&':
        case 'AND':
        default:
          return function (nodeQuery) {return nodeQuery.where(function (query) {
              query.where(function (q) {leftQuery(q);});
              query.andWhere(function (q) {rightQuery(q);});
            });};
        case '||':
        case 'OR':
          return function (nodeQuery) {return nodeQuery.where(function (query) {
              query.where(function (q) {leftQuery(q);});
              query.orWhere(function (q) {rightQuery(q);});
            });};}

    } }, { key: "getQuery", value: function getQuery(

    node) {
      if (typeof node !== 'string' && node !== null) {
        return this.parseNode(node);
      }
      var value = parseFloat(node);

      if (!isNaN(value)) {
        if (typeof this.queries[node] === 'undefined') {
          throw new Error("unknow query under index ".concat(node));
        }
        return this.queries[node];
      }
      return null;
    } }]);return QueryParser;}();

/***/ }),

/***/ "./src/lib/Metable/MetableCollection.js":
/*!**********************************************!*\
  !*** ./src/lib/Metable/MetableCollection.js ***!
  \**********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return MetableCollection; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__);
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}var
MetableCollection = /*#__PURE__*/function () {
  function MetableCollection() {var _this = this;_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3___default()(this, MetableCollection);
    this.metadata = [];
    this.KEY_COLUMN = 'key';
    this.VALUE_COLUMN = 'value';
    this.TYPE_COLUMN = 'type';
    this.model = null;
    this.extraColumns = [];

    this.extraQuery = function (query, meta) {
      query.where('key', meta[_this.KEY_COLUMN]);
    };
  }

  /**
     * Set model of this metadata collection.
     * @param {Object} model -
     */_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4___default()(MetableCollection, [{ key: "setModel", value: function setModel(
    model) {
      this.model = model;
    }

    /**
       * Find the given metadata key.
       * @param {String} key -
       * @return {object} - Metadata object.
       */ }, { key: "findMeta", value: function findMeta(
    key) {
      return this.allMetadata().find(function (meta) {return meta.key === key;});
    }

    /**
       * Retrieve all metadata.
       */ }, { key: "allMetadata", value: function allMetadata()
    {
      return this.metadata.filter(function (meta) {return !meta.markAsDeleted;});
    }

    /**
       * Retrieve metadata of the given key.
       * @param {String} key -
       * @param {Mixied} defaultValue -
       */ }, { key: "getMeta", value: function getMeta(
    key, defaultValue) {
      var metadata = this.findMeta(key);
      return metadata ? metadata.value : defaultValue || false;
    }

    /**
       * Markes the metadata to should be deleted.
       * @param {String} key -
       */ }, { key: "removeMeta", value: function removeMeta(
    key) {
      var metadata = this.findMeta(key);

      if (metadata) {
        metadata.markAsDeleted = true;
      }
    }

    /**
       * Remove all meta data of the given group.
       * @param {*} group
       */ }, { key: "removeAllMeta", value: function removeAllMeta()
    {var group = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'default';
      this.metadata = this.metadata.map(function (meta) {return _objectSpread({},
        meta, {
          markAsDeleted: true });});

    } }, { key: "setExtraQuery", value: function setExtraQuery(

    callback) {
      this.extraQuery = callback;
    }

    /**
       * Set the meta data to the stack.
       * @param {String} key -
       * @param {String} value -
       */ }, { key: "setMeta", value: function setMeta(
    key, value, payload) {var _this2 = this;
      if (Array.isArray(key)) {
        var _metadata = key;

        _metadata.forEach(function (meta) {
          _this2.setMeta(meta.key, meta.value);
        });
        return;
      }
      var metadata = this.findMeta(key);

      if (metadata) {
        metadata.value = value;
        metadata.markAsUpdated = true;
      } else {
        this.metadata.push(_objectSpread({
          value: value, key: key }, payload, { markAsInserted: true }));

      }
    }

    /**
       * Saved the modified/deleted and inserted metadata.
       */ }, { key: "saveMeta", value: function () {var _saveMeta = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() {var _this3 = this;var inserted, updated, deleted, opers;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:

                inserted = this.metadata.filter(function (m) {return m.markAsInserted === true;});
                updated = this.metadata.filter(function (m) {return m.markAsUpdated === true;});
                deleted = this.metadata.filter(function (m) {return m.markAsDeleted === true;});
                opers = [];

                if (deleted.length > 0) {
                  deleted.forEach(function (meta) {
                    var deleteOper = _this3.model.query().beforeRun(function (query, result) {
                      _this3.extraQuery(query, meta);
                      return result;
                    })["delete"]();
                    opers.push(deleteOper);
                  });
                }
                inserted.forEach(function (meta) {var _objectSpread2;
                  var insertOper = _this3.model.query().insert(_objectSpread((_objectSpread2 = {}, _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(_objectSpread2,
                  _this3.KEY_COLUMN, meta.key), _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(_objectSpread2,
                  _this3.VALUE_COLUMN, meta.value), _objectSpread2),
                  _this3.extraColumns.reduce(function (obj, column) {
                    if (typeof meta[column] !== 'undefined') {
                      obj[column] = meta[column];
                    }
                    return obj;
                  }, {})));

                  opers.push(insertOper);
                });
                updated.forEach(function (meta) {
                  var updateOper = _this3.model.query().onBuild(function (query) {
                    _this3.extraQuery(query, meta);
                  }).patch(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()({},
                  _this3.VALUE_COLUMN, meta.value));

                  opers.push(updateOper);
                });_context.next = 9;return (
                  Promise.all(opers));case 9:case "end":return _context.stop();}}}, _callee, this);}));function saveMeta() {return _saveMeta.apply(this, arguments);}return saveMeta;}()


    /**
                                                                                                                                                                                          * Loads the metadata from the storage.
                                                                                                                                                                                          * @param {String|Array} key -
                                                                                                                                                                                          * @param {Boolean} force -
                                                                                                                                                                                          */ }, { key: "load", value: function () {var _load = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {var _this4 = this;var metadata, metadataArray;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:_context2.next = 2;return (

                  this.query());case 2:metadata = _context2.sent;

                metadataArray = this.mapMetadataCollection(metadata);
                metadataArray.forEach(function (meta) {
                  _this4.metadata.push(meta);
                });case 5:case "end":return _context2.stop();}}}, _callee2, this);}));function load() {return _load.apply(this, arguments);}return load;}()


    /**
                                                                                                                                                             * Format the metadata before saving to the database.
                                                                                                                                                             * @param {String|Number|Boolean} value -
                                                                                                                                                             * @param {String} valueType -
                                                                                                                                                             * @return {String|Number|Boolean} -
                                                                                                                                                             */ }, { key: "mapMetadata",




















    /**
                                                                                                                                                                                          * Mapping and parse metadata to collection entries.
                                                                                                                                                                                          * @param {Meta} attr -
                                                                                                                                                                                          * @param {String} parseType -
                                                                                                                                                                                          */value: function mapMetadata(
    attr) {var parseType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'parse';
      return _objectSpread({
        key: attr[this.KEY_COLUMN],
        value: parseType === 'parse' ?
        MetableCollection.parseMetaValue(
        attr[this.VALUE_COLUMN],
        this.TYPE_COLUMN ? attr[this.TYPE_COLUMN] : false) :

        MetableCollection.formatMetaValue(
        attr[this.VALUE_COLUMN],
        this.TYPE_COLUMN ? attr[this.TYPE_COLUMN] : false) },

      this.extraColumns.map(function (extraCol) {return _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()({},
        extraCol, attr[extraCol] || null);}));


    }

    /**
       * Parse the metadata to the collection.
       * @param {Array} collection -
       */ }, { key: "mapMetadataToCollection", value: function mapMetadataToCollection(
    metadata) {var _this5 = this;var parseType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'parse';
      return metadata.map(function (model) {return _this5.mapMetadataToCollection(model, parseType);});
    }

    /**
       * Load metadata to the metable collection.
       * @param {Array} meta -
       */ }, { key: "from", value: function from(
    meta) {var _this6 = this;
      if (Array.isArray(meta)) {
        meta.forEach(function (m) {_this6.from(m);});
        return;
      }
      this.metadata.push(meta);
    } }, { key: "toArray", value: function toArray()


    {
      return this.metadata;
    }

    /**
       * Static method to load metadata to the collection.
       * @param {Array} meta 
       */ }], [{ key: "formatMetaValue", value: function formatMetaValue(value, valueType) {var parsedValue;switch (valueType) {case 'number':parsedValue = "".concat(value);break;case 'boolean':parsedValue = value ? '1' : '0';break;case 'json':parsedValue = JSON.stringify(parsedValue);break;default:parsedValue = value;break;}return parsedValue;} }, { key: "from", value: function from(
    meta) {
      var collection = new MetableCollection();
      collection.from(meta);

      return collection;
    } }]);return MetableCollection;}();

/***/ }),

/***/ "./src/lib/ViewRolesBuilder/index.js":
/*!*******************************************!*\
  !*** ./src/lib/ViewRolesBuilder/index.js ***!
  \*******************************************/
/*! exports provided: buildRoleQuery, viewRolesBuilder, validateViewLogicExpression, validateViewRoles, mapViewRolesToConditionals */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "buildRoleQuery", function() { return buildRoleQuery; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "viewRolesBuilder", function() { return viewRolesBuilder; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "validateViewLogicExpression", function() { return validateViewLogicExpression; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "validateViewRoles", function() { return validateViewRoles; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapViewRolesToConditionals", function() { return mapViewRolesToConditionals; });
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! lodash */ "lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _lib_LogicEvaluation_Lexer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @/lib/LogicEvaluation/Lexer */ "./src/lib/LogicEvaluation/Lexer.js");
/* harmony import */ var _lib_LogicEvaluation_Parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @/lib/LogicEvaluation/Parser */ "./src/lib/LogicEvaluation/Parser.js");
/* harmony import */ var _lib_LogicEvaluation_QueryParser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @/lib/LogicEvaluation/QueryParser */ "./src/lib/LogicEvaluation/QueryParser.js");
/* harmony import */ var _data_ResourceFieldsKeys__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/data/ResourceFieldsKeys */ "./src/data/ResourceFieldsKeys.js");






//  const role = {
//   compatotor: '',
//   value: '',
//   columnKey: '',
//   columnSlug: '',
//   index: 1,
// }

function buildRoleQuery(role) {
  var columnName = _data_ResourceFieldsKeys__WEBPACK_IMPORTED_MODULE_4__["default"][role.columnKey];

  switch (role.comparator) {
    case 'equals':
    default:
      return function (builder) {
        builder.where(columnName, role.value);
      };
    case 'not_equal':
    case 'not_equals':
      return function (builder) {
        builder.whereNot(columnName, role.value);
      };}

}

/**
   * Builds database query from stored view roles.
   *
   * @param {Array} roles -
   * @return {Function}
   */
function viewRolesBuilder(roles) {var logicExpression = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
  var rolesIndexSet = {};

  roles.forEach(function (role) {
    rolesIndexSet[role.index] = buildRoleQuery(role);
  });
  // Lexer for logic expression.
  var lexer = new _lib_LogicEvaluation_Lexer__WEBPACK_IMPORTED_MODULE_1__["Lexer"](logicExpression);
  var tokens = lexer.getTokens();

  // Parse the logic expression.
  var parser = new _lib_LogicEvaluation_Parser__WEBPACK_IMPORTED_MODULE_2__["default"](tokens);
  var parsedTree = parser.parse();

  var queryParser = new _lib_LogicEvaluation_QueryParser__WEBPACK_IMPORTED_MODULE_3__["default"](parsedTree, rolesIndexSet);
  return queryParser.parse();
}

/**
   * Validates the view logic expression.
   * @param {String} logicExpression 
   * @param {Array} indexes 
   */
function validateViewLogicExpression(logicExpression, indexes) {
  var logicExpIndexes = logicExpression.match(/\d+/g) || [];
  return !Object(lodash__WEBPACK_IMPORTED_MODULE_0__["difference"])(logicExpIndexes.map(Number), indexes).length;
}

/**
   * 
   * @param {Array} roles -
   * @param {String} logicExpression -
   * @return {Boolean}
   */
function validateViewRoles(roles, logicExpression) {
  return validateViewLogicExpression(logicExpression, roles.map(function (r) {return r.index;}));
}

/**
   * Mapes the view roles to view conditionals.
   * @param {Array} viewRoles -
   * @return {Array}
   */
function mapViewRolesToConditionals(viewRoles) {
  return viewRoles.map(function (viewRole) {return {
      comparator: viewRole.comparator,
      value: viewRole.value,
      columnKey: viewRole.field.columnKey,
      slug: viewRole.field.slug,
      index: viewRole.index };});

}

/***/ }),

/***/ "./src/models/Account.js":
/*!*******************************!*\
  !*** ./src/models/Account.js ***!
  \*******************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Account; });
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! objection */ "objection");
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(objection__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! lodash */ "lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");
/* harmony import */ var _lib_ViewRolesBuilder__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/lib/ViewRolesBuilder */ "./src/lib/ViewRolesBuilder/index.js");
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;} /* eslint-disable global-require */



var

Account = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_5___default()(Account, _BaseModel);function Account() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default()(this, Account);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_3___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_4___default()(Account).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(Account, null, [{ key: "collectJournalEntries", value: function collectJournalEntries(






































































    accounts) {
      return Object(lodash__WEBPACK_IMPORTED_MODULE_7__["flatten"])(accounts.map(function (account) {return account.transactions.map(function (transaction) {return _objectSpread({
            accountId: account.id },
          transaction, {
            accountNormal: account.type.normal });});}));

    } }, { key: "tableName", /**
                              * Table name
                              */get: function get() {return 'accounts';} /**
                                                                          * Model modifiers.
                                                                          */ }, { key: "modifiers", get: function get() {return { filterAccountTypes: function filterAccountTypes(query, typesIds) {if (typesIds.length > 0) {query.whereIn('accoun_type_id', typesIds);}}, viewRolesBuilder: function viewRolesBuilder(query, conditionals, expression) {Object(_lib_ViewRolesBuilder__WEBPACK_IMPORTED_MODULE_9__["viewRolesBuilder"])(conditionals, expression)(query);} };} /**
                                                                                                                                                                                                                                                                                                                                                                                                                    * Relationship mapping.
                                                                                                                                                                                                                                                                                                                                                                                                                    */ }, { key: "relationMappings", get: function get() {var AccountType = __webpack_require__(/*! @/models/AccountType */ "./src/models/AccountType.js");var AccountBalance = __webpack_require__(/*! @/models/AccountBalance */ "./src/models/AccountBalance.js");var AccountTransaction = __webpack_require__(/*! @/models/AccountTransaction */ "./src/models/AccountTransaction.js");return { /**
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              * Account model may belongs to account type.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              */type: { relation: objection__WEBPACK_IMPORTED_MODULE_6__["Model"].BelongsToOneRelation, modelClass: AccountType["default"], join: { from: 'accounts.accountTypeId', to: 'account_types.id' } }, /**
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       * Account model may has many balances accounts.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       */balance: { relation: objection__WEBPACK_IMPORTED_MODULE_6__["Model"].HasOneRelation, modelClass: AccountBalance["default"], join: { from: 'accounts.id', to: 'account_balances.accountId' } }, /**
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               * Account model may has many transactions.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               */transactions: { relation: objection__WEBPACK_IMPORTED_MODULE_6__["Model"].HasManyRelation, modelClass: AccountTransaction["default"], join: { from: 'accounts.id', to: 'accounts_transactions.accountId' } } };} }]);return Account;}(_models_Model__WEBPACK_IMPORTED_MODULE_8__["default"]);

/***/ }),

/***/ "./src/models/AccountBalance.js":
/*!**************************************!*\
  !*** ./src/models/AccountBalance.js ***!
  \**************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AccountBalance; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! objection */ "objection");
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(objection__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");

var

AccountBalance = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(AccountBalance, _BaseModel);function AccountBalance() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, AccountBalance);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(AccountBalance).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(AccountBalance, null, [{ key: "tableName",
    /**
                                                                                                                                                                                                                                                                                                                      * Table name
                                                                                                                                                                                                                                                                                                                      */get: function get()
    {
      return 'account_balances';
    }

    /**
       * Relationship mapping.
       */ }, { key: "relationMappings", get: function get()
    {
      var Account = __webpack_require__(/*! @/models/Account */ "./src/models/Account.js");

      return {
        account: {
          relation: objection__WEBPACK_IMPORTED_MODULE_5__["Model"].BelongsToOneRelation,
          modelClass: Account["default"],
          join: {
            from: 'account_balance.account_id',
            to: 'accounts.id' } } };



    } }]);return AccountBalance;}(_models_Model__WEBPACK_IMPORTED_MODULE_6__["default"]);

/***/ }),

/***/ "./src/models/AccountTransaction.js":
/*!******************************************!*\
  !*** ./src/models/AccountTransaction.js ***!
  \******************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AccountTransaction; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! objection */ "objection");
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(objection__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! moment */ "moment");
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(moment__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");


var

AccountTransaction = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(AccountTransaction, _BaseModel);function AccountTransaction() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, AccountTransaction);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(AccountTransaction).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(AccountTransaction, null, [{ key: "tableName",
    /**
                                                                                                                                                                                                                                                                                                                                              * Table name
                                                                                                                                                                                                                                                                                                                                              */get: function get()
    {
      return 'accounts_transactions';
    }

    /**
       * Model modifiers.
       */ }, { key: "modifiers", get: function get()
    {
      return {
        filterAccounts: function filterAccounts(query, accountsIds) {
          if (accountsIds.length > 0) {
            query.whereIn('account_id', accountsIds);
          }
        },
        filterTransactionTypes: function filterTransactionTypes(query, types) {
          if (Array.isArray(types) && types.length > 0) {
            query.whereIn('reference_type', types);
          } else if (typeof types === 'string') {
            query.where('reference_type', types);
          }
        },
        filterDateRange: function filterDateRange(query, startDate, endDate) {var type = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'day';
          var dateFormat = 'YYYY-MM-DD HH:mm:ss';
          var fromDate = moment__WEBPACK_IMPORTED_MODULE_6___default()(startDate).startOf(type).format(dateFormat);
          var toDate = moment__WEBPACK_IMPORTED_MODULE_6___default()(endDate).endOf(type).format(dateFormat);

          if (startDate) {
            query.where('date', '>=', fromDate);
          }
          if (endDate) {
            query.where('date', '<=', toDate);
          }
        },
        filterAmountRange: function filterAmountRange(query, fromAmount, toAmount) {
          if (fromAmount) {
            query.andWhere(function (q) {
              q.where('credit', '>=', fromAmount);
              q.orWhere('debit', '>=', fromAmount);
            });
          }
          if (toAmount) {
            query.andWhere(function (q) {
              q.where('credit', '<=', toAmount);
              q.orWhere('debit', '<=', toAmount);
            });
          }
        },
        sumationCreditDebit: function sumationCreditDebit(query) {
          query.sum('credit as credit');
          query.sum('debit as debit');
          query.groupBy('account_id');
        } };

    }

    /**
       * Relationship mapping.
       */ }, { key: "relationMappings", get: function get()
    {
      var Account = __webpack_require__(/*! @/models/Account */ "./src/models/Account.js");

      return {
        account: {
          relation: objection__WEBPACK_IMPORTED_MODULE_5__["Model"].BelongsToOneRelation,
          modelClass: Account["default"],
          join: {
            from: 'accounts_transactions.accountId',
            to: 'accounts.id' } } };



    } }]);return AccountTransaction;}(_models_Model__WEBPACK_IMPORTED_MODULE_7__["default"]);

/***/ }),

/***/ "./src/models/AccountType.js":
/*!***********************************!*\
  !*** ./src/models/AccountType.js ***!
  \***********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return AccountType; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! objection */ "objection");
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(objection__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");
 // import path from 'path';

var

AccountType = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(AccountType, _BaseModel);function AccountType() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, AccountType);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(AccountType).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(AccountType, null, [{ key: "tableName",
    /**
                                                                                                                                                                                                                                                                                                    * Table name
                                                                                                                                                                                                                                                                                                    */get: function get()
    {
      return 'account_types';
    }

    /**
       * Relationship mapping.
       */ }, { key: "relationMappings", get: function get()
    {
      var Account = __webpack_require__(/*! @/models/Account */ "./src/models/Account.js");

      return {
        /**
                * Account type may has many associated accounts.
                */
        accounts: {
          relation: objection__WEBPACK_IMPORTED_MODULE_5__["Model"].HasManyRelation,
          modelClass: Account["default"],
          join: {
            from: 'account_types.id',
            to: 'accounts.accountTypeId' } } };



    } }]);return AccountType;}(_models_Model__WEBPACK_IMPORTED_MODULE_6__["default"]);

/***/ }),

/***/ "./src/models/Budget.js":
/*!******************************!*\
  !*** ./src/models/Budget.js ***!
  \******************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Budget; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");
var

Budget = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(Budget, _BaseModel);function Budget() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Budget);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(Budget).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Budget, [{ key: "rangeBy", get: function get()




























    {
      switch (this.period) {
        case 'half-year':
        case 'quarter':
          return 'month';
        default:
          return this.period;}

    } }, { key: "rangeIncrement", get: function get()

    {
      switch (this.period) {
        case 'half-year':
          return 6;
        case 'quarter':
          return 3;
        default:
          return 1;}

    } }, { key: "rangeOffset", get: function get()

    {
      switch (this.period) {
        case 'half-year':return 5;
        case 'quarter':return 2;
        default:return 0;}

    } }], [{ key: "tableName", /**
                                * Table name
                                */get: function get() {return 'budgets';} }, { key: "virtualAttributes", get: function get() {return ['rangeBy', 'rangeIncrement'];} /**
                                                                                                                                                                      * Model modifiers.
                                                                                                                                                                      */ }, { key: "modifiers", get: function get() {return { filterByYear: function filterByYear(query, year) {query.where('year', year);}, filterByIncomeStatement: function filterByIncomeStatement(query) {query.where('account_types', 'income_statement');}, filterByProfitLoss: function filterByProfitLoss(query) {query.where('accounts_types', 'profit_loss');} };} }]);return Budget;}(_models_Model__WEBPACK_IMPORTED_MODULE_5__["default"]);

/***/ }),

/***/ "./src/models/BudgetEntry.js":
/*!***********************************!*\
  !*** ./src/models/BudgetEntry.js ***!
  \***********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Budget; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");
var

Budget = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(Budget, _BaseModel);function Budget() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Budget);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(Budget).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Budget, null, [{ key: "tableName",
    /**
                                                                                                                                                                                                                                                                      * Table name
                                                                                                                                                                                                                                                                      */get: function get()
    {
      return 'budget_entries';
    } }]);return Budget;}(_models_Model__WEBPACK_IMPORTED_MODULE_5__["default"]);

/***/ }),

/***/ "./src/models/Expense.js":
/*!*******************************!*\
  !*** ./src/models/Expense.js ***!
  \*******************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Expense; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! objection */ "objection");
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(objection__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");
/* harmony import */ var _lib_ViewRolesBuilder__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/lib/ViewRolesBuilder */ "./src/lib/ViewRolesBuilder/index.js");


var
Expense = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(Expense, _BaseModel);function Expense() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Expense);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(Expense).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Expense, null, [{ key: "tableName",
    /**
                                                                                                                                                                                                                                                                            * Table name
                                                                                                                                                                                                                                                                            */get: function get()
    {
      return 'expenses';
    } }, { key: "referenceType", get: function get()

    {
      return 'Expense';
    }

    /**
       * Model modifiers.
       */ }, { key: "modifiers", get: function get()
    {
      return {
        filterByDateRange: function filterByDateRange(query, startDate, endDate) {
          if (startDate) {
            query.where('date', '>=', startDate);
          }
          if (endDate) {
            query.where('date', '<=', endDate);
          }
        },
        filterByAmountRange: function filterByAmountRange(query, from, to) {
          if (from) {
            query.where('amount', '>=', from);
          }
          if (to) {
            query.where('amount', '<=', to);
          }
        },
        filterByExpenseAccount: function filterByExpenseAccount(query, accountId) {
          if (accountId) {
            query.where('expense_account_id', accountId);
          }
        },
        filterByPaymentAccount: function filterByPaymentAccount(query, accountId) {
          if (accountId) {
            query.where('payment_account_id', accountId);
          }
        },

        viewRolesBuilder: function viewRolesBuilder(query, conditionals, expression) {
          Object(_lib_ViewRolesBuilder__WEBPACK_IMPORTED_MODULE_7__["viewRolesBuilder"])(conditionals, expression)(query);
        },

        orderBy: function orderBy(query) {

        } };

    }

    /**
       * Relationship mapping.
       */ }, { key: "relationMappings", get: function get()
    {
      var Account = __webpack_require__(/*! @/models/Account */ "./src/models/Account.js");
      var User = __webpack_require__(/*! @/models/User */ "./src/models/User.js");

      return {
        paymentAccount: {
          relation: objection__WEBPACK_IMPORTED_MODULE_5__["Model"].BelongsToOneRelation,
          modelClass: Account["default"],
          join: {
            from: 'expenses.paymentAccountId',
            to: 'accounts.id' } },



        expenseAccount: {
          relation: objection__WEBPACK_IMPORTED_MODULE_5__["Model"].BelongsToOneRelation,
          modelClass: Account["default"],
          join: {
            from: 'expenses.expenseAccountId',
            to: 'accounts.id' } },



        user: {
          relation: objection__WEBPACK_IMPORTED_MODULE_5__["Model"].BelongsToOneRelation,
          modelClass: User["default"],
          join: {
            from: 'expenses.userId',
            to: 'users.id' } } };



    } }]);return Expense;}(_models_Model__WEBPACK_IMPORTED_MODULE_6__["default"]);

/***/ }),

/***/ "./src/models/Item.js":
/*!****************************!*\
  !*** ./src/models/Item.js ***!
  \****************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(__dirname) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Item; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! objection */ "objection");
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(objection__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! path */ "path");
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");


var

Item = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(Item, _BaseModel);function Item() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Item);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(Item).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Item, null, [{ key: "tableName",
    /**
                                                                                                                                                                                                                                                          * Table name
                                                                                                                                                                                                                                                          */get: function get()
    {
      return 'items';
    }

    /**
       * Relationship mapping.
       */ }, { key: "relationMappings", get: function get()
    {
      return {
        /**
                * Item may has many meta data.
                */
        metadata: {
          relation: objection__WEBPACK_IMPORTED_MODULE_5__["Model"].HasManyRelation,
          modelBase: path__WEBPACK_IMPORTED_MODULE_6___default.a.join(__dirname, 'ItemMetadata'),
          join: {
            from: 'items.id',
            to: 'items_metadata.item_id' } },



        /**
                                               * Item may belongs to cateogory model.
                                               */
        category: {
          relation: objection__WEBPACK_IMPORTED_MODULE_5__["Model"].BelongsToOneRelation,
          modelBase: path__WEBPACK_IMPORTED_MODULE_6___default.a.join(__dirname, 'ItemCategory'),
          join: {
            from: 'items.categoryId',
            to: 'items_categories.id' } } };



    } }]);return Item;}(_models_Model__WEBPACK_IMPORTED_MODULE_7__["default"]);
/* WEBPACK VAR INJECTION */}.call(this, "/"))

/***/ }),

/***/ "./src/models/ItemCategory.js":
/*!************************************!*\
  !*** ./src/models/ItemCategory.js ***!
  \************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(__dirname) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ItemCategory; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! path */ "path");
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! objection */ "objection");
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(objection__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");


var

ItemCategory = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(ItemCategory, _BaseModel);function ItemCategory() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, ItemCategory);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(ItemCategory).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(ItemCategory, null, [{ key: "tableName",
    /**
                                                                                                                                                                                                                                                                                                          * Table name.
                                                                                                                                                                                                                                                                                                          */get: function get()
    {
      return 'items_categories';
    }

    /**
       * Relationship mapping.
       */ }, { key: "relationMappings", get: function get()
    {
      return {
        /**
                * Item category may has many items.
                */
        items: {
          relation: objection__WEBPACK_IMPORTED_MODULE_6__["Model"].HasManyRelation,
          modelBase: path__WEBPACK_IMPORTED_MODULE_5___default.a.join(__dirname, 'Item'),
          join: {
            from: 'items_categories.item_id',
            to: 'items.id' } } };



    } }]);return ItemCategory;}(_models_Model__WEBPACK_IMPORTED_MODULE_7__["default"]);
/* WEBPACK VAR INJECTION */}.call(this, "/"))

/***/ }),

/***/ "./src/models/JournalEntry.js":
/*!************************************!*\
  !*** ./src/models/JournalEntry.js ***!
  \************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return JournalEntry; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");
var

JournalEntry = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(JournalEntry, _BaseModel);function JournalEntry() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, JournalEntry);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(JournalEntry).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(JournalEntry, null, [{ key: "tableName",
    /**
                                                                                                                                                                                                                                                                                                          * Table name.
                                                                                                                                                                                                                                                                                                          */get: function get()
    {
      return 'manual_journals';
    } }]);return JournalEntry;}(_models_Model__WEBPACK_IMPORTED_MODULE_5__["default"]);

/***/ }),

/***/ "./src/models/ManualJournal.js":
/*!*************************************!*\
  !*** ./src/models/ManualJournal.js ***!
  \*************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ManualJournal; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");
var

ManualJournal = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(ManualJournal, _BaseModel);function ManualJournal() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, ManualJournal);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(ManualJournal).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(ManualJournal, null, [{ key: "tableName",
    /**
                                                                                                                                                                                                                                                                                                                * Table name.
                                                                                                                                                                                                                                                                                                                */get: function get()
    {
      return 'manual_journals';
    } }]);return ManualJournal;}(_models_Model__WEBPACK_IMPORTED_MODULE_5__["default"]);

/***/ }),

/***/ "./src/models/Model.js":
/*!*****************************!*\
  !*** ./src/models/Model.js ***!
  \*****************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ModelBase; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_get__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/get */ "@babel/runtime/helpers/get");
/* harmony import */ var _babel_runtime_helpers_get__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_get__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! objection */ "objection");
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(objection__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! lodash */ "lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/utils */ "./src/utils/index.js");


var

ModelBase = /*#__PURE__*/function (_Model) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_5___default()(ModelBase, _Model);function ModelBase() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, ModelBase);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(ModelBase).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(ModelBase, [{ key: "$formatJson", value: function $formatJson(













    json, opt) {
      var transformed = Object(_utils__WEBPACK_IMPORTED_MODULE_8__["mapKeysDeep"])(json, function (value, key) {
        return Object(lodash__WEBPACK_IMPORTED_MODULE_7__["snakeCase"])(key);
      });
      var parsedJson = _babel_runtime_helpers_get__WEBPACK_IMPORTED_MODULE_4___default()(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(ModelBase.prototype), "$formatJson", this).call(this, transformed, opt);

      return parsedJson;
    } }], [{ key: "query", value: function query() {var _get2,_this = this;for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {args[_key] = arguments[_key];}return (_get2 = _babel_runtime_helpers_get__WEBPACK_IMPORTED_MODULE_4___default()(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(ModelBase), "query", this)).call.apply(_get2, [this].concat(args)).runAfter(function (result) {if (Array.isArray(result)) {return _this.collection.from(result);}return result;});} }, { key: "collection", get: function get() {return Array;} }]);return ModelBase;}(objection__WEBPACK_IMPORTED_MODULE_6__["Model"]);

/***/ }),

/***/ "./src/models/Option.js":
/*!******************************!*\
  !*** ./src/models/Option.js ***!
  \******************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Option; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_get__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/get */ "@babel/runtime/helpers/get");
/* harmony import */ var _babel_runtime_helpers_get__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_get__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! objection */ "objection");
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(objection__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");
/* harmony import */ var _lib_Metable_MetableCollection__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/lib/Metable/MetableCollection */ "./src/lib/Metable/MetableCollection.js");


var

Option = /*#__PURE__*/function (_mixin) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_5___default()(Option, _mixin);function Option() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Option);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(Option).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Option, null, [{ key: "query",







    /**
                                                                                                                                                                                                                                                          * Override the model query.
                                                                                                                                                                                                                                                          * @param  {...any} args -
                                                                                                                                                                                                                                                          */value: function query()
    {var _get2;for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {args[_key] = arguments[_key];}
      return (_get2 = _babel_runtime_helpers_get__WEBPACK_IMPORTED_MODULE_4___default()(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(Option), "query", this)).call.apply(_get2, [this].concat(args)).runAfter(function (result) {
        if (result instanceof _lib_Metable_MetableCollection__WEBPACK_IMPORTED_MODULE_8__["default"]) {
          result.setModel(Option);
        }
        return result;
      });
    } }, { key: "tableName", /**
                              * Table name.
                              */get: function get() {return 'options';} }, { key: "collection", get: function get() {
      return _lib_Metable_MetableCollection__WEBPACK_IMPORTED_MODULE_8__["default"];
    } }]);return Option;}(Object(objection__WEBPACK_IMPORTED_MODULE_6__["mixin"])(_models_Model__WEBPACK_IMPORTED_MODULE_7__["default"], [objection__WEBPACK_IMPORTED_MODULE_6__["mixin"]]));

/***/ }),

/***/ "./src/models/PasswordReset.js":
/*!*************************************!*\
  !*** ./src/models/PasswordReset.js ***!
  \*************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return PasswordResets; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");
var

PasswordResets = /*#__PURE__*/function (_Model) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(PasswordResets, _Model);function PasswordResets() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, PasswordResets);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(PasswordResets).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(PasswordResets, null, [{ key: "tableName",
    /**
                                                                                                                                                                                                                                                                                                              * Table name
                                                                                                                                                                                                                                                                                                              */get: function get()
    {
      return 'password_resets';
    } }]);return PasswordResets;}(_models_Model__WEBPACK_IMPORTED_MODULE_5__["default"]);

/***/ }),

/***/ "./src/models/Permission.js":
/*!**********************************!*\
  !*** ./src/models/Permission.js ***!
  \**********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(__dirname) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Permission; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! objection */ "objection");
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(objection__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! path */ "path");
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");


var

Permission = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(Permission, _BaseModel);function Permission() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Permission);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(Permission).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Permission, null, [{ key: "tableName",
    /**
                                                                                                                                                                                                                                                                                              * Table name of Role model.
                                                                                                                                                                                                                                                                                              * @type {String}
                                                                                                                                                                                                                                                                                              */get: function get()
    {
      return 'permissions';
    }

    /**
       * Relationship mapping.
       */ }, { key: "relationMappings", get: function get()
    {
      return {
        /**
                * Permission model may belongs to role model.
                */
        role: {
          relation: objection__WEBPACK_IMPORTED_MODULE_5__["Model"].BelongsToOneRelation,
          modelBase: path__WEBPACK_IMPORTED_MODULE_6___default.a.join(__dirname, 'Role'),
          join: {
            from: 'permissions.role_id',
            to: 'roles.id' } }



        // resource: {
        //   relation: Model.BelongsToOneRelation,
        //   modelBase: path.join(__dirname, 'Resource'),
        //   join: {
        //     from: 'permissions.',
        //     to: '',
        //   }
        // }
      };
    } }]);return Permission;}(_models_Model__WEBPACK_IMPORTED_MODULE_7__["default"]);
/* WEBPACK VAR INJECTION */}.call(this, "/"))

/***/ }),

/***/ "./src/models/Resource.js":
/*!********************************!*\
  !*** ./src/models/Resource.js ***!
  \********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Resource; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! path */ "path");
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! objection */ "objection");
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(objection__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");


var

Resource = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(Resource, _BaseModel);function Resource() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Resource);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(Resource).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Resource, null, [{ key: "tableName",
    /**
                                                                                                                                                                                                                                                                                  * Table name.
                                                                                                                                                                                                                                                                                  */get: function get()
    {
      return 'resources';
    }

    /**
       * Timestamp columns.
       */ }, { key: "hasTimestamps", get: function get()
    {
      return false;
    }

    /**
       * Relationship mapping.
       */ }, { key: "relationMappings", get: function get()
    {
      var View = __webpack_require__(/*! @/models/View */ "./src/models/View.js");
      var ResourceField = __webpack_require__(/*! @/models/ResourceField */ "./src/models/ResourceField.js");
      var Permission = __webpack_require__(/*! @/models/Permission */ "./src/models/Permission.js");

      return {
        /**
                * Resource model may has many views.
                */
        views: {
          relation: objection__WEBPACK_IMPORTED_MODULE_6__["Model"].HasManyRelation,
          modelClass: View["default"],
          join: {
            from: 'resources.id',
            to: 'views.resourceId' } },



        /**
                                         * Resource model may has many fields.
                                         */
        fields: {
          relation: objection__WEBPACK_IMPORTED_MODULE_6__["Model"].HasManyRelation,
          modelClass: ResourceField["default"],
          join: {
            from: 'resources.id',
            to: 'resource_fields.resourceId' } },



        /**
                                                   * Resource model may has many associated permissions.
                                                   */
        permissions: {
          relation: objection__WEBPACK_IMPORTED_MODULE_6__["Model"].ManyToManyRelation,
          modelClass: Permission["default"],
          join: {
            from: 'resources.id',
            through: {
              from: 'role_has_permissions.resourceId',
              to: 'role_has_permissions.permissionId' },

            to: 'permissions.id' } } };



    } }]);return Resource;}(_models_Model__WEBPACK_IMPORTED_MODULE_7__["default"]);

/***/ }),

/***/ "./src/models/ResourceField.js":
/*!*************************************!*\
  !*** ./src/models/ResourceField.js ***!
  \*************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(__dirname) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ResourceField; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! lodash */ "lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! objection */ "objection");
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(objection__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! path */ "path");
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_7__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");



var

ResourceField = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(ResourceField, _BaseModel);function ResourceField() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, ResourceField);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(ResourceField).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(ResourceField, [{ key: "key",




































    /**
                                                                                                                                                                                                                                                                                                    * Resource field key.
                                                                                                                                                                                                                                                                                                    */value: function key()
    {
      return Object(lodash__WEBPACK_IMPORTED_MODULE_5__["snakeCase"])(this.labelName);
    }

    /**
       * Relationship mapping.
       */ }], [{ key: "tableName", /**
                                    * Table name.
                                    */get: function get() {return 'resource_fields';} }, { key: "jsonAttributes", get: function get() {return ['options'];} /**
                                                                                                                                                             * Model modifiers.
                                                                                                                                                             */ }, { key: "modifiers", get: function get() {return { whereNotPredefined: function whereNotPredefined(query) {query.whereNot('predefined', true);} };} /**
                                                                                                                                                                                                                                                                                                                       * Timestamp columns.
                                                                                                                                                                                                                                                                                                                       */ }, { key: "hasTimestamps", get: function get() {return false;} /**
                                                                                                                                                                                                                                                                                                                                                                                          * Virtual attributes.
                                                                                                                                                                                                                                                                                                                                                                                          */ }, { key: "virtualAttributes", get: function get() {return ['key'];} }, { key: "relationMappings", get: function get() {return { /**
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               * Resource field may belongs to resource model.
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               */resource: { relation: objection__WEBPACK_IMPORTED_MODULE_6__["Model"].BelongsToOneRelation, modelBase: path__WEBPACK_IMPORTED_MODULE_7___default.a.join(__dirname, 'Resource'), join: { from: 'resource_fields.resource_id',
            to: 'resources.id' } } };



    } }]);return ResourceField;}(_models_Model__WEBPACK_IMPORTED_MODULE_8__["default"]);
/* WEBPACK VAR INJECTION */}.call(this, "/"))

/***/ }),

/***/ "./src/models/ResourceFieldMetadata.js":
/*!*********************************************!*\
  !*** ./src/models/ResourceFieldMetadata.js ***!
  \*********************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(__dirname) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ResourceFieldMetadata; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! objection */ "objection");
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(objection__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! path */ "path");
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");
/* harmony import */ var _collection_ResourceFieldMetadataCollection__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/collection/ResourceFieldMetadataCollection */ "./src/collection/ResourceFieldMetadataCollection.js");



var

ResourceFieldMetadata = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(ResourceFieldMetadata, _BaseModel);function ResourceFieldMetadata() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, ResourceFieldMetadata);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(ResourceFieldMetadata).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(ResourceFieldMetadata, null, [{ key: "tableName",
    /**
                                                                                                                                                                                                                                                                                                                                                                * Table name.
                                                                                                                                                                                                                                                                                                                                                                */get: function get()
    {
      return 'resource_custom_fields_metadata';
    }

    /**
       * Override the resource field metadata collection.
       */ }, { key: "collection", get: function get()
    {
      return _collection_ResourceFieldMetadataCollection__WEBPACK_IMPORTED_MODULE_8__["default"];
    }

    /**
       * Relationship mapping.
       */ }, { key: "relationMappings", get: function get()
    {
      return {
        /**
                * Resource field may belongs to resource model.
                */
        resource: {
          relation: objection__WEBPACK_IMPORTED_MODULE_5__["Model"].BelongsToOneRelation,
          modelBase: path__WEBPACK_IMPORTED_MODULE_6___default.a.join(__dirname, 'Resource'),
          join: {
            from: 'resource_fields.resource_id',
            to: 'resources.id' } } };



    } }]);return ResourceFieldMetadata;}(_models_Model__WEBPACK_IMPORTED_MODULE_7__["default"]);
/* WEBPACK VAR INJECTION */}.call(this, "/"))

/***/ }),

/***/ "./src/models/Role.js":
/*!****************************!*\
  !*** ./src/models/Role.js ***!
  \****************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return Role; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! objection */ "objection");
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(objection__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");

var

Role = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(Role, _BaseModel);function Role() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Role);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(Role).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Role, null, [{ key: "tableName",
    /**
                                                                                                                                                                                                                                                          * Table name of Role model.
                                                                                                                                                                                                                                                          * @type {String}
                                                                                                                                                                                                                                                          */get: function get()
    {
      return 'roles';
    }

    /**
       * Timestamp columns.
       */ }, { key: "hasTimestamps", get: function get()
    {
      return false;
    }

    /**
       * Relationship mapping.
       */ }, { key: "relationMappings", get: function get()
    {
      var Permission = __webpack_require__(/*! @/models/Permission */ "./src/models/Permission.js");
      var Resource = __webpack_require__(/*! @/models/Resource */ "./src/models/Resource.js");
      var User = __webpack_require__(/*! @/models/User */ "./src/models/User.js");
      var ResourceField = __webpack_require__(/*! @/models/ResourceField */ "./src/models/ResourceField.js");

      return {
        /**
                * Role may has many permissions.
                */
        permissions: {
          relation: objection__WEBPACK_IMPORTED_MODULE_5__["Model"].ManyToManyRelation,
          modelClass: Permission["default"],
          join: {
            from: 'roles.id',
            through: {
              from: 'role_has_permissions.roleId',
              to: 'role_has_permissions.permissionId' },

            to: 'permissions.id' } },



        /**
                                       * Role may has many resources.
                                       */
        resources: {
          relation: objection__WEBPACK_IMPORTED_MODULE_5__["Model"].ManyToManyRelation,
          modelClass: Resource["default"],
          join: {
            from: 'roles.id',
            through: {
              from: 'role_has_permissions.roleId',
              to: 'role_has_permissions.resourceId' },

            to: 'resources.id' } },



        /**
                                     * Role may has resource field.
                                     */
        field: {
          relation: objection__WEBPACK_IMPORTED_MODULE_5__["Model"].BelongsToOneRelation,
          modelClass: ResourceField["default"],
          join: {
            from: 'roles.fieldId',
            to: 'resource_fields.id' } },



        /**
                                           * Role may has many associated users.
                                           */
        users: {
          relation: objection__WEBPACK_IMPORTED_MODULE_5__["Model"].ManyToManyRelation,
          modelClass: User["default"],
          join: {
            from: 'roles.id',
            through: {
              from: 'user_has_roles.roleId',
              to: 'user_has_roles.userId' },

            to: 'users.id' } } };



    } }]);return Role;}(_models_Model__WEBPACK_IMPORTED_MODULE_6__["default"]);

/***/ }),

/***/ "./src/models/User.js":
/*!****************************!*\
  !*** ./src/models/User.js ***!
  \****************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return User; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var bcryptjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! bcryptjs */ "bcryptjs");
/* harmony import */ var bcryptjs__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(bcryptjs__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! objection */ "objection");
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(objection__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");



// import PermissionsService from '@/services/PermissionsService';
var
User = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(User, _BaseModel);function User() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, User);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(User).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(User, [{ key: "verifyPassword",



































    /**
                                                                                                                                                                                                                                                         * Verify the password of the user.
                                                                                                                                                                                                                                                         * @param  {String} password - The given password.
                                                                                                                                                                                                                                                         * @return {Boolean}
                                                                                                                                                                                                                                                         */value: function verifyPassword(
    password) {
      return bcryptjs__WEBPACK_IMPORTED_MODULE_5___default.a.compareSync(password, this.password);
    } }, { key: "fullName", value: function fullName()

    {
      return "".concat(this.firstName, " ").concat(this.lastName);
    } }], [{ key: "virtualAttributes", // ...PermissionsService
    get: function get() {return ['fullName'];} /**
                                                * Table name
                                                */ }, { key: "tableName", get: function get() {return 'users';} /**
                                                                                                                 * Relationship mapping.
                                                                                                                 */ }, { key: "relationMappings", get: function get() {var Role = __webpack_require__(/*! @/models/Role */ "./src/models/Role.js");return { roles: { relation: objection__WEBPACK_IMPORTED_MODULE_6__["Model"].ManyToManyRelation, modelClass: Role["default"], join: { from: 'users.id', through: { from: 'user_has_roles.userId', to: 'user_has_roles.roleId' }, to: 'roles.id' } } };} }]);return User;}(_models_Model__WEBPACK_IMPORTED_MODULE_7__["default"]);

/***/ }),

/***/ "./src/models/View.js":
/*!****************************!*\
  !*** ./src/models/View.js ***!
  \****************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return View; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! path */ "path");
/* harmony import */ var path__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(path__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! objection */ "objection");
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(objection__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");


var

View = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(View, _BaseModel);function View() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, View);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(View).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(View, null, [{ key: "tableName",
    /**
                                                                                                                                                                                                                                                          * Table name.
                                                                                                                                                                                                                                                          */get: function get()
    {
      return 'views';
    }

    /**
       * Relationship mapping.
       */ }, { key: "relationMappings", get: function get()
    {
      var Resource = __webpack_require__(/*! @/models/Resource */ "./src/models/Resource.js");
      var ViewColumn = __webpack_require__(/*! @/models/ViewColumn */ "./src/models/ViewColumn.js");
      var ViewRole = __webpack_require__(/*! @/models/ViewRole */ "./src/models/ViewRole.js");

      return {
        /**
                * View model belongs to resource model.
                */
        resource: {
          relation: objection__WEBPACK_IMPORTED_MODULE_6__["Model"].BelongsToOneRelation,
          modelClass: Resource["default"],
          join: {
            from: 'views.resourceId',
            to: 'resources.id' } },



        /**
                                     * View model may has many columns.
                                     */
        columns: {
          relation: objection__WEBPACK_IMPORTED_MODULE_6__["Model"].HasManyRelation,
          modelClass: ViewColumn["default"],
          join: {
            from: 'views.id',
            to: 'view_has_columns.viewId' } },



        /**
                                                * View model may has many view roles.
                                                */
        roles: {
          relation: objection__WEBPACK_IMPORTED_MODULE_6__["Model"].HasManyRelation,
          modelClass: ViewRole["default"],
          join: {
            from: 'views.id',
            to: 'view_roles.viewId' } } };



    } }]);return View;}(_models_Model__WEBPACK_IMPORTED_MODULE_7__["default"]);

/***/ }),

/***/ "./src/models/ViewColumn.js":
/*!**********************************!*\
  !*** ./src/models/ViewColumn.js ***!
  \**********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ViewColumn; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");
var

ViewColumn = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(ViewColumn, _BaseModel);function ViewColumn() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, ViewColumn);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(ViewColumn).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(ViewColumn, null, [{ key: "tableName",
    /**
                                                                                                                                                                                                                                                                                              * Table name.
                                                                                                                                                                                                                                                                                              */get: function get()
    {
      return 'view_has_columns';
    }

    /**
       * Timestamp columns.
       */ }, { key: "hasTimestamps", get: function get()
    {
      return false;
    } }]);return ViewColumn;}(_models_Model__WEBPACK_IMPORTED_MODULE_5__["default"]);

/***/ }),

/***/ "./src/models/ViewRole.js":
/*!********************************!*\
  !*** ./src/models/ViewRole.js ***!
  \********************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ViewRole; });
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/possibleConstructorReturn */ "@babel/runtime/helpers/possibleConstructorReturn");
/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/getPrototypeOf */ "@babel/runtime/helpers/getPrototypeOf");
/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/inherits */ "@babel/runtime/helpers/inherits");
/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! objection */ "objection");
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(objection__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _models_Model__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/models/Model */ "./src/models/Model.js");

var

ViewRole = /*#__PURE__*/function (_BaseModel) {_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_4___default()(ViewRole, _BaseModel);function ViewRole() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, ViewRole);return _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_2___default()(this, _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_3___default()(ViewRole).apply(this, arguments));}_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(ViewRole, null, [{ key: "virtualAttributes",

    /**
                                                                                                                                                                                                                                                                                          * Virtual attributes.
                                                                                                                                                                                                                                                                                          */get: function get()
    {
      return ['comparators'];
    } }, { key: "comparators", get: function get()

    {
      return [
      'equals', 'not_equal', 'contains', 'not_contain'];

    }

    /**
       * Table name.
       */ }, { key: "tableName", get: function get()
    {
      return 'view_roles';
    }

    /**
       * Timestamp columns.
       */ }, { key: "hasTimestamps", get: function get()
    {
      return false;
    }

    /**
       * Relationship mapping.
       */ }, { key: "relationMappings", get: function get()
    {
      var ResourceField = __webpack_require__(/*! @/models/ResourceField */ "./src/models/ResourceField.js");
      var View = __webpack_require__(/*! @/models/View */ "./src/models/View.js");

      return {
        /**
                * View role model may belongs to view model.
                */
        view: {
          relation: objection__WEBPACK_IMPORTED_MODULE_5__["Model"].BelongsToOneRelation,
          modelClass: View["default"],
          join: {
            from: 'view_roles.viewId',
            to: 'views.id' } },



        /**
                                 * View role model may belongs to resource field model.
                                 */
        field: {
          relation: objection__WEBPACK_IMPORTED_MODULE_5__["Model"].BelongsToOneRelation,
          modelClass: ResourceField["default"],
          join: {
            from: 'view_roles.fieldId',
            to: 'resource_fields.id' } } };



    } }]);return ViewRole;}(_models_Model__WEBPACK_IMPORTED_MODULE_6__["default"]);

/***/ }),

/***/ "./src/models/index.js":
/*!*****************************!*\
  !*** ./src/models/index.js ***!
  \*****************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! objection */ "objection");
/* harmony import */ var objection__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(objection__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _database_knex__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @/database/knex */ "./src/database/knex.js");



// Bind all Models to a knex instance. If you only have one database in
// your server this is all you have to do. For multi database systems, see
// the Model.bindKnex() method.
objection__WEBPACK_IMPORTED_MODULE_0__["Model"].knex(_database_knex__WEBPACK_IMPORTED_MODULE_1__["default"]);

/***/ }),

/***/ "./src/server.js":
/*!***********************!*\
  !*** ./src/server.js ***!
  \***********************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var errorhandler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! errorhandler */ "errorhandler");
/* harmony import */ var errorhandler__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(errorhandler__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _app__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @/app */ "./src/app.js");



_app__WEBPACK_IMPORTED_MODULE_1__["default"].use(errorhandler__WEBPACK_IMPORTED_MODULE_0___default.a);

var server = _app__WEBPACK_IMPORTED_MODULE_1__["default"].listen(_app__WEBPACK_IMPORTED_MODULE_1__["default"].get('port'), function () {
  console.log(
  '  App is running at http://localhost:%d in %s mode',
  _app__WEBPACK_IMPORTED_MODULE_1__["default"].get('port'),
  _app__WEBPACK_IMPORTED_MODULE_1__["default"].get('env'));

  console.log('  Press CTRL-C to stop');
});

/* harmony default export */ __webpack_exports__["default"] = (server);

/***/ }),

/***/ "./src/services/Accounting/JournalEntry.js":
/*!*************************************************!*\
  !*** ./src/services/Accounting/JournalEntry.js ***!
  \*************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return JournalEntry; });
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__);
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}var
JournalEntry =
function JournalEntry(entry) {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default()(this, JournalEntry);
  var defaults = {
    credit: 0,
    debit: 0 };

  this.entry = _objectSpread({}, defaults, {}, entry);
};

/***/ }),

/***/ "./src/services/Accounting/JournalPoster.js":
/*!**************************************************!*\
  !*** ./src/services/Accounting/JournalPoster.js ***!
  \**************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return JournalPoster; });
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/defineProperty */ "@babel/runtime/helpers/defineProperty");
/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! lodash */ "lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! moment */ "moment");
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(moment__WEBPACK_IMPORTED_MODULE_6__);
/* harmony import */ var _services_Accounting_JournalEntry__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/services/Accounting/JournalEntry */ "./src/services/Accounting/JournalEntry.js");
/* harmony import */ var _models_AccountTransaction__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! @/models/AccountTransaction */ "./src/models/AccountTransaction.js");
/* harmony import */ var _models_AccountBalance__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! @/models/AccountBalance */ "./src/models/AccountBalance.js");
/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! @/utils */ "./src/utils/index.js");
function ownKeys(object, enumerableOnly) {var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {var symbols = Object.getOwnPropertySymbols(object);if (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 = arguments[i] != null ? arguments[i] : {};if (i % 2) {ownKeys(source, true).forEach(function (key) {_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(target, key, source[key]);});} else if (Object.getOwnPropertyDescriptors) {Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));} else {ownKeys(source).forEach(function (key) {Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));});}}return target;}




var

JournalPoster = /*#__PURE__*/function () {
  /**
                                           * Journal poster constructor.
                                           */
  function JournalPoster() {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3___default()(this, JournalPoster);
    this.entries = [];
    this.balancesChange = {};
  }

  /**
     * Writes the credit entry for the given account.
     * @param {JournalEntry} entry -
     */_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4___default()(JournalPoster, [{ key: "credit", value: function credit(
    entryModel) {
      if (entryModel instanceof _services_Accounting_JournalEntry__WEBPACK_IMPORTED_MODULE_7__["default"] === false) {
        throw new Error('The entry is not instance of JournalEntry.');
      }
      this.entries.push(entryModel.entry);
      this.setAccountBalanceChange(entryModel.entry, 'credit');
    }

    /**
       * Writes the debit entry for the given account.
       * @param {JournalEntry} entry -
       */ }, { key: "debit", value: function debit(
    entryModel) {
      if (entryModel instanceof _services_Accounting_JournalEntry__WEBPACK_IMPORTED_MODULE_7__["default"] === false) {
        throw new Error('The entry is not instance of JournalEntry.');
      }
      this.entries.push(entryModel.entry);
      this.setAccountBalanceChange(entryModel.entry, 'debit');
    }

    /**
       * Sets account balance change.
       * @param {JournalEntry} entry
       * @param {String} type
       */ }, { key: "setAccountBalanceChange", value: function setAccountBalanceChange(
    entry, type) {
      if (!this.balancesChange[entry.account]) {
        this.balancesChange[entry.account] = 0;
      }
      var change = 0;

      if (entry.accountNormal === 'credit') {
        change = type === 'credit' ? entry.credit : -1 * entry.debit;
      } else if (entry.accountNormal === 'debit') {
        change = type === 'debit' ? entry.debit : -1 * entry.credit;
      }
      this.balancesChange[entry.account] += change;
    }

    /**
       * Mapping the balance change to list.
       */ }, { key: "mapBalanceChangesToList", value: function mapBalanceChangesToList()
    {var _this = this;
      var mappedList = [];

      Object.keys(this.balancesChange).forEach(function (accountId) {
        var balance = _this.balancesChange[accountId];

        mappedList.push({
          account_id: accountId,
          amount: balance });

      });
      return mappedList;
    }

    /**
       * Saves the balance change of journal entries.
       */ }, { key: "saveBalance", value: function () {var _saveBalance = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee() {var balancesList, balanceUpdateOpers, balanceInsertOpers, balanceFindOneOpers, balanceAccounts;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:

                balancesList = this.mapBalanceChangesToList();
                balanceUpdateOpers = [];
                balanceInsertOpers = [];
                balanceFindOneOpers = [];
                balanceAccounts = [];

                balancesList.forEach(function (balance) {
                  var oper = _models_AccountBalance__WEBPACK_IMPORTED_MODULE_9__["default"].query().findOne('account_id', balance.account_id);
                  balanceFindOneOpers.push(oper);
                });_context.next = 8;return (
                  Promise.all(balanceFindOneOpers));case 8:balanceAccounts = _context.sent;

                balancesList.forEach(function (balance) {
                  var method = balance.amount < 0 ? 'decrement' : 'increment';

                  // Detarmine if the account balance is already exists or not.
                  var foundAccBalance = balanceAccounts.some(function (account) {return (
                      account && account.account_id === balance.account_id);});

                  if (foundAccBalance) {
                    var query = _models_AccountBalance__WEBPACK_IMPORTED_MODULE_9__["default"].
                    query()[method]('amount', Math.abs(balance.amount)).
                    where('account_id', balance.account_id);

                    balanceUpdateOpers.push(query);
                  } else {
                    var _query = _models_AccountBalance__WEBPACK_IMPORTED_MODULE_9__["default"].query().insert({
                      account_id: balance.account_id,
                      amount: balance.amount,
                      currency_code: 'USD' });

                    balanceInsertOpers.push(_query);
                  }
                });_context.next = 12;return (
                  Promise.all([].concat(
                  balanceUpdateOpers, balanceInsertOpers)));case 12:case "end":return _context.stop();}}}, _callee, this);}));function saveBalance() {return _saveBalance.apply(this, arguments);}return saveBalance;}()



    /**
                                                                                                                                                                                                                          * Saves the stacked journal entries to the storage.
                                                                                                                                                                                                                          */ }, { key: "saveEntries", value: function () {var _saveEntries = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee2() {var saveOperations;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:

                saveOperations = [];

                this.entries.forEach(function (entry) {
                  var oper = _models_AccountTransaction__WEBPACK_IMPORTED_MODULE_8__["default"].query().insert(_objectSpread({
                    accountId: entry.account },
                  Object(lodash__WEBPACK_IMPORTED_MODULE_5__["pick"])(entry, ['credit', 'debit', 'transactionType', 'date', 'userId',
                  'referenceType', 'referenceId', 'note'])));

                  saveOperations.push(function () {return oper;});
                });_context2.next = 4;return (
                  Object(_utils__WEBPACK_IMPORTED_MODULE_10__["promiseSerial"])(saveOperations));case 4:case "end":return _context2.stop();}}}, _callee2, this);}));function saveEntries() {return _saveEntries.apply(this, arguments);}return saveEntries;}()


    /**
                                                                                                                                                                                                                * Reverses the stacked journal entries.
                                                                                                                                                                                                                */ }, { key: "reverseEntries", value: function reverseEntries()
    {
      var reverseEntries = [];

      this.entries.forEach(function (entry) {
        var reverseEntry = _objectSpread({}, entry);

        if (entry.credit) {
          reverseEntry.debit = entry.credit;
        }
        if (entry.debit) {
          reverseEntry.credit = entry.debit;
        }
        reverseEntries.push(reverseEntry);
      });
      this.entries = reverseEntries;
    }

    /**
       * Delete the given or all stacked entries.
       * @param {Array} ids -
       */ }, { key: "deleteEntries", value: function () {var _deleteEntries = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee3(
      ids) {var entriesIds;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:
                entriesIds = ids || this.entries.map(function (e) {return e.id;});if (!(

                entriesIds.length > 0)) {_context3.next = 4;break;}_context3.next = 4;return (
                  _models_AccountTransaction__WEBPACK_IMPORTED_MODULE_8__["default"].query().whereIn('id', entriesIds)["delete"]());case 4:case "end":return _context3.stop();}}}, _callee3, this);}));function deleteEntries(_x) {return _deleteEntries.apply(this, arguments);}return deleteEntries;}()



    /**
                                                                                                                                                                                                                                                           * Retrieve the closing balance for the given account and closing date.
                                                                                                                                                                                                                                                           * @param {Number} accountId -
                                                                                                                                                                                                                                                           * @param {Date} closingDate -
                                                                                                                                                                                                                                                           */ }, { key: "getClosingBalance", value: function getClosingBalance(
    accountId, closingDate) {var dateType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'day';
      var closingBalance = 0;
      var momentClosingDate = moment__WEBPACK_IMPORTED_MODULE_6___default()(closingDate);

      this.entries.forEach(function (entry) {
        // Can not continue if not before or event same closing date.
        if (!momentClosingDate.isAfter(entry.date, dateType) &&
        !momentClosingDate.isSame(entry.date, dateType) ||
        entry.account !== accountId && accountId) {
          return;
        }
        if (entry.accountNormal === 'credit') {
          closingBalance += entry.credit ? entry.credit : -1 * entry.debit;
        } else if (entry.accountNormal === 'debit') {
          closingBalance += entry.debit ? entry.debit : -1 * entry.credit;
        }
      });
      return closingBalance;
    }

    /**
       * Retrieve the credit/debit sumation for the given account and date.
       * @param {Number} account -
       * @param {Date|String} closingDate -
       */ }, { key: "getTrialBalance", value: function getTrialBalance(
    accountId, closingDate, dateType) {
      var momentClosingDate = moment__WEBPACK_IMPORTED_MODULE_6___default()(closingDate);
      var result = {
        credit: 0,
        debit: 0,
        balance: 0 };

      this.entries.forEach(function (entry) {
        if (!momentClosingDate.isAfter(entry.date, dateType) &&
        !momentClosingDate.isSame(entry.date, dateType) ||
        entry.account !== accountId && accountId) {
          return;
        }
        result.credit += entry.credit;
        result.debit += entry.debit;

        if (entry.accountNormal === 'credit') {
          result.balance += entry.credit ? entry.credit : -1 * entry.debit;
        } else if (entry.accountNormal === 'debit') {
          result.balance += entry.debit ? entry.debit : -1 * entry.credit;
        }
      });
      return result;
    }

    /**
       * Load fetched accounts journal entries.
       * @param {Array} entries -
       */ }, { key: "loadEntries", value: function loadEntries(
    entries) {var _this2 = this;
      entries.forEach(function (entry) {
        _this2.entries.push(_objectSpread({},
        entry, {
          account: entry.account ? entry.account.id : entry.accountId,
          accountNormal: entry.account && entry.account.type ?
          entry.account.type.normal : entry.accountNormal }));

      });
    } }], [{ key: "loadAccounts", value: function loadAccounts()

    {

    } }]);return JournalPoster;}();

/***/ }),

/***/ "./src/services/CustomFields/ResourceCustomFieldRepository.js":
/*!********************************************************************!*\
  !*** ./src/services/CustomFields/ResourceCustomFieldRepository.js ***!
  \********************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return ResourceCustomFieldRepository; });
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/regenerator */ "@babel/runtime/regenerator");
/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ "@babel/runtime/helpers/asyncToGenerator");
/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @babel/runtime/helpers/classCallCheck */ "@babel/runtime/helpers/classCallCheck");
/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @babel/runtime/helpers/createClass */ "@babel/runtime/helpers/createClass");
/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _models_Resource__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! @/models/Resource */ "./src/models/Resource.js");
/* harmony import */ var _models_ResourceField__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @/models/ResourceField */ "./src/models/ResourceField.js");
/* harmony import */ var _models_ResourceFieldMetadata__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! @/models/ResourceFieldMetadata */ "./src/models/ResourceFieldMetadata.js");
/* harmony import */ var _collection_ResourceFieldMetadataCollection__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! @/collection/ResourceFieldMetadataCollection */ "./src/collection/ResourceFieldMetadataCollection.js");



var

ResourceCustomFieldRepository = /*#__PURE__*/function () {
  /**
                                                           * Class constructor.
                                                           */
  function ResourceCustomFieldRepository(model) {_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, ResourceCustomFieldRepository);
    if (typeof model === 'function') {
      this.resourceName = model.name;
    } else if (typeof model === 'string') {
      this.resourceName = model;
    }
    // Custom fields of the given resource.
    this.customFields = [];
    this.filledCustomFields = {};

    // metadata of custom fields of the given resource.
    this.fieldsMetadata = {};
    this.resource = {};
  }

  /**
     * Fetches metadata of custom fields of the given resource.
     * @param {Integer} id - Resource item id.
     */_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(ResourceCustomFieldRepository, [{ key: "fetchCustomFieldsMetadata", value: function () {var _fetchCustomFieldsMetadata = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(
      id) {var metadata;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) {while (1) {switch (_context.prev = _context.next) {case 0:if (!(
                typeof id === 'undefined')) {_context.next = 2;break;}throw (
                  new Error('Please define the resource item id.'));case 2:if (

                this.resource) {_context.next = 4;break;}throw (
                  new Error('Target resource model is not found.'));case 4:_context.next = 6;return (

                  _models_ResourceFieldMetadata__WEBPACK_IMPORTED_MODULE_6__["default"].query().
                  where('resource_id', this.resource.id).
                  where('resource_item_id', id));case 6:metadata = _context.sent;

                this.fieldsMetadata[id] = metadata;case 8:case "end":return _context.stop();}}}, _callee, this);}));function fetchCustomFieldsMetadata(_x) {return _fetchCustomFieldsMetadata.apply(this, arguments);}return fetchCustomFieldsMetadata;}()


    /**
                                                                                                                                                                                                                                                            * Load resource.
                                                                                                                                                                                                                                                            */ }, { key: "loadResource", value: function () {var _loadResource = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() {var resource;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {while (1) {switch (_context2.prev = _context2.next) {case 0:_context2.next = 2;return (

                  _models_Resource__WEBPACK_IMPORTED_MODULE_4__["default"].query().where('name', this.resourceName).first());case 2:resource = _context2.sent;if (

                resource) {_context2.next = 5;break;}throw (
                  new Error('There is no stored resource in the storage with the given model name.'));case 5:

                this.setResource(resource);case 6:case "end":return _context2.stop();}}}, _callee2, this);}));function loadResource() {return _loadResource.apply(this, arguments);}return loadResource;}()


    /**
                                                                                                                                                                                                             * Load metadata of the resource.
                                                                                                                                                                                                             */ }, { key: "loadResourceCustomFields", value: function () {var _loadResourceCustomFields = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3() {var customFields;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {while (1) {switch (_context3.prev = _context3.next) {case 0:if (!(

                typeof this.resource.id === 'undefined')) {_context3.next = 2;break;}throw (
                  new Error('Please fetch resource details before fetch custom fields of the resource.'));case 2:_context3.next = 4;return (

                  _models_ResourceField__WEBPACK_IMPORTED_MODULE_5__["default"].query().
                  where('resource_id', this.resource.id).
                  modify('whereNotPredefined'));case 4:customFields = _context3.sent;

                this.setResourceCustomFields(customFields);case 6:case "end":return _context3.stop();}}}, _callee3, this);}));function loadResourceCustomFields() {return _loadResourceCustomFields.apply(this, arguments);}return loadResourceCustomFields;}()


    /**
                                                                                                                                                                                                                                                                 * Sets resource model.
                                                                                                                                                                                                                                                                 * @param {Resource} resource -
                                                                                                                                                                                                                                                                 */ }, { key: "setResource", value: function setResource(
    resource) {
      this.resource = resource;
    }

    /**
       * Sets resource custom fields collection.
       * @param {Array} customFields -
       */ }, { key: "setResourceCustomFields", value: function setResourceCustomFields(
    customFields) {
      this.customFields = customFields;
    }

    /**
       * Retrieve metadata of the resource custom fields.
       * @param {Integer} itemId -
       */ }, { key: "getMetadata", value: function getMetadata(
    itemId) {
      return this.fieldsMetadata[itemId] || this.fieldsMetadata;
    }

    /**
       * Fill metadata of the custom fields that associated to the resource.
       * @param {Inter} id - Resource item id.
       * @param {Array} attributes -
       */ }, { key: "fillCustomFields", value: function fillCustomFields(
    id, attributes) {var _this = this;
      if (typeof this.filledCustomFields[id] === 'undefined') {
        this.filledCustomFields[id] = [];
      }
      attributes.forEach(function (attr) {
        _this.filledCustomFields[id].push(attr);

        if (!_this.fieldsMetadata[id]) {
          _this.fieldsMetadata[id] = new _collection_ResourceFieldMetadataCollection__WEBPACK_IMPORTED_MODULE_7__["default"]();
        }
        _this.fieldsMetadata[id].setMeta(attr.key, attr.value, {
          resource_id: _this.resource.id,
          resource_item_id: id });

      });
    }

    /**
       * Saves the instered, updated and deleted  custom fields metadata.
       * @param {Integer} id - Optional resource item id.
       */ }, { key: "saveCustomFields", value: function () {var _saveCustomFields = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4(
      id) {var opers;return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) {while (1) {switch (_context4.prev = _context4.next) {case 0:if (!
                id) {_context4.next = 7;break;}if (!(
                typeof this.fieldsMetadata[id] === 'undefined')) {_context4.next = 3;break;}throw (
                  new Error('There is no resource item with the given id.'));case 3:_context4.next = 5;return (

                  this.fieldsMetadata[id].saveMeta());case 5:_context4.next = 11;break;case 7:

                opers = [];
                this.fieldsMetadata.forEach(function (metadata) {
                  var oper = metadata.saveMeta();
                  opers.push(oper);
                });_context4.next = 11;return (
                  Promise.all(opers));case 11:case "end":return _context4.stop();}}}, _callee4, this);}));function saveCustomFields(_x2) {return _saveCustomFields.apply(this, arguments);}return saveCustomFields;}()



    /**
                                                                                                                                                                                                                        * Validates the exist custom fields.
                                                                                                                                                                                                                        */ }, { key: "validateExistCustomFields", value: function validateExistCustomFields()
    {

    } }, { key: "toArray", value: function toArray()

    {
      return this.fieldsMetadata.toArray();
    } }, { key: "load", value: function () {var _load = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5() {return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) {while (1) {switch (_context5.prev = _context5.next) {case 0:_context5.next = 2;return (


                  this.loadResource());case 2:_context5.next = 4;return (
                  this.loadResourceCustomFields());case 4:case "end":return _context5.stop();}}}, _callee5, this);}));function load() {return _load.apply(this, arguments);}return load;}() }], [{ key: "forgeMetadataCollection", value: function forgeMetadataCollection()


    {

    } }]);return ResourceCustomFieldRepository;}();

/***/ }),

/***/ "./src/services/Moment/index.js":
/*!**************************************!*\
  !*** ./src/services/Moment/index.js ***!
  \**************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! moment */ "moment");
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(moment__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var moment_range__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! moment-range */ "moment-range");
/* harmony import */ var moment_range__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(moment_range__WEBPACK_IMPORTED_MODULE_1__);



var moment = Object(moment_range__WEBPACK_IMPORTED_MODULE_1__["extendMoment"])(moment__WEBPACK_IMPORTED_MODULE_0___default.a);

/* harmony default export */ __webpack_exports__["default"] = (moment);

/***/ }),

/***/ "./src/services/mail.js":
/*!******************************!*\
  !*** ./src/services/mail.js ***!
  \******************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var nodemailer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! nodemailer */ "nodemailer");
/* harmony import */ var nodemailer__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(nodemailer__WEBPACK_IMPORTED_MODULE_0__);


// create reusable transporter object using the default SMTP transport
var transporter = nodemailer__WEBPACK_IMPORTED_MODULE_0___default.a.createTransport({
  host: process.env.MAIL_HOST,
  port: Number(process.env.MAIL_PORT),
  secure: process.env.MAIL_SECURE === 'true', // true for 465, false for other ports
  auth: {
    user: process.env.MAIL_USERNAME,
    pass: process.env.MAIL_PASSWORD } });



/* harmony default export */ __webpack_exports__["default"] = (transporter);

/***/ }),

/***/ "./src/utils/index.js":
/*!****************************!*\
  !*** ./src/utils/index.js ***!
  \****************************/
/*! exports provided: hashPassword, origin, dateRangeCollection, dateRangeFormat, mapValuesDeep, mapKeysDeep, promiseSerial */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "hashPassword", function() { return hashPassword; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "origin", function() { return origin; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dateRangeCollection", function() { return dateRangeCollection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dateRangeFormat", function() { return dateRangeFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapValuesDeep", function() { return mapValuesDeep; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "mapKeysDeep", function() { return mapKeysDeep; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "promiseSerial", function() { return promiseSerial; });
/* harmony import */ var bcryptjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! bcryptjs */ "bcryptjs");
/* harmony import */ var bcryptjs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(bcryptjs__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! moment */ "moment");
/* harmony import */ var moment__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(moment__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lodash */ "lodash");
/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_2__);


var _require =
__webpack_require__(/*! lodash */ "lodash"),map = _require.map,isArray = _require.isArray,isPlainObject = _require.isPlainObject,mapKeys = _require.mapKeys,mapValues = _require.mapValues;


var hashPassword = function hashPassword(password) {return new Promise(function (resolve) {
    bcryptjs__WEBPACK_IMPORTED_MODULE_0___default.a.genSalt(10, function (error, salt) {
      bcryptjs__WEBPACK_IMPORTED_MODULE_0___default.a.hash(password, salt, function (err, hash) {resolve(hash);});
    });
  });};

var origin = function origin(request) {return "".concat(request.protocol, "://").concat(request.hostname);};

var dateRangeCollection = function dateRangeCollection(fromDate, toDate) {var addType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'day';var increment = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1;
  var collection = [];
  var momentFromDate = moment__WEBPACK_IMPORTED_MODULE_1___default()(fromDate);
  var dateFormat = '';

  switch (addType) {
    case 'day':
    default:
      dateFormat = 'YYYY-MM-DD';break;
    case 'month':
    case 'quarter':
      dateFormat = 'YYYY-MM';break;
    case 'year':
      dateFormat = 'YYYY';break;}

  for (var i = momentFromDate;
  i.isBefore(toDate, addType) || i.isSame(toDate, addType);
  i.add(increment, "".concat(addType, "s"))) {
    collection.push(i.endOf(addType).format(dateFormat));
  }
  return collection;
};

var dateRangeFormat = function dateRangeFormat(rangeType) {
  switch (rangeType) {
    case 'year':
      return 'YYYY';
    case 'month':
    case 'quarter':
    default:
      return 'YYYY-MM';}

};


var mapKeysDeep = function mapKeysDeep(obj, cb) {
  if (lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isArray(obj)) {
    return obj.map(function (innerObj) {return mapKeysDeep(innerObj, cb);});
  } else
  if (lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isObject(obj)) {
    return lodash__WEBPACK_IMPORTED_MODULE_2___default.a.mapValues(
    lodash__WEBPACK_IMPORTED_MODULE_2___default.a.mapKeys(obj, cb),
    function (val) {return mapKeysDeep(val, cb);});

  } else {
    return obj;
  }
};

var mapValuesDeep = function mapValuesDeep(v, callback) {return (
    lodash__WEBPACK_IMPORTED_MODULE_2___default.a.isObject(v) ?
    lodash__WEBPACK_IMPORTED_MODULE_2___default.a.mapValues(v, function (v) {return mapValuesDeep(v, callback);}) :
    callback(v));};


var promiseSerial = function promiseSerial(funcs) {
  return funcs.reduce(function (promise, func) {return promise.then(function (result) {return func().then(Array.prototype.concat.bind(result));});},
  Promise.resolve([]));
};



/***/ }),

/***/ 0:
/*!*********************************************************!*\
  !*** multi @babel/plugin-transform-runtime @/server.js ***!
  \*********************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

__webpack_require__(/*! @babel/plugin-transform-runtime */"@babel/plugin-transform-runtime");
module.exports = __webpack_require__(/*! @/server.js */"./src/server.js");


/***/ }),

/***/ "@babel/plugin-transform-runtime":
/*!**************************************************!*\
  !*** external "@babel/plugin-transform-runtime" ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("@babel/plugin-transform-runtime");

/***/ }),

/***/ "@babel/runtime/helpers/asyncToGenerator":
/*!**********************************************************!*\
  !*** external "@babel/runtime/helpers/asyncToGenerator" ***!
  \**********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("@babel/runtime/helpers/asyncToGenerator");

/***/ }),

/***/ "@babel/runtime/helpers/classCallCheck":
/*!********************************************************!*\
  !*** external "@babel/runtime/helpers/classCallCheck" ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("@babel/runtime/helpers/classCallCheck");

/***/ }),

/***/ "@babel/runtime/helpers/createClass":
/*!*****************************************************!*\
  !*** external "@babel/runtime/helpers/createClass" ***!
  \*****************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("@babel/runtime/helpers/createClass");

/***/ }),

/***/ "@babel/runtime/helpers/defineProperty":
/*!********************************************************!*\
  !*** external "@babel/runtime/helpers/defineProperty" ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("@babel/runtime/helpers/defineProperty");

/***/ }),

/***/ "@babel/runtime/helpers/get":
/*!*********************************************!*\
  !*** external "@babel/runtime/helpers/get" ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("@babel/runtime/helpers/get");

/***/ }),

/***/ "@babel/runtime/helpers/getPrototypeOf":
/*!********************************************************!*\
  !*** external "@babel/runtime/helpers/getPrototypeOf" ***!
  \********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("@babel/runtime/helpers/getPrototypeOf");

/***/ }),

/***/ "@babel/runtime/helpers/inherits":
/*!**************************************************!*\
  !*** external "@babel/runtime/helpers/inherits" ***!
  \**************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("@babel/runtime/helpers/inherits");

/***/ }),

/***/ "@babel/runtime/helpers/possibleConstructorReturn":
/*!*******************************************************************!*\
  !*** external "@babel/runtime/helpers/possibleConstructorReturn" ***!
  \*******************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("@babel/runtime/helpers/possibleConstructorReturn");

/***/ }),

/***/ "@babel/runtime/helpers/slicedToArray":
/*!*******************************************************!*\
  !*** external "@babel/runtime/helpers/slicedToArray" ***!
  \*******************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("@babel/runtime/helpers/slicedToArray");

/***/ }),

/***/ "@babel/runtime/helpers/toConsumableArray":
/*!***********************************************************!*\
  !*** external "@babel/runtime/helpers/toConsumableArray" ***!
  \***********************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("@babel/runtime/helpers/toConsumableArray");

/***/ }),

/***/ "@babel/runtime/regenerator":
/*!*********************************************!*\
  !*** external "@babel/runtime/regenerator" ***!
  \*********************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("@babel/runtime/regenerator");

/***/ }),

/***/ "bcryptjs":
/*!***************************!*\
  !*** external "bcryptjs" ***!
  \***************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("bcryptjs");

/***/ }),

/***/ "dotenv":
/*!*************************!*\
  !*** external "dotenv" ***!
  \*************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("dotenv");

/***/ }),

/***/ "errorhandler":
/*!*******************************!*\
  !*** external "errorhandler" ***!
  \*******************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("errorhandler");

/***/ }),

/***/ "express":
/*!**************************!*\
  !*** external "express" ***!
  \**************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("express");

/***/ }),

/***/ "express-boom":
/*!*******************************!*\
  !*** external "express-boom" ***!
  \*******************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("express-boom");

/***/ }),

/***/ "express-validator":
/*!************************************!*\
  !*** external "express-validator" ***!
  \************************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("express-validator");

/***/ }),

/***/ "fs":
/*!*********************!*\
  !*** external "fs" ***!
  \*********************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("fs");

/***/ }),

/***/ "helmet":
/*!*************************!*\
  !*** external "helmet" ***!
  \*************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("helmet");

/***/ }),

/***/ "i18n":
/*!***********************!*\
  !*** external "i18n" ***!
  \***********************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("i18n");

/***/ }),

/***/ "jsonwebtoken":
/*!*******************************!*\
  !*** external "jsonwebtoken" ***!
  \*******************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("jsonwebtoken");

/***/ }),

/***/ "knex":
/*!***********************!*\
  !*** external "knex" ***!
  \***********************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("knex");

/***/ }),

/***/ "lodash":
/*!*************************!*\
  !*** external "lodash" ***!
  \*************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("lodash");

/***/ }),

/***/ "moment":
/*!*************************!*\
  !*** external "moment" ***!
  \*************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("moment");

/***/ }),

/***/ "moment-range":
/*!*******************************!*\
  !*** external "moment-range" ***!
  \*******************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("moment-range");

/***/ }),

/***/ "mustache":
/*!***************************!*\
  !*** external "mustache" ***!
  \***************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("mustache");

/***/ }),

/***/ "nodemailer":
/*!*****************************!*\
  !*** external "nodemailer" ***!
  \*****************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("nodemailer");

/***/ }),

/***/ "objection":
/*!****************************!*\
  !*** external "objection" ***!
  \****************************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("objection");

/***/ }),

/***/ "path":
/*!***********************!*\
  !*** external "path" ***!
  \***********************/
/*! no static exports found */
/***/ (function(module, exports) {

module.exports = require("path");

/***/ })

/******/ });
//# sourceMappingURL=data:application/json;charset=utf-8;base64,[encoded data, 334608 characters]