@azrico/webobject 1.5.59 → 1.5.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,166 +1,208 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports["default"] = exports.SimpleObject = void 0;
7
- var _object = require("@azrico/object");
8
- var _string = require("@azrico/string");
9
- var _global = require("@azrico/global");
10
- var _MapableObject2 = require("./MapableObject");
11
- var _ObjectManager = _interopRequireDefault(require("./ObjectManager"));
12
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
13
- function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
14
- function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
15
- function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
16
- function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
17
- function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
18
- function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
19
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
20
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
21
- function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
22
- function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
23
- function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
24
- function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
25
- function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
26
- function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
27
- function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
28
- function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
29
- function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
30
- function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
31
- function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
32
- function _superPropGet(t, o, e, r) { var p = _get(_getPrototypeOf(1 & r ? t.prototype : t), o, e); return 2 & r && "function" == typeof p ? function (t) { return p.apply(e, t); } : p; }
33
- function _get() { return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) { var p = _superPropBase(e, t); if (p) { var n = Object.getOwnPropertyDescriptor(p, t); return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value; } }, _get.apply(null, arguments); }
34
- function _superPropBase(t, o) { for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t));); return t; }
35
- function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
36
- function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
37
- function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
38
- function _classPrivateMethodInitSpec(e, a) { _checkPrivateRedeclaration(e, a), a.add(e); }
39
- function _classPrivateFieldInitSpec(e, t, a) { _checkPrivateRedeclaration(e, t), t.set(e, a); }
40
- function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); }
41
- function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
42
- function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
43
- function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
44
- function _classPrivateFieldSet(s, a, r) { return s.set(_assertClassBrand(s, a), r), r; }
45
- function _classPrivateFieldGet(s, a) { return s.get(_assertClassBrand(s, a)); }
46
- function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); }
47
- var _objectColor = /*#__PURE__*/new WeakMap();
48
- var _SimpleObject_brand = /*#__PURE__*/new WeakSet();
49
- var SimpleObject = exports.SimpleObject = /*#__PURE__*/function (_MapableObject) {
50
- function SimpleObject() {
51
- var _this;
52
- var is_readonly = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
53
- _classCallCheck(this, SimpleObject);
54
- _this = _callSuper(this, SimpleObject);
55
- _classPrivateMethodInitSpec(_this, _SimpleObject_brand);
56
- //an exact copy of this object is stored here
57
- _defineProperty(_this, "__originalobject", void 0);
58
- //changes are saved here
59
- _defineProperty(_this, "__delta", {});
60
- //// protected __has_delta: boolean = false;
61
- //the last thing that was changed on this object
62
- _defineProperty(_this, "__lastChanged", void 0);
63
- //is the object read only
64
- _defineProperty(_this, "__is_readonly", void 0);
65
- //should we throw errors when encountering an error?
66
- //is TRUE by default
67
- _defineProperty(_this, "__throw_errors", void 0);
68
- //is this object marked as deleted?
69
- _defineProperty(_this, "_deleted", void 0);
70
- _defineProperty(_this, "_archived", void 0);
71
- _defineProperty(_this, "_deletedBy", void 0);
72
- //is this object locked?
73
- _defineProperty(_this, "_locked", void 0);
74
- //errors
75
- _defineProperty(_this, "__errors", void 0);
76
- _defineProperty(_this, "__showErrors", void 0);
77
- //refresh func
78
- _defineProperty(_this, "__refresh_functions", void 0);
79
- //save results
80
- _defineProperty(_this, "__saveResultObject", void 0);
81
- _defineProperty(_this, "__saveResultIsSuccess", true);
82
- _defineProperty(_this, "__saveResultType", void 0);
83
- //init function
84
- _defineProperty(_this, "__initialized", void 0);
85
- _classPrivateFieldInitSpec(_this, _objectColor, void 0);
86
- //id in the database
87
- _defineProperty(_this, "_id", "");
88
- //sequence key (usually managed by the database)
89
- _defineProperty(_this, "_index_key", "");
90
- //sequence value , used to index the object with increasing numbers
91
- _defineProperty(_this, "_index_value", -1);
92
- _defineProperty(_this, "getSubValue", _assertClassBrand(_SimpleObject_brand, _this, _getSubProperty));
1
+ import { array_intersection, array_isEmpty, array_merge, fn_eval, fn_eval_this, object_clone, object_equals, object_get, object_getStatic, object_isClass, object_isEmpty, object_isTrue, object_removeKeys, object_set, wrap_array, } from "@azrico/object";
2
+ import { combine_if_not_blank, string_isEmpty, string_to_color, } from "@azrico/string";
3
+ import { gcache, gfunc } from "@azrico/global";
4
+ import { MapableObject } from "./MapableObject";
5
+ import ObjectManager from "./ObjectManager";
6
+ export class SimpleObject extends MapableObject {
7
+ static __db_name = "";
8
+ static __object_name = "";
9
+ //these properties should not be changed and are usually set by server
10
+ static __unchangeables = [];
11
+ //these properties can be directly changed and are included in deltaObject
12
+ static __changeables = [];
13
+ //these properties usually are not directly changed and sometimes are included in deltaObject
14
+ static __extraProperties = [];
15
+ //these properties are never sent to database but may be sent to client
16
+ static __tempProperties = [];
17
+ //these properties can only be changed by the _creator
18
+ static __protectedProperties = [];
19
+ //these properties will be evaluated when needed
20
+ static __functionProperties = [];
21
+ //apply these string formats
22
+ static __formatList;
23
+ //types for children can be used when importing children
24
+ static __childTypes;
25
+ //these fields are used when importing
26
+ static __importColumns;
27
+ //these fields can be used when importing and checking if an item exists
28
+ static __checkProperties = [];
29
+ static __use_delta = true;
30
+ _static() {
31
+ return this.constructor;
32
+ }
33
+ //an exact copy of this object is stored here
34
+ __originalobject;
35
+ //changes are saved here
36
+ __delta = {};
37
+ //// protected __has_delta: boolean = false;
38
+ //the last thing that was changed on this object
39
+ __lastChanged;
40
+ //is the object read only
41
+ __is_readonly;
42
+ //should we throw errors when encountering an error?
43
+ //is TRUE by default
44
+ __throw_errors;
45
+ //is this object marked as deleted?
46
+ _deleted;
47
+ _archived;
48
+ _deletedBy;
49
+ //is this object locked?
50
+ _locked;
51
+ //errors
52
+ __errors;
53
+ __showErrors;
54
+ //refresh func
55
+ __refresh_functions;
56
+ //save results
57
+ __saveResultObject;
58
+ __saveResultIsSuccess = true;
59
+ __saveResultType;
60
+ //init function
61
+ __initialized;
62
+ #objectColor;
63
+ //id in the database
64
+ _id = "";
65
+ //sequence key (usually managed by the database)
66
+ _index_key = "";
67
+ //sequence value , used to index the object with increasing numbers
68
+ _index_value = -1;
69
+ constructor(is_readonly = false) {
70
+ super();
71
+ this.__is_readonly = is_readonly;
72
+ if (this._id)
73
+ this.__table_id = this._id;
74
+ this.clear_changes();
75
+ }
76
+ init(...p) {
77
+ this.__initialized = true;
78
+ }
79
+ get(key, original = false) {
80
+ //check if we should treat the prop as a function
81
+ const is_fnc = this.constructor["__functionProperties"] != null &&
82
+ this.constructor["__functionProperties"].includes(key);
83
+ //check if we should use delta version or normal version for this property
84
+ let used_value;
85
+ if (typeof key === "string" && key.includes(".")) {
86
+ /* ----------------------------- using sub value ---------------------------- */
87
+ const keysp = key.split(".");
88
+ const key_part = keysp.shift();
89
+ const subkey_part = keysp.shift();
90
+ used_value = this.#getSubProperty(key_part, subkey_part);
91
+ }
92
+ else {
93
+ /* --------------------------- using this or delta -------------------------- */
94
+ const self_key = key;
95
+ const use_orig = original || !this.__use_delta || !(self_key in this.__delta);
96
+ used_value = (use_orig ? this[self_key] : this.__delta[self_key]);
97
+ }
98
+ return is_fnc ? fn_eval_this(this, used_value) : used_value;
99
+ }
93
100
  /**
94
- * @deprecated use `set`
95
- * set value and run the event handlers if needed
96
- * @return true if changed , false otherwise
97
- */
98
- _defineProperty(_this, "setValue", _this.set);
99
- /**
100
- * set value of a key to now date time
101
+ * static get method for SimpleObject
102
+ * @param obj
101
103
  * @param key
102
- * @param value
104
+ * @param original
103
105
  * @returns
104
- */
105
- _defineProperty(_this, "setDefaultValueNow", _assertClassBrand(_SimpleObject_brand, _this, _setDefaultPropertyNow));
106
+ */
107
+ static get(obj, key, original = false) {
108
+ if (obj == null)
109
+ return undefined;
110
+ if (obj instanceof SimpleObject && typeof obj.get === "function")
111
+ return obj.get(key, original);
112
+ /* ------------------------------- manual get ------------------------------- */
113
+ if (!original &&
114
+ obj.__use_delta != false &&
115
+ typeof obj.__delta === "object" &&
116
+ key in obj.__delta) {
117
+ //@ts-ignore
118
+ return obj.__delta[key];
119
+ }
120
+ return obj[key];
121
+ }
122
+ /**
123
+ * use a property from the object, this will return latest value of the property
124
+ * uses `EventManager` to detect changes
125
+ *
126
+ * Only objects with a manager can use this function
127
+ */
128
+ use(key) {
129
+ if (this.manager == null) {
130
+ console.warn("Objects with no manager should not use useProperty");
131
+ return this.get(key);
132
+ }
133
+ return this.manager.use(key);
134
+ }
135
+ #getSubProperty(key, subkey, original = false) {
136
+ let subobj = this.get(key, original);
137
+ if (subobj == null || typeof subobj !== "object")
138
+ return undefined;
139
+ return subobj[subkey];
140
+ }
141
+ getSubValue = this.#getSubProperty;
142
+ /* -------------------------------------------------------------------------- */
143
+ /* set */
144
+ /* -------------------------------------------------------------------------- */
106
145
  /**
107
146
  * set value of a key only if the value is empty (null,undef,"")
108
147
  * @param key
109
148
  * @param value
110
149
  * @returns
111
- */
112
- _defineProperty(_this, "setDefault", _this.setDefaultValue);
113
- _defineProperty(_this, "get_managerClass", function () {
114
- return undefined;
115
- });
116
- _this.__is_readonly = is_readonly;
117
- if (_this._id) _this.__table_id = _this._id;
118
- _this.clear_changes();
119
- return _this;
120
- }
121
- _inherits(SimpleObject, _MapableObject);
122
- return _createClass(SimpleObject, [{
123
- key: "_static",
124
- value: function _static() {
125
- return this.constructor;
126
- }
127
- }, {
128
- key: "init",
129
- value: function init() {
130
- this.__initialized = true;
131
- }
132
- }, {
133
- key: "get",
134
- value: function get(key) {
135
- var original = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
136
- //check if we should treat the prop as a function
137
- var is_fnc = this.constructor["__functionProperties"] != null && this.constructor["__functionProperties"].includes(key);
138
- //check if we should use delta version or normal version for this property
139
- var used_value;
140
- if (typeof key === "string" && key.includes(".")) {
141
- /* ----------------------------- using sub value ---------------------------- */
142
- var keysp = key.split(".");
143
- var key_part = keysp.shift();
144
- var subkey_part = keysp.shift();
145
- used_value = _assertClassBrand(_SimpleObject_brand, this, _getSubProperty).call(this, key_part, subkey_part);
146
- } else {
147
- /* --------------------------- using this or delta -------------------------- */
148
- var self_key = key;
149
- var use_orig = original || !this.__use_delta || !(self_key in this.__delta);
150
- used_value = use_orig ? this[self_key] : this.__delta[self_key];
151
- }
152
- return is_fnc ? (0, _object.fn_eval_this)(this, used_value) : used_value;
153
- }
150
+ */
151
+ setDefaultValue(key, value) {
152
+ //@ts-ignore
153
+ if (this[key] == undefined || this[key] === "" || this[key] === 0) {
154
+ this[key] = value;
155
+ return true;
156
+ }
157
+ return false;
158
+ }
159
+ setDefault = this.setDefaultValue;
160
+ setDefaultPropertyNow(key) {
161
+ //@ts-ignore
162
+ if (this[key] == undefined || this[key] === "" || this[key] === 0) {
163
+ this[key] = new Date();
164
+ return true;
165
+ }
166
+ return false;
167
+ }
168
+ #setSubProperty(key, subkey, value) {
169
+ let subobj = this.get(key);
170
+ //@ts-ignore
171
+ if (subobj == null || typeof subobj !== "object")
172
+ subobj = {};
173
+ else
174
+ subobj = { ...subobj }; //make a clone so we dont update the original
175
+ subobj[subkey] = value;
176
+ this.#setProperty(key, subobj);
177
+ }
154
178
  /**
155
- * static get method for SimpleObject
156
- * @param obj
179
+ * update a property on this object by updating the `__delta`
180
+ * or update the object property directly depending on `__use_delta` setting
181
+ *
157
182
  * @param key
158
- * @param original
159
- * @returns
160
- */
161
- }, {
162
- key: "set",
163
- value: (
183
+ * @param value
184
+ */
185
+ #setProperty(key, value) {
186
+ let checkIsChanged = false;
187
+ if (this.__use_delta) {
188
+ if (this[key] === value) {
189
+ /**
190
+ * we set something back to its original value
191
+ * no need to save it as delta
192
+ */
193
+ delete this.__delta[key];
194
+ ////checkIsChanged = true; //check if we should set __has_delta to false
195
+ }
196
+ else {
197
+ this.__delta[key] = value; //always update delta to keep track of changes
198
+ }
199
+ }
200
+ else {
201
+ this[key] = value; //on noDelta mode update the object itself
202
+ this.__delta[key] = value; //always update delta to keep track of changes
203
+ }
204
+ return true;
205
+ }
164
206
  /**
165
207
  * set value and run the event handlers if needed
166
208
  * @param key
@@ -168,134 +210,108 @@ var SimpleObject = exports.SimpleObject = /*#__PURE__*/function (_MapableObject)
168
210
  * @param shouldNotify
169
211
  * @param autoApply if the field is not in delta, instantly calls the `apply` function to remove from delta
170
212
  * @returns
171
- */
172
- function () {
173
- var _set = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(key, value) {
174
- var shouldNotify,
175
- autoApply,
176
- isValueChanged,
177
- mkey,
178
- keyExists,
179
- keysp,
180
- subkey_part,
181
- subval,
182
- old_value,
183
- _this$manager,
184
- _args = arguments;
185
- return _regeneratorRuntime().wrap(function _callee$(_context) {
186
- while (1) switch (_context.prev = _context.next) {
187
- case 0:
188
- shouldNotify = _args.length > 2 && _args[2] !== undefined ? _args[2] : "auto";
189
- autoApply = _args.length > 3 && _args[3] !== undefined ? _args[3] : false;
190
- if (this.canModify) {
191
- _context.next = 8;
192
- break;
193
- }
194
- if (!(this.__throw_errors !== false)) {
195
- _context.next = 7;
196
- break;
197
- }
198
- throw Error("Cant use set(".concat(String(key), ") when on readonly mode"));
199
- case 7:
200
- return _context.abrupt("return", false);
201
- case 8:
202
- /* -------------------------------------------------------------------------- */
203
- keyExists = false;
204
- if (typeof key === "string" && key.includes(".")) {
205
- /* -------------------------------------------------------------------------- */
206
- /* set value of object */
207
- /* -------------------------------------------------------------------------- */
208
- keysp = key.split(".");
209
- mkey = keysp.shift();
210
- keyExists = mkey in this.__delta;
211
- subkey_part = keysp.shift(); //if accessing subval of an object, make sure the object is not null
212
- subval = _assertClassBrand(_SimpleObject_brand, this, _getSubProperty).call(this, mkey, subkey_part);
213
- isValueChanged = !(0, _object.object_equals)(subval, value, {
214
- ignoredStartingWords: "_",
215
- strictArrayCheck: true
216
- });
217
- if (isValueChanged) _assertClassBrand(_SimpleObject_brand, this, _setSubProperty).call(this, mkey, subkey_part, value);
218
- } else {
219
- /* -------------------------------------------------------------------------- */
220
- /* set basic value */
221
- /* -------------------------------------------------------------------------- */
222
- mkey = key;
223
- keyExists = mkey in this.__delta;
224
- old_value = this.get(mkey);
225
- isValueChanged = !(0, _object.object_equals)(old_value, value, {
226
- strictArrayCheck: true,
227
- ignoredStartingWords: "_"
228
- });
229
- if (isValueChanged) _assertClassBrand(_SimpleObject_brand, this, _setProperty).call(this, mkey, value);
230
- }
231
- if (autoApply && keyExists === false) {
232
- /**
233
- * if the field is not in delta
234
- * instantly calls the `apply` function to remove from delta
235
- */
236
- this.apply(mkey);
237
- if (shouldNotify === "auto") shouldNotify = false;
238
- }
239
- if (isValueChanged) {
240
- /**
241
- * notify the manager when the state of `__has_delta` is changed
242
- * managers can use this to detect if they need to save
243
- */
244
- (_this$manager = this.manager) === null || _this$manager === void 0 || _this$manager.checkIsChanged();
245
- }
246
- /* --------------------------------- notify --------------------------------- */
247
- if (!(shouldNotify === true || shouldNotify === "auto" && isValueChanged)) {
248
- _context.next = 15;
249
- break;
250
- }
251
- _context.next = 15;
252
- return this.notifyChanged("", key, value);
253
- case 15:
254
- return _context.abrupt("return", isValueChanged);
255
- case 16:
256
- case "end":
257
- return _context.stop();
258
- }
259
- }, _callee, this);
260
- }));
261
- function set(_x, _x2) {
262
- return _set.apply(this, arguments);
263
- }
264
- return set;
265
- }())
266
- }, {
267
- key: "setPreferApply",
268
- value: (
213
+ */
214
+ async set(key, value, shouldNotify = "auto", autoApply = false) {
215
+ /* -------------------- check if modification is allowed -------------------- */
216
+ if (!this.canModify) {
217
+ if (this.__throw_errors !== false)
218
+ throw Error(`Cant use set(${String(key)}) when on readonly mode`);
219
+ else
220
+ return false;
221
+ }
222
+ let isValueChanged, mkey, keyExists = false;
223
+ /* -------------------------------------------------------------------------- */
224
+ /* set all values from object */
225
+ /* -------------------------------------------------------------------------- */
226
+ if (typeof key === "object") {
227
+ let finalResult = true;
228
+ let changeablesOnly = Boolean(value);
229
+ value = key;
230
+ const checkKeys = changeablesOnly
231
+ ? array_intersection(this.__changeables, Object.keys(value))
232
+ : Object.keys(value);
233
+ for (let index = 0; index < checkKeys.length; index++) {
234
+ const key = checkKeys[index];
235
+ if (false ==
236
+ (await this.set(key, value[key], shouldNotify, autoApply)))
237
+ finalResult = false;
238
+ }
239
+ return finalResult;
240
+ }
241
+ if (typeof key === "string" && key.includes(".")) {
242
+ /* -------------------------------------------------------------------------- */
243
+ /* set value of object */
244
+ /* -------------------------------------------------------------------------- */
245
+ const keysp = key.split(".");
246
+ mkey = keysp.shift();
247
+ keyExists = mkey in this.__delta;
248
+ const subkey_part = keysp.shift();
249
+ //if accessing subval of an object, make sure the object is not null
250
+ const subval = this.#getSubProperty(mkey, subkey_part);
251
+ isValueChanged = !object_equals(subval, value, {
252
+ ignoredStartingWords: "_",
253
+ strictArrayCheck: true,
254
+ });
255
+ if (isValueChanged)
256
+ this.#setSubProperty(mkey, subkey_part, value);
257
+ }
258
+ else {
259
+ /* -------------------------------------------------------------------------- */
260
+ /* set basic value */
261
+ /* -------------------------------------------------------------------------- */
262
+ mkey = key;
263
+ keyExists = mkey in this.__delta;
264
+ const old_value = this.get(mkey);
265
+ isValueChanged = !object_equals(old_value, value, {
266
+ strictArrayCheck: true,
267
+ ignoredStartingWords: "_",
268
+ });
269
+ if (isValueChanged)
270
+ this.#setProperty(mkey, value);
271
+ }
272
+ if (autoApply && keyExists === false) {
273
+ /**
274
+ * if the field is not in delta
275
+ * instantly calls the `apply` function to remove from delta
276
+ */
277
+ this.apply(mkey);
278
+ if (shouldNotify === "auto")
279
+ shouldNotify = false;
280
+ }
281
+ if (isValueChanged) {
282
+ /**
283
+ * notify the manager when the state of `__has_delta` is changed
284
+ * managers can use this to detect if they need to save
285
+ */
286
+ this.manager?.checkIsChanged();
287
+ }
288
+ /* --------------------------------- notify --------------------------------- */
289
+ if (shouldNotify === true ||
290
+ (shouldNotify === "auto" && isValueChanged)) {
291
+ await this.notifyChanged("", key, value);
292
+ }
293
+ return isValueChanged;
294
+ }
295
+ /**
296
+ * @deprecated use `set`
297
+ * set value and run the event handlers if needed
298
+ * @return true if changed , false otherwise
299
+ */
300
+ setValue = this.set;
301
+ /**
302
+ * @deprecated use set function
303
+ */
304
+ setAll = this.set;
269
305
  /**
270
306
  * set value and run the event handlers if needed
271
307
  *
272
308
  * if the field is not in delta instantly calls the `apply` function to remove from delta
273
309
  * @param key
274
310
  * @param value
275
- */
276
- function () {
277
- var _setPreferApply = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(key, value) {
278
- var shouldNotify,
279
- _args2 = arguments;
280
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
281
- while (1) switch (_context2.prev = _context2.next) {
282
- case 0:
283
- shouldNotify = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : "auto";
284
- _context2.next = 3;
285
- return this.set(key, value, shouldNotify, true);
286
- case 3:
287
- return _context2.abrupt("return", _context2.sent);
288
- case 4:
289
- case "end":
290
- return _context2.stop();
291
- }
292
- }, _callee2, this);
293
- }));
294
- function setPreferApply(_x3, _x4) {
295
- return _setPreferApply.apply(this, arguments);
296
- }
297
- return setPreferApply;
298
- }()
311
+ */
312
+ async setPreferApply(key, value, shouldNotify = "auto") {
313
+ return await this.set(key, value, shouldNotify, true);
314
+ }
299
315
  /**
300
316
  * set key of subObject
301
317
  * @param key
@@ -303,375 +319,131 @@ var SimpleObject = exports.SimpleObject = /*#__PURE__*/function (_MapableObject)
303
319
  * @param subvalue
304
320
  * @param sendChanges
305
321
  * @return true if changed , false otherwise
306
- */
307
- )
308
- }, {
309
- key: "setSubValue",
310
- value: (function () {
311
- var _setSubValue = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(key, objKey, subvalue) {
312
- var sendChanges,
313
- _args3 = arguments;
314
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
315
- while (1) switch (_context3.prev = _context3.next) {
316
- case 0:
317
- sendChanges = _args3.length > 3 && _args3[3] !== undefined ? _args3[3] : "auto";
318
- _context3.next = 3;
319
- return this.set("".concat(String(key), ".").concat(objKey), subvalue, sendChanges);
320
- case 3:
321
- return _context3.abrupt("return", _context3.sent);
322
- case 4:
323
- case "end":
324
- return _context3.stop();
325
- }
326
- }, _callee3, this);
327
- }));
328
- function setSubValue(_x5, _x6, _x7) {
329
- return _setSubValue.apply(this, arguments);
330
- }
331
- return setSubValue;
332
- }()
333
- /* -------------------------------------------------------------------------- */
334
- /* Load */
335
- /* -------------------------------------------------------------------------- */
336
- )
337
- }, {
338
- key: "setTemp",
339
- value: (function () {
340
- var _setTemp = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(key, value) {
341
- var sendChanges,
342
- isValueChanged,
343
- _args4 = arguments;
344
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
345
- while (1) switch (_context4.prev = _context4.next) {
346
- case 0:
347
- sendChanges = _args4.length > 2 && _args4[2] !== undefined ? _args4[2] : false;
348
- _context4.next = 3;
349
- return _superPropGet(SimpleObject, "setTemp", this, 3)([key, value]);
350
- case 3:
351
- isValueChanged = _context4.sent;
352
- if (!(sendChanges === true || sendChanges === "auto" && isValueChanged)) {
353
- _context4.next = 7;
354
- break;
355
- }
356
- _context4.next = 7;
357
- return this.notifyChanged("temp", key, value);
358
- case 7:
359
- return _context4.abrupt("return", isValueChanged);
360
- case 8:
361
- case "end":
362
- return _context4.stop();
363
- }
364
- }, _callee4, this);
365
- }));
366
- function setTemp(_x8, _x9) {
367
- return _setTemp.apply(this, arguments);
368
- }
369
- return setTemp;
370
- }()
371
- /* -------------------------------------------------------------------------- */
372
- /**
373
- * load all properties in `initObject` into the current object
374
- * @param initObject
375
- * @param fullUpdate
376
- * @returns
377
- */
378
- )
379
- }, {
380
- key: "loadValues",
381
- value: function loadValues(initObject) {
382
- var fullUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
383
- return SimpleObject.loadValues(this, initObject, fullUpdate);
384
- }
385
- }, {
386
- key: "clearRefreshFunction",
387
- value: (/* ---------------------------- refresh functions --------------------------- */function () {
388
- var _clearRefreshFunction = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
389
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
390
- while (1) switch (_context5.prev = _context5.next) {
391
- case 0:
392
- this.__refresh_functions = undefined;
393
- case 1:
394
- case "end":
395
- return _context5.stop();
396
- }
397
- }, _callee5, this);
398
- }));
399
- function clearRefreshFunction() {
400
- return _clearRefreshFunction.apply(this, arguments);
401
- }
402
- return clearRefreshFunction;
403
- }())
404
- }, {
405
- key: "setRefreshFunction",
406
- value: function () {
407
- var _setRefreshFunction = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(new_fnc) {
408
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
409
- while (1) switch (_context6.prev = _context6.next) {
410
- case 0:
411
- _context6.next = 2;
412
- return this.addRefreshFunction(new_fnc);
413
- case 2:
414
- return _context6.abrupt("return", _context6.sent);
415
- case 3:
416
- case "end":
417
- return _context6.stop();
418
- }
419
- }, _callee6, this);
420
- }));
421
- function setRefreshFunction(_x10) {
422
- return _setRefreshFunction.apply(this, arguments);
423
- }
424
- return setRefreshFunction;
425
- }()
426
- }, {
427
- key: "addRefreshFunction",
428
- value: function () {
429
- var _addRefreshFunction = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(key, new_fnc) {
430
- var oldFunctions;
431
- return _regeneratorRuntime().wrap(function _callee7$(_context7) {
432
- while (1) switch (_context7.prev = _context7.next) {
433
- case 0:
434
- if (typeof key === "function") {
435
- new_fnc = key;
436
- key = "main";
437
- }
438
- key = key || "main";
439
- oldFunctions = this.__refresh_functions;
440
- if (oldFunctions == null || _typeof(oldFunctions) !== "object") oldFunctions = {};
441
- oldFunctions[key] = new_fnc;
442
- this.__refresh_functions = oldFunctions;
443
- case 6:
444
- case "end":
445
- return _context7.stop();
446
- }
447
- }, _callee7, this);
448
- }));
449
- function addRefreshFunction(_x11, _x12) {
450
- return _addRefreshFunction.apply(this, arguments);
451
- }
452
- return addRefreshFunction;
453
- }()
454
- }, {
455
- key: "runRefreshFunction",
456
- value: function () {
457
- var _runRefreshFunction = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8() {
458
- var oldFunctions,
459
- fncArray,
460
- _len,
461
- params,
462
- _key,
463
- index,
464
- fnc,
465
- _args8 = arguments;
466
- return _regeneratorRuntime().wrap(function _callee8$(_context8) {
467
- while (1) switch (_context8.prev = _context8.next) {
468
- case 0:
469
- oldFunctions = this.__refresh_functions;
470
- if (!(oldFunctions == null || _typeof(oldFunctions) !== "object")) {
471
- _context8.next = 3;
472
- break;
473
- }
474
- return _context8.abrupt("return");
475
- case 3:
476
- fncArray = Object.values(oldFunctions);
477
- for (_len = _args8.length, params = new Array(_len), _key = 0; _key < _len; _key++) {
478
- params[_key] = _args8[_key];
479
- }
480
- index = 0;
481
- case 6:
482
- if (!(index < fncArray.length)) {
483
- _context8.next = 13;
484
- break;
485
- }
486
- fnc = fncArray[index];
487
- _context8.next = 10;
488
- return _object.fn_eval.apply(void 0, [fnc].concat(params));
489
- case 10:
490
- index++;
491
- _context8.next = 6;
492
- break;
493
- case 13:
494
- case "end":
495
- return _context8.stop();
496
- }
497
- }, _callee8, this);
498
- }));
499
- function runRefreshFunction() {
500
- return _runRefreshFunction.apply(this, arguments);
501
- }
502
- return runRefreshFunction;
503
- }()
504
- /* -------------------------------------------------------------------------- */
505
- /**
506
- * calls `set` function for all props of `setObj`
507
- * @param setObj
508
- * @param changeablesOnly only updates the `__changeables` fields
509
- * @returns
510
- */
511
- }, {
512
- key: "setAll",
513
- value: (function () {
514
- var _setAll = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(setObj) {
515
- var changeablesOnly,
516
- finalRes,
517
- checkKeys,
518
- index,
519
- key,
520
- _args9 = arguments;
521
- return _regeneratorRuntime().wrap(function _callee9$(_context9) {
522
- while (1) switch (_context9.prev = _context9.next) {
523
- case 0:
524
- changeablesOnly = _args9.length > 1 && _args9[1] !== undefined ? _args9[1] : true;
525
- finalRes = true;
526
- checkKeys = changeablesOnly ? (0, _object.array_intersection)(this.__changeables, Object.keys(setObj)) : Object.keys(setObj);
527
- index = 0;
528
- case 4:
529
- if (!(index < checkKeys.length)) {
530
- _context9.next = 13;
531
- break;
532
- }
533
- key = checkKeys[index];
534
- _context9.next = 8;
535
- return this.set(key, setObj[key]);
536
- case 8:
537
- if (_context9.sent) {
538
- _context9.next = 10;
539
- break;
540
- }
541
- finalRes = false;
542
- case 10:
543
- index++;
544
- _context9.next = 4;
545
- break;
546
- case 13:
547
- return _context9.abrupt("return", finalRes);
548
- case 14:
549
- case "end":
550
- return _context9.stop();
551
- }
552
- }, _callee9, this);
553
- }));
554
- function setAll(_x13) {
555
- return _setAll.apply(this, arguments);
556
- }
557
- return setAll;
558
- }()
559
- /**
560
- * set value of a key only if the value is empty (null,undef,"")
561
- * @param key
562
- * @param value
563
- * @returns
564
- */
565
- )
566
- }, {
567
- key: "setDefaultValue",
568
- value: function setDefaultValue(key, value) {
569
- return _assertClassBrand(_SimpleObject_brand, this, _setDefaultProperty).call(this, key, value);
570
- }
571
- }, {
572
- key: "pushValue",
573
- value: (
322
+ */
323
+ async setSubValue(key, objKey, subvalue, sendChanges = "auto") {
324
+ return await this.set(`${String(key)}.${objKey}`, subvalue, sendChanges);
325
+ }
326
+ async setTemp(key, value, sendChanges = false) {
327
+ let isValueChanged = await super.setTemp(key, value);
328
+ if (sendChanges === true ||
329
+ (sendChanges === "auto" && isValueChanged)) {
330
+ await this.notifyChanged("temp", key, value);
331
+ }
332
+ return isValueChanged;
333
+ }
574
334
  /**
575
335
  * Push a single value to array property
576
336
  * @param key
577
337
  * @param value
578
338
  * @param sendChanges
579
339
  * @returns
580
- */
581
- function () {
582
- var _pushValue = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(key, value) {
583
- var sendChanges,
584
- _args10 = arguments;
585
- return _regeneratorRuntime().wrap(function _callee10$(_context10) {
586
- while (1) switch (_context10.prev = _context10.next) {
587
- case 0:
588
- sendChanges = _args10.length > 2 && _args10[2] !== undefined ? _args10[2] : "auto";
589
- _context10.next = 3;
590
- return this.pushValues(key, [value], sendChanges);
591
- case 3:
592
- return _context10.abrupt("return", _context10.sent);
593
- case 4:
594
- case "end":
595
- return _context10.stop();
596
- }
597
- }, _callee10, this);
598
- }));
599
- function pushValue(_x14, _x15) {
600
- return _pushValue.apply(this, arguments);
601
- }
602
- return pushValue;
603
- }()
340
+ */
341
+ async pushValue(key, value, sendChanges = "auto") {
342
+ return await this.pushValues(key, [value], sendChanges);
343
+ }
604
344
  /**
605
345
  * Push a list of values to array property
606
346
  * @param key
607
347
  * @param values
608
348
  * @param sendChanges
609
349
  * @returns
610
- */
611
- )
612
- }, {
613
- key: "pushValues",
614
- value: (function () {
615
- var _pushValues = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(key, values) {
616
- var sendChanges,
617
- tempArray,
618
- _args11 = arguments;
619
- return _regeneratorRuntime().wrap(function _callee11$(_context11) {
620
- while (1) switch (_context11.prev = _context11.next) {
621
- case 0:
622
- sendChanges = _args11.length > 2 && _args11[2] !== undefined ? _args11[2] : "auto";
623
- if (!(0, _object.array_isEmpty)(values)) {
624
- _context11.next = 3;
625
- break;
626
- }
627
- return _context11.abrupt("return", false);
628
- case 3:
629
- if (this.canModify) {
630
- _context11.next = 9;
631
- break;
632
- }
633
- if (!(this.__throw_errors !== false)) {
634
- _context11.next = 8;
635
- break;
636
- }
637
- throw Error("Cant use pushValues (".concat(String(key), ") when on readonly mode"));
638
- case 8:
639
- return _context11.abrupt("return", false);
640
- case 9:
641
- if (this.get(key) == null) _assertClassBrand(_SimpleObject_brand, this, _setProperty).call(this, key, []);
642
- tempArray = this.get(key);
643
- if (Array.isArray(tempArray)) {
644
- _context11.next = 17;
645
- break;
646
- }
647
- if (!(this.__throw_errors !== false)) {
648
- _context11.next = 16;
649
- break;
650
- }
651
- throw Error("Cant use pushValues (".concat(String(key), ") on non Array keys"));
652
- case 16:
653
- return _context11.abrupt("return", false);
654
- case 17:
655
- _assertClassBrand(_SimpleObject_brand, this, _setProperty).call(this, key, (0, _object.array_merge)(tempArray, values));
656
- if (!(sendChanges === true || sendChanges === "auto")) {
657
- _context11.next = 21;
658
- break;
659
- }
660
- _context11.next = 21;
661
- return this.notifyChanged("", key, values);
662
- case 21:
663
- return _context11.abrupt("return", tempArray);
664
- case 22:
665
- case "end":
666
- return _context11.stop();
667
- }
668
- }, _callee11, this);
669
- }));
670
- function pushValues(_x16, _x17) {
671
- return _pushValues.apply(this, arguments);
672
- }
673
- return pushValues;
674
- }()
350
+ */
351
+ async pushValues(key, values, sendChanges = "auto") {
352
+ if (array_isEmpty(values))
353
+ return false;
354
+ if (!this.canModify) {
355
+ if (this.__throw_errors !== false)
356
+ throw Error(`Cant use pushValues (${String(key)}) when on readonly mode`);
357
+ else
358
+ return false;
359
+ }
360
+ if (this.get(key) == null)
361
+ this.#setProperty(key, []);
362
+ let tempArray = this.get(key);
363
+ if (!Array.isArray(tempArray)) {
364
+ if (this.__throw_errors !== false)
365
+ throw Error(`Cant use pushValues (${String(key)}) on non Array keys`);
366
+ else
367
+ return false;
368
+ }
369
+ this.#setProperty(key, array_merge(tempArray, values));
370
+ if (sendChanges === true || sendChanges === "auto")
371
+ await this.notifyChanged("", key, values);
372
+ return tempArray;
373
+ }
374
+ /* -------------------------------------------------------------------------- */
375
+ /* Load */
376
+ /* -------------------------------------------------------------------------- */
377
+ /**
378
+ * load all properties in `initObject` into the current object
379
+ * @param initObject
380
+ * @param fullUpdate
381
+ * @returns
382
+ */
383
+ loadValues(initObject, fullUpdate = false) {
384
+ return SimpleObject.loadValues(this, initObject, fullUpdate);
385
+ }
386
+ static loadValues(obj, initObject, fullUpdate = false) {
387
+ if (typeof initObject === "number" || typeof initObject === "string") {
388
+ initObject = { _id: initObject };
389
+ }
390
+ SimpleObject.factoryClear(obj);
391
+ if (initObject == null) {
392
+ for (const key in obj) {
393
+ if (typeof obj[key] === "function")
394
+ continue;
395
+ if (key.startsWith("__"))
396
+ continue;
397
+ delete obj[key];
398
+ }
399
+ }
400
+ else if (typeof initObject == "object") {
401
+ for (const key in initObject) {
402
+ if (key.startsWith("__"))
403
+ continue;
404
+ if (fullUpdate ||
405
+ Object.prototype.hasOwnProperty.call(obj, key)) {
406
+ obj[key] = initObject[key];
407
+ }
408
+ }
409
+ /* --------------------- special case 1, temp properties -------------------- */
410
+ if ("__temp" in initObject) {
411
+ obj["__temp"] = initObject["__temp"];
412
+ }
413
+ }
414
+ return true;
415
+ }
416
+ /* -------------------------------------------------------------------------- */
417
+ /* Refresh Functions */
418
+ /* -------------------------------------------------------------------------- */
419
+ async clearRefreshFunction() {
420
+ this.__refresh_functions = undefined;
421
+ }
422
+ async setRefreshFunction(new_fnc) {
423
+ return await this.addRefreshFunction(new_fnc);
424
+ }
425
+ async addRefreshFunction(key, new_fnc) {
426
+ if (typeof key === "function") {
427
+ new_fnc = key;
428
+ key = "main";
429
+ }
430
+ key = key || "main";
431
+ let oldFunctions = this.__refresh_functions;
432
+ if (oldFunctions == null || typeof oldFunctions !== "object")
433
+ oldFunctions = {};
434
+ oldFunctions[key] = new_fnc;
435
+ this.__refresh_functions = oldFunctions;
436
+ }
437
+ async runRefreshFunction(...params) {
438
+ let oldFunctions = this.__refresh_functions;
439
+ if (oldFunctions == null || typeof oldFunctions !== "object")
440
+ return;
441
+ const fncArray = Object.values(oldFunctions);
442
+ for (let index = 0; index < fncArray.length; index++) {
443
+ const fnc = fncArray[index];
444
+ await fn_eval(fnc, ...params);
445
+ }
446
+ }
675
447
  /**
676
448
  *
677
449
  * @param type
@@ -679,1073 +451,693 @@ var SimpleObject = exports.SimpleObject = /*#__PURE__*/function (_MapableObject)
679
451
  * @param value
680
452
  * @param subvalue
681
453
  * @returns true if manager was notified. false otherwise
682
- */
683
- )
684
- }, {
685
- key: "notifyChanged",
686
- value: (function () {
687
- var _notifyChanged = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12(type, key, value, subvalue) {
688
- var lc, manager_class;
689
- return _regeneratorRuntime().wrap(function _callee12$(_context12) {
690
- while (1) switch (_context12.prev = _context12.next) {
691
- case 0:
692
- if (value === undefined && type == "") value = this.get(key);
693
- lc = "";
694
- if (type) lc += "$".concat(String(type), "$");
695
- if (subvalue) {
696
- lc += "".concat(String(key), ".").concat(value);
697
- } else {
698
- lc += "".concat(String(key));
699
- }
700
- this.__lastChanged = lc;
701
- /* --------------------------- notify the manager --------------------------- */
702
- manager_class = this.manager;
703
- if (!(typeof (manager_class === null || manager_class === void 0 ? void 0 : manager_class.notifyChanged) === "function")) {
704
- _context12.next = 10;
705
- break;
706
- }
707
- _context12.next = 9;
708
- return manager_class.notifyChanged(type, key, value, subvalue);
709
- case 9:
710
- return _context12.abrupt("return", _context12.sent);
711
- case 10:
712
- return _context12.abrupt("return", false);
713
- case 11:
714
- case "end":
715
- return _context12.stop();
716
- }
717
- }, _callee12, this);
718
- }));
719
- function notifyChanged(_x18, _x19, _x20, _x21) {
720
- return _notifyChanged.apply(this, arguments);
721
- }
722
- return notifyChanged;
723
- }()
454
+ */
455
+ async notifyChanged(type, key, value, subvalue) {
456
+ if (value === undefined && type == "")
457
+ value = this.get(key);
458
+ let lc = "";
459
+ if (type)
460
+ lc += `$${String(type)}$`;
461
+ if (subvalue) {
462
+ lc += `${String(key)}.${value}`;
463
+ }
464
+ else {
465
+ lc += `${String(key)}`;
466
+ }
467
+ this.__lastChanged = lc;
468
+ /* --------------------------- notify the manager --------------------------- */
469
+ const manager_class = this.manager;
470
+ if (typeof manager_class?.notifyChanged === "function") {
471
+ return await manager_class.notifyChanged(type, key, value, subvalue);
472
+ }
473
+ return false;
474
+ }
724
475
  /**
725
476
  * get a list of all keys that can be changed in given objcet
726
477
  * @param object
727
478
  * @param options
728
479
  * @returns
729
- */
730
- )
731
- }, {
732
- key: "apply_changes",
733
- value: /* -------------------------------------------------------------------------- */
734
- /* Changes */
735
- /* -------------------------------------------------------------------------- */
480
+ */
481
+ static getChangeableKeys(object, options) {
482
+ if (!object)
483
+ return [];
484
+ let key_list = [];
485
+ key_list.push(...object.constructor["__changeables"]);
486
+ const __unchangeables = object.constructor["__unchangeables"];
487
+ if (!array_isEmpty(__unchangeables)) {
488
+ key_list = key_list.filter((s) => !__unchangeables.includes(s));
489
+ }
490
+ /* -------------------------------------------------------------------------- */
491
+ if (options.extraProperties) {
492
+ key_list.push(...object.constructor["__extraProperties"]);
493
+ }
494
+ if (options.tempProperties) {
495
+ key_list.push("__temp");
496
+ key_list.push(...object.constructor["__tempProperties"]);
497
+ }
498
+ if (options.bypassProtected !== true && !options.allProperties) {
499
+ const __protectedProperties = object.constructor["__protectedProperties"];
500
+ //protected keys can only be changed by the creator of this object
501
+ //make sure you set the is_current_user function correctly
502
+ if (!object.isNew &&
503
+ !array_isEmpty(__protectedProperties) &&
504
+ !Boolean(gfunc.run_action_sync("is_current_user", object.get("_creator")))) {
505
+ key_list = key_list.filter((s) => !__protectedProperties.includes(s));
506
+ }
507
+ }
508
+ return key_list;
509
+ }
510
+ /**
511
+ * check if a key can be changed on an object
512
+ * @param object the object we are checking
513
+ * @param key key of the object
514
+ * @param useExtraProps should we check extra props?
515
+ * @returns
516
+ */
517
+ static canChangeKey(object, key, options) {
518
+ if (!object || !key)
519
+ return false;
520
+ const keys = this.getChangeableKeys(object, options);
521
+ return keys.includes(key);
522
+ }
523
+ static hasIllegalChanges(referenceObject, changesObject, updaterUser) {
524
+ const __protectedProperties = object_getStatic(referenceObject, "__protectedProperties");
525
+ if (object_isEmpty(__protectedProperties))
526
+ return false;
527
+ const referenceUser = object_isClass(referenceObject)
528
+ ? object_get(changesObject, "__user", "_creator")
529
+ : object_get(referenceObject, "__user", "_creator");
530
+ if (Boolean(SimpleObject.getID(referenceUser) ==
531
+ SimpleObject.getID(updaterUser))) {
532
+ return false;
533
+ }
534
+ for (const key in changesObject) {
535
+ if (__protectedProperties.includes(key)) {
536
+ return true;
537
+ }
538
+ }
539
+ return false;
540
+ }
541
+ /* -------------------------------------------------------------------------- */
542
+ /* Changes */
543
+ /* -------------------------------------------------------------------------- */
736
544
  /**
737
545
  * Apply all the changes and empty the delta object
738
- */
739
- function apply_changes() {
740
- try {
741
- if (!this.__use_delta) {
742
- //in this mode , we track changes by updating the original product
743
- this.setOriginal();
744
- return true;
745
- }
746
- if (!this.isChanged) {
747
- console.warn("No changes to apply");
748
- return false;
749
- }
750
- for (var key in this.__delta) {
751
- var nv = this.__delta[key];
752
- this[key] = nv;
753
- }
754
- return true;
755
- } finally {
756
- this.clear_changes();
757
- }
758
- }
546
+ */
547
+ apply_changes() {
548
+ try {
549
+ if (!this.__use_delta) {
550
+ /**
551
+ * in this mode , we track changes by updating the original product
552
+ */
553
+ this.setOriginal();
554
+ return true;
555
+ }
556
+ if (!this.isChanged) {
557
+ console.warn("No changes to apply");
558
+ return false;
559
+ }
560
+ for (const key in this.__delta) {
561
+ const nv = this.__delta[key];
562
+ this[key] = nv;
563
+ }
564
+ return true;
565
+ }
566
+ finally {
567
+ this.clear_changes();
568
+ }
569
+ }
759
570
  /**
760
571
  * apply changes for the given fields
761
572
  * @param key
762
573
  * @returns
763
- */
764
- }, {
765
- key: "apply",
766
- value: function apply(keylist) {
767
- var _this2 = this;
768
- (0, _object.wrap_array)(keylist).forEach(function (key) {
769
- try {
770
- if (!_this2.__use_delta) {
771
- //in this mode , we track changes by updating the original
772
- return true;
773
- }
774
- if (_this2.__delta != null && key in _this2.__delta) {
775
- _this2[key] = _this2.__delta[key];
776
- delete _this2.__delta[key];
777
- }
778
- return true;
779
- } finally {}
780
- });
781
- return true;
782
- }
574
+ */
575
+ apply(keylist) {
576
+ if (!this.__use_delta) {
577
+ /**
578
+ * in this mode , we track changes by updating the original
579
+ */
580
+ return true;
581
+ }
582
+ if (this.__delta == null || Object.keys(this.__delta).length == 0) {
583
+ /**
584
+ * nothing to apply
585
+ */
586
+ return true;
587
+ }
588
+ keylist = wrap_array(keylist);
589
+ if (keylist.length == 0) {
590
+ /**
591
+ * nothing to apply
592
+ */
593
+ return true;
594
+ }
595
+ for (const key of keylist) {
596
+ if (key in this.__delta) {
597
+ this[key] = this.__delta[key];
598
+ delete this.__delta[key];
599
+ }
600
+ }
601
+ return true;
602
+ }
783
603
  /**
784
604
  * set the value to its original
785
605
  * @param key
786
- */
787
- }, {
788
- key: "discard",
789
- value: (function () {
790
- var _discard = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee13(key) {
791
- var shouldNotify,
792
- originalValue,
793
- _args13 = arguments;
794
- return _regeneratorRuntime().wrap(function _callee13$(_context13) {
795
- while (1) switch (_context13.prev = _context13.next) {
796
- case 0:
797
- shouldNotify = _args13.length > 1 && _args13[1] !== undefined ? _args13[1] : "auto";
798
- if (this.__use_delta) {
799
- originalValue = this[key];
800
- } else if (this.__originalobject) originalValue = this.__originalobject[key];else originalValue = this[key];
801
- _context13.next = 4;
802
- return this.set(key, originalValue, shouldNotify);
803
- case 4:
804
- return _context13.abrupt("return", _context13.sent);
805
- case 5:
806
- case "end":
807
- return _context13.stop();
808
- }
809
- }, _callee13, this);
810
- }));
811
- function discard(_x22) {
812
- return _discard.apply(this, arguments);
813
- }
814
- return discard;
815
- }()
606
+ */
607
+ async discard(key, shouldNotify = "auto") {
608
+ let originalValue;
609
+ if (this.__use_delta) {
610
+ originalValue = this[key];
611
+ }
612
+ else if (this.__originalobject)
613
+ originalValue = this.__originalobject[key];
614
+ else
615
+ originalValue = this[key];
616
+ return await this.set(key, originalValue, shouldNotify);
617
+ }
816
618
  /**
817
619
  * reset all values back to their original
818
620
  *
819
621
  * this function also calls `on_change` and then `clear_changes`
820
622
  * @param key
821
- */
822
- )
823
- }, {
824
- key: "discardAll",
825
- value: (function () {
826
- var _discardAll = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee14() {
827
- var shouldNotify,
828
- final_result,
829
- key,
830
- _args14 = arguments;
831
- return _regeneratorRuntime().wrap(function _callee14$(_context14) {
832
- while (1) switch (_context14.prev = _context14.next) {
833
- case 0:
834
- shouldNotify = _args14.length > 0 && _args14[0] !== undefined ? _args14[0] : "auto";
835
- final_result = true;
836
- _context14.t0 = _regeneratorRuntime().keys(this.__delta);
837
- case 3:
838
- if ((_context14.t1 = _context14.t0()).done) {
839
- _context14.next = 13;
840
- break;
841
- }
842
- key = _context14.t1.value;
843
- _context14.t2 = final_result;
844
- if (!_context14.t2) {
845
- _context14.next = 10;
846
- break;
847
- }
848
- _context14.next = 9;
849
- return this.discard(key, shouldNotify);
850
- case 9:
851
- _context14.t2 = _context14.sent;
852
- case 10:
853
- final_result = _context14.t2;
854
- _context14.next = 3;
855
- break;
856
- case 13:
857
- if (final_result) this.clear_changes();
858
- return _context14.abrupt("return", final_result);
859
- case 15:
860
- case "end":
861
- return _context14.stop();
862
- }
863
- }, _callee14, this);
864
- }));
865
- function discardAll() {
866
- return _discardAll.apply(this, arguments);
867
- }
868
- return discardAll;
869
- }()
623
+ */
624
+ async discardAll(shouldNotify = "auto") {
625
+ let final_result = true;
626
+ for (const key in this.__delta) {
627
+ final_result =
628
+ final_result && (await this.discard(key, shouldNotify));
629
+ }
630
+ if (final_result)
631
+ this.clear_changes();
632
+ return final_result;
633
+ }
870
634
  /**
871
635
  * clear and discard all changes
872
636
  *
873
637
  * does not call `on_change` functions
874
638
  * @returns
875
- */
876
- )
877
- }, {
878
- key: "clear_changes",
879
- value: function clear_changes() {
880
- this.__delta = {};
881
- ////this.__has_delta = false;
882
- return true;
883
- }
884
- /**
885
- * clear and discard all temp values
886
- * @returns
887
- */
888
- }, {
889
- key: "clear_cache",
890
- value: function clear_cache() {
891
- delete this.__temp;
892
- return true;
893
- }
639
+ */
640
+ clear_changes() {
641
+ this.__delta = {};
642
+ ////this.__has_delta = false;
643
+ return true;
644
+ }
894
645
  /**
895
646
  * Sets readonly property on given objects
896
647
  * @param objs array of given objects or a single object
897
648
  * @param readonlyval readonly
898
649
  * @param clearChanges should we clean the changes after setting readonly
899
- */
900
- }, {
901
- key: "__object_name",
902
- get: /* -------------------------------------------------------------------------- */
903
- /* Get/Check */
904
- /* -------------------------------------------------------------------------- */
905
- function get() {
906
- return this.constructor["__object_name"] || this.__db_name;
907
- }
908
- }, {
909
- key: "__db_name",
910
- get: function get() {
911
- return this.constructor["__db_name"] || this.constructor["__web_path"];
912
- }
913
- }, {
914
- key: "isChanged",
915
- get: function get() {
916
- var _this3 = this;
917
- ////const deltaIsBlank = object_isEmpty(this.__delta);
918
- ////if (!deltaIsBlank) return true; //delta is not blank, definitely changed
919
- ////if (this.__use_delta) return !deltaIsBlank; //trust the delta.
920
- if (this.__use_delta) {
921
- ////return this.__has_delta;
922
- for (var key in this.__delta) {
923
- return true;
924
- }
925
- return false;
926
- }
927
- /* --------------------- check the properties one by one -------------------- */
928
- var orig = this.getOriginal();
929
- if (!orig) return false; //we dont know if anything has changed
930
- /**
931
- * if object is not using delta mode,
932
- * check changes by comparing changeable fields with original object
933
- */
934
- if (Array.isArray(this.__changeables)) {
935
- return this.__changeables.find(function (c) {
936
- return !(0, _object.object_equals)(_this3[c], orig[c]);
937
- }) != undefined;
938
- } else {
939
- /* check all fields */
940
- for (var _key2 in this) {
941
- if (_key2.startsWith("__")) continue;
942
- if (!(0, _object.object_equals)(this[_key2], orig[_key2])) return true;
943
- }
944
- return false;
945
- }
946
- }
947
- }, {
948
- key: "isArchived",
949
- get: function get() {
950
- return this._archived || false;
951
- },
952
- set: function set(v) {
953
- this._archived = v;
954
- }
955
- }, {
956
- key: "isDeleted",
957
- get: function get() {
958
- return this.get("_deleted") || false;
959
- },
960
- set: function set(v) {
961
- this._deleted = v;
962
- }
963
- }, {
964
- key: "isLocked",
965
- get: function get() {
966
- return this.get("_locked") || false;
967
- },
968
- set: function set(v) {
969
- this._locked = v;
970
- }
971
- }, {
972
- key: "objectColor",
973
- get: function get() {
974
- if (!_classPrivateFieldGet(_objectColor, this)) {
975
- var lastid = this.getID();
976
- if (lastid) _classPrivateFieldSet(_objectColor, this, (0, _string.string_to_color)(lastid));
977
- }
978
- return _classPrivateFieldGet(_objectColor, this) || "#000000";
979
- }
980
- }, {
981
- key: "d",
982
- get: function get() {
983
- return this.__use_delta ? this.__delta : this;
984
- }
985
- /* all updated properties */
986
- }, {
987
- key: "allproperties",
988
- get: function get() {
989
- var result = _objectSpread(_objectSpread({}, this), this.__delta);
990
- result.__delta = {};
991
- return result;
992
- }
993
- }, {
994
- key: "canModify",
995
- get: function get() {
996
- return !Boolean(this.__is_readonly);
997
- }
998
- }, {
999
- key: "__changeables",
1000
- get: function get() {
1001
- return this.constructor["__changeables"];
1002
- }
1003
- }, {
1004
- key: "__unchangeables",
1005
- get: function get() {
1006
- return this.constructor["__unchangeables"];
1007
- }
1008
- }, {
1009
- key: "__use_delta",
1010
- get: function get() {
1011
- return this.constructor["__use_delta"];
1012
- }
1013
- }, {
1014
- key: "isSaved",
1015
- get: function get() {
1016
- var _this$__saveResultIsS;
1017
- return Boolean((_this$__saveResultIsS = this.__saveResultIsSuccess) !== null && _this$__saveResultIsS !== void 0 ? _this$__saveResultIsS : false);
1018
- }
1019
- }, {
1020
- key: "isNew",
1021
- get: function get() {
1022
- var mid = this.getID();
1023
- if (!mid) return true;
1024
- if (typeof mid === "string") return mid === "" || mid === "-1";
1025
- if (typeof mid === "number") return mid === -1;
1026
- return false;
1027
- }
1028
- }, {
1029
- key: "lastChanged",
1030
- get: function get() {
1031
- return this.__lastChanged || "";
1032
- }
1033
- }, {
1034
- key: "manager",
1035
- get: function get() {
1036
- return this.get_managerClass() || undefined;
1037
- }
1038
- }, {
1039
- key: "set_managerClass",
1040
- value:
650
+ */
651
+ static setReadonly(objs, readonlyval = true, clearChanges = false) {
652
+ let checkObjs = [];
653
+ if (!objs)
654
+ objs = [];
655
+ if (!Array.isArray(objs))
656
+ checkObjs = [objs];
657
+ else
658
+ checkObjs = objs;
659
+ for (let index = 0; index < checkObjs.length; index++) {
660
+ const obj = checkObjs[index];
661
+ obj.__is_readonly = Boolean(readonlyval);
662
+ if (obj instanceof SimpleObject) {
663
+ if (obj.canModify) {
664
+ if (!obj.getOriginal())
665
+ obj.setOriginal();
666
+ }
667
+ else {
668
+ if (clearChanges)
669
+ obj.clear_changes();
670
+ //we dont need the original object in readonly mode
671
+ obj.setOriginal(null);
672
+ }
673
+ }
674
+ }
675
+ }
676
+ static setThrowErrors(objs, throwErr = true) {
677
+ let checkObjs = [];
678
+ if (!objs)
679
+ objs = [];
680
+ if (!Array.isArray(objs))
681
+ checkObjs = [objs];
682
+ else
683
+ checkObjs = objs;
684
+ for (let index = 0; index < checkObjs.length; index++) {
685
+ const element = checkObjs[index];
686
+ element.__throw_errors = throwErr;
687
+ }
688
+ }
689
+ /* -------------------------------------------------------------------------- */
690
+ /* Get/Check */
691
+ /* -------------------------------------------------------------------------- */
692
+ get __object_name() {
693
+ return this.constructor["__object_name"] || this.__db_name;
694
+ }
695
+ get __db_name() {
696
+ return this.constructor["__db_name"] || this.constructor["__web_path"];
697
+ }
698
+ get isChanged() {
699
+ ////const deltaIsBlank = object_isEmpty(this.__delta);
700
+ ////if (!deltaIsBlank) return true; //delta is not blank, definitely changed
701
+ ////if (this.__use_delta) return !deltaIsBlank; //trust the delta.
702
+ if (this.__use_delta) {
703
+ ////return this.__has_delta;
704
+ /**
705
+ * if there is any key in delta, then the object is changed
706
+ */
707
+ for (const key in this.__delta)
708
+ return true;
709
+ return false;
710
+ }
711
+ /* --------------------- check the properties one by one -------------------- */
712
+ const orig = this.getOriginal();
713
+ if (!orig)
714
+ return false; //we dont know if anything has changed
715
+ /**
716
+ * if object is not using delta mode,
717
+ * check changes by comparing changeable fields with original object
718
+ */
719
+ if (Array.isArray(this.__changeables)) {
720
+ return (this.__changeables.find((c) => {
721
+ return !object_equals(this[c], orig[c]);
722
+ }) != undefined);
723
+ }
724
+ else {
725
+ /* check all fields */
726
+ for (const key in this) {
727
+ if (key.startsWith("__"))
728
+ continue;
729
+ if (!object_equals(this[key], orig[key]))
730
+ return true;
731
+ }
732
+ return false;
733
+ }
734
+ }
735
+ get isArchived() {
736
+ return this._archived || false;
737
+ }
738
+ set isArchived(v) {
739
+ this._archived = v;
740
+ }
741
+ get isDeleted() {
742
+ return this.get("_deleted") || false;
743
+ }
744
+ get isLocked() {
745
+ return this.get("_locked") || false;
746
+ }
747
+ get objectColor() {
748
+ if (!this.#objectColor) {
749
+ const lastid = this.getID();
750
+ if (lastid)
751
+ this.#objectColor = string_to_color(lastid);
752
+ }
753
+ return this.#objectColor || "#000000";
754
+ }
755
+ set isLocked(v) {
756
+ this._locked = v;
757
+ }
758
+ set isDeleted(v) {
759
+ this._deleted = v;
760
+ }
761
+ get d() {
762
+ return this.__use_delta ? this.__delta : this;
763
+ }
764
+ /* all updated properties */
765
+ get allproperties() {
766
+ const result = { ...this, ...this.__delta };
767
+ result.__delta = {};
768
+ return result;
769
+ }
770
+ get canModify() {
771
+ return !Boolean(this.__is_readonly);
772
+ }
773
+ get __changeables() {
774
+ return this.constructor["__changeables"];
775
+ }
776
+ get __unchangeables() {
777
+ return this.constructor["__unchangeables"];
778
+ }
779
+ get __use_delta() {
780
+ return this.constructor["__use_delta"];
781
+ }
782
+ get isSaved() {
783
+ return Boolean(this.__saveResultIsSuccess ?? false);
784
+ }
785
+ get isNew() {
786
+ const mid = this.getID();
787
+ if (!mid)
788
+ return true;
789
+ if (typeof mid === "string")
790
+ return mid === "" || mid === "-1";
791
+ if (typeof mid === "number")
792
+ return mid === -1;
793
+ return false;
794
+ }
795
+ get lastChanged() {
796
+ return this.__lastChanged || "";
797
+ }
798
+ get manager() {
799
+ return this.get_managerClass() || undefined;
800
+ }
801
+ get_managerClass = () => undefined;
1041
802
  /**
1042
803
  * @deprecated use setManager
1043
804
  * @param mng
1044
- */
1045
- function set_managerClass(mng) {
1046
- return this.setManager(mng);
1047
- }
805
+ */
806
+ set_managerClass(mng) {
807
+ return this.setManager(mng);
808
+ }
1048
809
  /**
1049
810
  * update the manager class for this object
1050
811
  * @param mng
1051
- */
1052
- }, {
1053
- key: "setManager",
1054
- value: function setManager(mng) {
1055
- if (mng instanceof _ObjectManager["default"] && typeof mng.setObject === "function") {
1056
- //make sure the manager knows what object it is managing
1057
- return mng.setObject(this);
1058
- } else {
1059
- console.error("set_managerClass was used with a bad manager. make sure the input to this function is a correct ObjectManager");
1060
- }
1061
- }
1062
- }, {
1063
- key: "getIndexOrID",
1064
- value: function getIndexOrID() {
1065
- return SimpleObject.getIndexOrID(this);
1066
- }
1067
- }, {
1068
- key: "getIndex",
1069
- value: function getIndex() {
1070
- return SimpleObject.getIndex(this);
1071
- }
1072
- }, {
1073
- key: "getID",
1074
- value: function getID() {
1075
- return SimpleObject.getID(this);
1076
- }
1077
- }, {
1078
- key: "event_run",
1079
- value: (
1080
- /* -------------------------------------------------------------------------- */
1081
- /* Events */
1082
- /* -------------------------------------------------------------------------- */
1083
- function () {
1084
- var _event_run = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee15(eventName) {
1085
- var _this$manager2;
1086
- var _len2,
1087
- params,
1088
- _key3,
1089
- _args15 = arguments;
1090
- return _regeneratorRuntime().wrap(function _callee15$(_context15) {
1091
- while (1) switch (_context15.prev = _context15.next) {
1092
- case 0:
1093
- if (this.manager) {
1094
- _context15.next = 3;
1095
- break;
1096
- }
1097
- if (this.__showErrors === true) console.error("you cant use events (".concat(eventName, ") if your object has no manager"));
1098
- return _context15.abrupt("return");
1099
- case 3:
1100
- for (_len2 = _args15.length, params = new Array(_len2 > 1 ? _len2 - 1 : 0), _key3 = 1; _key3 < _len2; _key3++) {
1101
- params[_key3 - 1] = _args15[_key3];
1102
- }
1103
- _context15.next = 6;
1104
- return (_this$manager2 = this.manager).event_run.apply(_this$manager2, [eventName].concat(params));
1105
- case 6:
1106
- return _context15.abrupt("return", _context15.sent);
1107
- case 7:
1108
- case "end":
1109
- return _context15.stop();
1110
- }
1111
- }, _callee15, this);
1112
- }));
1113
- function event_run(_x23) {
1114
- return _event_run.apply(this, arguments);
1115
- }
1116
- return event_run;
1117
- }())
1118
- }, {
1119
- key: "event_use",
1120
- value: function event_use(name, runEvent) {
1121
- var onlyOn = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
1122
- var runOnce = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
1123
- if (!this.manager) {
1124
- if (this.__showErrors === true) console.error("you cant use events (".concat(name, ") if your object has no manager"));
1125
- return;
1126
- }
1127
- return this.manager.event_use(name, runEvent, onlyOn, runOnce);
1128
- }
1129
- }, {
1130
- key: "event_remove",
1131
- value: function event_remove(name, uname) {
1132
- if (!this.manager) {
1133
- if (this.__showErrors === true) console.error("you cant use events (".concat(name, ") if your object has no manager"));
1134
- return;
1135
- }
1136
- return this.manager.event_remove(name, uname);
1137
- }
1138
- }, {
1139
- key: "event_add",
1140
- value: function () {
1141
- var _event_add = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee16(name, uname, runEvent) {
1142
- var onlyOn,
1143
- runOnce,
1144
- _args16 = arguments;
1145
- return _regeneratorRuntime().wrap(function _callee16$(_context16) {
1146
- while (1) switch (_context16.prev = _context16.next) {
1147
- case 0:
1148
- onlyOn = _args16.length > 3 && _args16[3] !== undefined ? _args16[3] : null;
1149
- runOnce = _args16.length > 4 && _args16[4] !== undefined ? _args16[4] : false;
1150
- if (this.manager) {
1151
- _context16.next = 5;
1152
- break;
1153
- }
1154
- if (this.__showErrors === true) console.error("you cant use events (".concat(name, ") if your object has no manager"));
1155
- return _context16.abrupt("return");
1156
- case 5:
1157
- _context16.next = 7;
1158
- return this.manager.event_add(name, uname, runEvent, onlyOn, runOnce);
1159
- case 7:
1160
- case "end":
1161
- return _context16.stop();
1162
- }
1163
- }, _callee16, this);
1164
- }));
1165
- function event_add(_x24, _x25, _x26) {
1166
- return _event_add.apply(this, arguments);
1167
- }
1168
- return event_add;
1169
- }()
1170
- /* -------------------------------------------------------------------------- */
1171
- /* Original */
1172
- /* -------------------------------------------------------------------------- */
1173
- }, {
1174
- key: "getOriginal",
1175
- value: function getOriginal() {
1176
- return this.__originalobject || undefined;
1177
- }
1178
- }, {
1179
- key: "setOriginal",
1180
- value: function setOriginal() {
1181
- var toObj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
1182
- if (toObj === null) {
1183
- delete this.__originalobject;
1184
- return;
1185
- }
1186
- if (!this.canModify) {
1187
- console.warn("Cant use setOriginal on non original OR readonly objects ! this will create an infinite loop");
1188
- delete this.__originalobject;
1189
- return;
1190
- }
1191
- if (toObj === 0) {
1192
- toObj = this;
1193
- }
1194
- var cloneObject = (0, _object.object_clone)(toObj);
1195
- SimpleObject.setReadonly(cloneObject, true);
1196
- this.__originalobject = (0, _object.object_removeKeys)(cloneObject, ["__"]);
1197
- return this;
1198
- }
1199
- }, {
1200
- key: "addError",
1201
- value: /* -------------------------------------------------------------------------- */
1202
- /* Errors */
1203
- /* -------------------------------------------------------------------------- */
1204
- function addError(title, message) {
1205
- var sendToRegister = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "auto";
1206
- return SimpleObject.addError(this, title, message, sendToRegister);
1207
- }
1208
- }, {
1209
- key: "clearErrors",
1210
- value: function clearErrors() {
1211
- return SimpleObject.clearErrors(this);
1212
- }
1213
- }, {
1214
- key: "getErrors",
1215
- value: function getErrors() {
1216
- return SimpleObject.getErrors(this);
1217
- }
1218
- }, {
1219
- key: "setSaveResult",
1220
- value:
812
+ */
813
+ setManager(mng) {
814
+ if (mng instanceof ObjectManager &&
815
+ typeof mng.setObject === "function") {
816
+ //make sure the manager knows what object it is managing
817
+ return mng.setObject(this);
818
+ }
819
+ else {
820
+ console.error("set_managerClass was used with a bad manager. make sure the input to this function is a correct ObjectManager");
821
+ }
822
+ }
823
+ static isDeleted(obj) {
824
+ if (obj instanceof SimpleObject)
825
+ return obj.isDeleted === true;
826
+ return false;
827
+ }
828
+ getIndexOrID() {
829
+ return SimpleObject.getIndexOrID(this);
830
+ }
831
+ getIndex() {
832
+ return SimpleObject.getIndex(this);
833
+ }
834
+ getID() {
835
+ return SimpleObject.getID(this);
836
+ }
837
+ static getIndexOrID(o) {
838
+ let res = SimpleObject.getIndex(o);
839
+ if (!res || res == -1)
840
+ res = SimpleObject.getID(o);
841
+ return res || -1;
842
+ }
843
+ static getIndex(o) {
844
+ if (o == null || o == undefined)
845
+ return -1;
846
+ switch (typeof o) {
847
+ case "object":
848
+ return o._index_value || -1;
849
+ case "number":
850
+ case "string":
851
+ return Number(o);
852
+ }
853
+ return -1;
854
+ }
855
+ static getID(obj) {
856
+ if (obj == null || obj == undefined)
857
+ return "";
858
+ switch (typeof obj) {
859
+ case "object":
860
+ if (String(obj._bsontype).toLowerCase() == "objectid") {
861
+ return String(obj);
862
+ }
863
+ return String(obj._id ||
864
+ obj.insertedId ||
865
+ obj.ID ||
866
+ obj.id ||
867
+ obj.__data_id ||
868
+ "");
869
+ case "string":
870
+ case "number":
871
+ return String(obj);
872
+ }
873
+ return "";
874
+ }
875
+ /* -------------------------------------------------------------------------- */
876
+ /* Events */
877
+ /* -------------------------------------------------------------------------- */
878
+ async event_run(eventName, ...params) {
879
+ if (!this.manager) {
880
+ if (this.__showErrors === true)
881
+ console.error(`you cant use events (${eventName}) if your object has no manager`);
882
+ return;
883
+ }
884
+ return await this.manager.event_run(eventName, ...params);
885
+ }
886
+ event_use(name, runEvent, onlyOn = null, runOnce = false) {
887
+ if (!this.manager) {
888
+ if (this.__showErrors === true)
889
+ console.error(`you cant use events (${name}) if your object has no manager`);
890
+ return;
891
+ }
892
+ return this.manager.event_use(name, runEvent, onlyOn, runOnce);
893
+ }
894
+ event_remove(name, uname) {
895
+ if (!this.manager) {
896
+ if (this.__showErrors === true)
897
+ console.error(`you cant use events (${name}) if your object has no manager`);
898
+ return;
899
+ }
900
+ return this.manager.event_remove(name, uname);
901
+ }
902
+ async event_add(name, uname, runEvent, onlyOn = null, runOnce = false) {
903
+ if (!this.manager) {
904
+ if (this.__showErrors === true)
905
+ console.error(`you cant use events (${name}) if your object has no manager`);
906
+ return;
907
+ }
908
+ await this.manager.event_add(name, uname, runEvent, onlyOn, runOnce);
909
+ }
910
+ /* -------------------------------------------------------------------------- */
911
+ /* Original */
912
+ /* -------------------------------------------------------------------------- */
913
+ getOriginal() {
914
+ return this.__originalobject || undefined;
915
+ }
916
+ setOriginal(toObj = 0) {
917
+ if (toObj === null) {
918
+ delete this.__originalobject;
919
+ return;
920
+ }
921
+ if (!this.canModify) {
922
+ console.warn("Cant use setOriginal on non original OR readonly objects ! this will create an infinite loop");
923
+ delete this.__originalobject;
924
+ return;
925
+ }
926
+ if (toObj === 0) {
927
+ toObj = this;
928
+ }
929
+ const cloneObject = object_clone(toObj);
930
+ SimpleObject.setReadonly(cloneObject, true);
931
+ this.__originalobject = object_removeKeys(cloneObject, ["__"]);
932
+ return this;
933
+ }
934
+ static setOriginal(obj, toObj = 0) {
935
+ if (!(obj instanceof SimpleObject))
936
+ return undefined;
937
+ return obj.setOriginal(toObj);
938
+ }
939
+ static getOriginal(obj) {
940
+ if (obj instanceof SimpleObject)
941
+ return obj.getOriginal();
942
+ return obj?.__originalobject;
943
+ }
944
+ /* -------------------------------------------------------------------------- */
945
+ /* Errors */
946
+ /* -------------------------------------------------------------------------- */
947
+ addError(title, message, sendToRegister = "auto") {
948
+ return SimpleObject.addError(this, title, message, sendToRegister);
949
+ }
950
+ clearErrors() {
951
+ return SimpleObject.clearErrors(this);
952
+ }
953
+ getErrors() {
954
+ return SimpleObject.getErrors(this);
955
+ }
956
+ static addError(o, title, message, sendToRegister = "auto") {
957
+ const errStr = combine_if_not_blank(title, " : ", message);
958
+ if (o) {
959
+ if (!Array.isArray(o.__errors))
960
+ o.__errors = [];
961
+ o.__errors.push(errStr);
962
+ if (o.__showErrors === false)
963
+ return;
964
+ }
965
+ else if (sendToRegister === "auto")
966
+ sendToRegister = true;
967
+ if (sendToRegister === true) {
968
+ console.error("[REGISTER-ERROR]", errStr);
969
+ gfunc.run_action("add_error", {
970
+ title: title,
971
+ message: message,
972
+ type: "error",
973
+ });
974
+ }
975
+ else {
976
+ console.error("[ERROR]", errStr);
977
+ }
978
+ return o?.__errors || [];
979
+ }
980
+ static getErrors(o) {
981
+ return o?.__errors || [];
982
+ }
983
+ static clearErrors(o) {
984
+ if (o)
985
+ o.__errors = [];
986
+ return true;
987
+ }
988
+ /* -------------------------------------------------------------------------- */
989
+ /* Save Results */
990
+ /* -------------------------------------------------------------------------- */
991
+ /**
992
+ * Checks if the given object is a valid and truthy save result
993
+ * @param result_object
994
+ * @returns
995
+ */
996
+ static isResultValid(result_object, depth = 0) {
997
+ if (object_isEmpty(result_object))
998
+ return false;
999
+ switch (typeof result_object) {
1000
+ case "string":
1001
+ try {
1002
+ result_object = JSON.parse(result_object);
1003
+ return this.isResultValid(result_object);
1004
+ }
1005
+ catch {
1006
+ return false;
1007
+ }
1008
+ case "number":
1009
+ return result_object > 0;
1010
+ case "boolean":
1011
+ return result_object === true;
1012
+ case "object":
1013
+ /* ----------------------------- result is error ---------------------------- */
1014
+ if (result_object instanceof Error) {
1015
+ return false;
1016
+ }
1017
+ /* ----------------- maybe website sends the result as array ---------------- */
1018
+ if (Array.isArray(result_object)) {
1019
+ const allResults = result_object.map((r) => {
1020
+ return Boolean(this.isResultValid(r, depth + 1));
1021
+ });
1022
+ return allResults.find((s) => s === false) == null;
1023
+ }
1024
+ /* ----------------------------- check products/variations ----------------------------- */
1025
+ const varKeys = ["products", "variations"];
1026
+ for (const vk of varKeys) {
1027
+ if (!(vk in result_object) ||
1028
+ array_isEmpty(result_object[vk]))
1029
+ continue;
1030
+ /**
1031
+ * if one product is not valid the result is not valid
1032
+ * but if all products are valid we still need to check the object itself
1033
+ */
1034
+ if (!this.isResultValid(result_object[vk], depth + 1))
1035
+ return false;
1036
+ }
1037
+ if (result_object.order) {
1038
+ /**
1039
+ * if we get a order-products pair, checking the order is enough
1040
+ */
1041
+ return this.isResultValid(result_object.order, depth + 1);
1042
+ }
1043
+ /* -------------------------- check if acknowledged ------------------------- */
1044
+ if (object_isTrue(result_object.acknowledged)) {
1045
+ return true;
1046
+ }
1047
+ if (result_object.expected && result_object.result) {
1048
+ return object_equals(result_object.expected, result_object.result);
1049
+ }
1050
+ return !string_isEmpty(this.getID(result_object));
1051
+ }
1052
+ return false;
1053
+ }
1221
1054
  /**
1222
1055
  * set the response of last save from site
1223
1056
  * and its type
1224
1057
  * @param toObj
1225
- */
1226
- function setSaveResult(toObj) {
1227
- var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "auto";
1228
- var registerErrors = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
1229
- _assertClassBrand(_SimpleObject_brand, this, _setSaveResultObject).call(this, toObj);
1230
- //check if the given object is a valid save result
1231
- if (type === "error") this.__saveResultIsSuccess = false;else this.__saveResultIsSuccess = Boolean(type === "nothing" || this.constructor["isResultValid"](toObj));
1232
- if (type === "auto") {
1233
- type = this.__saveResultIsSuccess ? "normal" : "error";
1234
- }
1235
- if (registerErrors && !this.__saveResultIsSuccess) {
1236
- var sr = this.__saveResultObject;
1237
- var errorString = sr == null ? "" : sr instanceof Error ? sr.message : JSON.stringify(sr);
1238
- SimpleObject.addError(this, "save result is not valid", errorString, true);
1239
- }
1240
- this.__saveResultType = type;
1241
- return type;
1242
- }
1058
+ */
1059
+ setSaveResult(toObj, type = "auto", registerErrors = false) {
1060
+ this.#setSaveResultObject(toObj);
1061
+ //check if the given object is a valid save result
1062
+ if (type === "error")
1063
+ this.__saveResultIsSuccess = false;
1064
+ else
1065
+ this.__saveResultIsSuccess = Boolean(type === "nothing" || this.constructor["isResultValid"](toObj));
1066
+ if (type === "auto") {
1067
+ type = this.__saveResultIsSuccess ? "normal" : "error";
1068
+ }
1069
+ if (registerErrors && !this.__saveResultIsSuccess) {
1070
+ const sr = this.__saveResultObject;
1071
+ const errorString = sr == null
1072
+ ? ""
1073
+ : sr instanceof Error
1074
+ ? sr.message
1075
+ : JSON.stringify(sr);
1076
+ SimpleObject.addError(this, "save result is not valid", errorString, true);
1077
+ }
1078
+ this.__saveResultType = type;
1079
+ return type;
1080
+ }
1243
1081
  /**
1244
1082
  * set the response of last save from site
1245
1083
  * @param toObj
1246
- */
1247
- }, {
1248
- key: "getSaveResult",
1249
- value: function getSaveResult() {
1250
- var original = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
1251
- if (this.isSaved) return this.__saveResultObject;
1252
- return false;
1253
- }
1254
- }, {
1255
- key: "getSaveResultType",
1256
- value: function getSaveResultType() {
1257
- return this.__saveResultType || "nothing";
1258
- }
1259
- /** did we create on the last save */
1260
- }, {
1261
- key: "getIsLastSaveCreate",
1262
- value: function getIsLastSaveCreate() {
1263
- return this.isSaved && this.getSaveResult().insertedId;
1264
- }
1265
- /* -------------------------------------------------------------------------- */
1266
- /* statics */
1267
- /* -------------------------------------------------------------------------- */
1268
- }], [{
1269
- key: "get",
1270
- value: function get(obj, key) {
1271
- var original = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
1272
- if (obj == null) return undefined;
1273
- if (obj instanceof SimpleObject && typeof obj.get === "function") return obj.get(key, original);
1274
- /* ------------------------------- manual get ------------------------------- */
1275
- if (!original && obj.__use_delta != false && _typeof(obj.__delta) === "object" && key in obj.__delta) {
1276
- //@ts-ignore
1277
- return obj.__delta[key];
1278
- }
1279
- return obj[key];
1280
- }
1281
- }, {
1282
- key: "loadValues",
1283
- value: function loadValues(obj, initObject) {
1284
- var fullUpdate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
1285
- if (typeof initObject === "number" || typeof initObject === "string") {
1286
- initObject = {
1287
- _id: initObject
1288
- };
1289
- }
1290
- SimpleObject.factoryClear(obj);
1291
- if (initObject == null) {
1292
- for (var key in obj) {
1293
- if (typeof obj[key] === "function") continue;
1294
- if (key.startsWith("__")) continue;
1295
- delete obj[key];
1296
- }
1297
- } else if (_typeof(initObject) == "object") {
1298
- for (var _key4 in initObject) {
1299
- if (_key4.startsWith("__")) continue;
1300
- if (fullUpdate || Object.prototype.hasOwnProperty.call(obj, _key4)) {
1301
- obj[_key4] = initObject[_key4];
1302
- }
1303
- }
1304
- /* --------------------- special case 1, temp properties -------------------- */
1305
- if ("__temp" in initObject) {
1306
- obj["__temp"] = initObject["__temp"];
1307
- }
1308
- }
1309
- return true;
1310
- }
1311
- }, {
1312
- key: "getChangeableKeys",
1313
- value: function getChangeableKeys(object, options) {
1314
- var _key_list;
1315
- if (!object) return [];
1316
- var key_list = [];
1317
- (_key_list = key_list).push.apply(_key_list, _toConsumableArray(object.constructor["__changeables"]));
1318
- var __unchangeables = object.constructor["__unchangeables"];
1319
- if (!(0, _object.array_isEmpty)(__unchangeables)) {
1320
- key_list = key_list.filter(function (s) {
1321
- return !__unchangeables.includes(s);
1322
- });
1323
- }
1324
- /* -------------------------------------------------------------------------- */
1325
- if (options.extraProperties) {
1326
- var _key_list2;
1327
- (_key_list2 = key_list).push.apply(_key_list2, _toConsumableArray(object.constructor["__extraProperties"]));
1328
- }
1329
- if (options.tempProperties) {
1330
- var _key_list3;
1331
- key_list.push("__temp");
1332
- (_key_list3 = key_list).push.apply(_key_list3, _toConsumableArray(object.constructor["__tempProperties"]));
1333
- }
1334
- if (options.bypassProtected !== true && !options.allProperties) {
1335
- var __protectedProperties = object.constructor["__protectedProperties"];
1336
- //protected keys can only be changed by the creator of this object
1337
- //make sure you set the is_current_user function correctly
1338
- if (!object.isNew && !(0, _object.array_isEmpty)(__protectedProperties) && !Boolean(_global.gfunc.run_action_sync("is_current_user", object.get("_creator")))) {
1339
- key_list = key_list.filter(function (s) {
1340
- return !__protectedProperties.includes(s);
1341
- });
1342
- }
1343
- }
1344
- return key_list;
1345
- }
1346
- /**
1347
- * check if a key can be changed on an object
1348
- * @param object the object we are checking
1349
- * @param key key of the object
1350
- * @param useExtraProps should we check extra props?
1351
- * @returns
1352
- */
1353
- }, {
1354
- key: "canChangeKey",
1355
- value: function canChangeKey(object, key, options) {
1356
- if (!object || !key) return false;
1357
- var keys = this.getChangeableKeys(object, options);
1358
- return keys.includes(key);
1359
- }
1360
- }, {
1361
- key: "hasIllegalChanges",
1362
- value: function hasIllegalChanges(referenceObject, changesObject, updaterUser) {
1363
- var __protectedProperties = (0, _object.object_getStatic)(referenceObject, "__protectedProperties");
1364
- if ((0, _object.object_isEmpty)(__protectedProperties)) return false;
1365
- var referenceUser = (0, _object.object_isClass)(referenceObject) ? (0, _object.object_get)(changesObject, "__user", "_creator") : (0, _object.object_get)(referenceObject, "__user", "_creator");
1366
- if (Boolean(SimpleObject.getID(referenceUser) == SimpleObject.getID(updaterUser))) {
1367
- return false;
1368
- }
1369
- for (var key in changesObject) {
1370
- if (__protectedProperties.includes(key)) {
1371
- return true;
1372
- }
1373
- }
1374
- return false;
1375
- }
1376
- }, {
1377
- key: "setReadonly",
1378
- value: function setReadonly(objs) {
1379
- var readonlyval = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
1380
- var clearChanges = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
1381
- var checkObjs = [];
1382
- if (!objs) objs = [];
1383
- if (!Array.isArray(objs)) checkObjs = [objs];else checkObjs = objs;
1384
- for (var index = 0; index < checkObjs.length; index++) {
1385
- var obj = checkObjs[index];
1386
- obj.__is_readonly = Boolean(readonlyval);
1387
- if (obj instanceof SimpleObject) {
1388
- if (obj.canModify) {
1389
- if (!obj.getOriginal()) obj.setOriginal();
1390
- } else {
1391
- if (clearChanges) obj.clear_changes();
1392
- //we dont need the original object in readonly mode
1393
- obj.setOriginal(null);
1394
- }
1395
- }
1396
- }
1397
- }
1398
- }, {
1399
- key: "setThrowErrors",
1400
- value: function setThrowErrors(objs) {
1401
- var throwErr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
1402
- var checkObjs = [];
1403
- if (!objs) objs = [];
1404
- if (!Array.isArray(objs)) checkObjs = [objs];else checkObjs = objs;
1405
- for (var index = 0; index < checkObjs.length; index++) {
1406
- var element = checkObjs[index];
1407
- element.__throw_errors = throwErr;
1408
- }
1409
- }
1410
- }, {
1411
- key: "isDeleted",
1412
- value: function isDeleted(obj) {
1413
- if (obj instanceof SimpleObject) return obj.isDeleted === true;
1414
- return false;
1415
- }
1416
- }, {
1417
- key: "getIndexOrID",
1418
- value: function getIndexOrID(o) {
1419
- var res = SimpleObject.getIndex(o);
1420
- if (!res || res == -1) res = SimpleObject.getID(o);
1421
- return res || -1;
1422
- }
1423
- }, {
1424
- key: "getIndex",
1425
- value: function getIndex(o) {
1426
- if (o == null || o == undefined) return -1;
1427
- switch (_typeof(o)) {
1428
- case "object":
1429
- return o._index_value || -1;
1430
- case "number":
1431
- case "string":
1432
- return Number(o);
1433
- }
1434
- return -1;
1435
- }
1436
- }, {
1437
- key: "getID",
1438
- value: function getID(obj) {
1439
- if (obj == null || obj == undefined) return "";
1440
- switch (_typeof(obj)) {
1441
- case "object":
1442
- if (String(obj._bsontype).toLowerCase() == "objectid") {
1443
- return String(obj);
1444
- }
1445
- return String(obj._id || obj.insertedId || obj.ID || obj.id || obj.__data_id || "");
1446
- case "string":
1447
- case "number":
1448
- return String(obj);
1449
- }
1450
- return "";
1451
- }
1452
- }, {
1453
- key: "setOriginal",
1454
- value: function setOriginal(obj) {
1455
- var toObj = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
1456
- if (!(obj instanceof SimpleObject)) return undefined;
1457
- return obj.setOriginal(toObj);
1458
- }
1459
- }, {
1460
- key: "getOriginal",
1461
- value: function getOriginal(obj) {
1462
- if (obj instanceof SimpleObject) return obj.getOriginal();
1463
- return obj === null || obj === void 0 ? void 0 : obj.__originalobject;
1464
- }
1465
- }, {
1466
- key: "addError",
1467
- value: function addError(o, title, message) {
1468
- var sendToRegister = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "auto";
1469
- var errStr = (0, _string.combine_if_not_blank)(title, " : ", message);
1470
- if (o) {
1471
- if (!Array.isArray(o.__errors)) o.__errors = [];
1472
- o.__errors.push(errStr);
1473
- if (o.__showErrors === false) return;
1474
- } else if (sendToRegister === "auto") sendToRegister = true;
1475
- if (sendToRegister === true) {
1476
- console.error("[REGISTER-ERROR]", errStr);
1477
- _global.gfunc.run_action("add_error", {
1478
- title: title,
1479
- message: message,
1480
- type: "error"
1481
- });
1482
- } else {
1483
- console.error("[ERROR]", errStr);
1484
- }
1485
- return (o === null || o === void 0 ? void 0 : o.__errors) || [];
1486
- }
1487
- }, {
1488
- key: "getErrors",
1489
- value: function getErrors(o) {
1490
- return (o === null || o === void 0 ? void 0 : o.__errors) || [];
1491
- }
1492
- }, {
1493
- key: "clearErrors",
1494
- value: function clearErrors(o) {
1495
- if (o) o.__errors = [];
1496
- return true;
1497
- }
1498
- /* -------------------------------------------------------------------------- */
1499
- /* Save Results */
1500
- /* -------------------------------------------------------------------------- */
1501
- /**
1502
- * Checks if the given object is a valid and truthy save result
1503
- * @param result_object
1504
- * @returns
1505
- */
1506
- }, {
1507
- key: "isResultValid",
1508
- value: function isResultValid(result_object) {
1509
- var _this4 = this;
1510
- var depth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
1511
- if ((0, _object.object_isEmpty)(result_object)) return false;
1512
- switch (_typeof(result_object)) {
1513
- case "string":
1514
- try {
1515
- result_object = JSON.parse(result_object);
1516
- return this.isResultValid(result_object);
1517
- } catch (_unused) {
1518
- return false;
1519
- }
1520
- case "number":
1521
- return result_object > 0;
1522
- case "boolean":
1523
- return result_object === true;
1524
- case "object":
1525
- /* ----------------------------- result is error ---------------------------- */
1526
- if (result_object instanceof Error) {
1527
- return false;
1528
- }
1529
- /* ----------------- maybe website sends the result as array ---------------- */
1530
- if (Array.isArray(result_object)) {
1531
- var allResults = result_object.map(function (r) {
1532
- return Boolean(_this4.isResultValid(r, depth + 1));
1533
- });
1534
- return allResults.find(function (s) {
1535
- return s === false;
1536
- }) == null;
1537
- }
1538
- /* ----------------------------- check products/variations ----------------------------- */
1539
- var varKeys = ["products", "variations"];
1540
- for (var _i = 0, _varKeys = varKeys; _i < _varKeys.length; _i++) {
1541
- var vk = _varKeys[_i];
1542
- if (!(vk in result_object) || (0, _object.array_isEmpty)(result_object[vk])) continue;
1543
- /**
1544
- * if one product is not valid the result is not valid
1545
- * but if all products are valid we still need to check the object itself
1546
- */
1547
- if (!this.isResultValid(result_object[vk], depth + 1)) return false;
1548
- }
1549
- if (result_object.order) {
1550
- /**
1551
- * if we get a order-products pair, checking the order is enough
1552
- */
1553
- return this.isResultValid(result_object.order, depth + 1);
1554
- }
1555
- /* -------------------------- check if acknowledged ------------------------- */
1556
- if ((0, _object.object_isTrue)(result_object.acknowledged)) {
1557
- return true;
1558
- }
1559
- if (result_object.expected && result_object.result) {
1560
- return (0, _object.object_equals)(result_object.expected, result_object.result);
1561
- }
1562
- return !(0, _string.string_isEmpty)(this.getID(result_object));
1563
- }
1564
- return false;
1565
- }
1566
- }, {
1567
- key: "setTemp",
1568
- value: (function () {
1569
- var _setTemp2 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee17(obj, key, value) {
1570
- var sendChanges,
1571
- _args17 = arguments;
1572
- return _regeneratorRuntime().wrap(function _callee17$(_context17) {
1573
- while (1) switch (_context17.prev = _context17.next) {
1574
- case 0:
1575
- sendChanges = _args17.length > 3 && _args17[3] !== undefined ? _args17[3] : false;
1576
- if (!(_typeof(obj) !== "object" || !obj || Array.isArray(obj))) {
1577
- _context17.next = 3;
1578
- break;
1579
- }
1580
- return _context17.abrupt("return");
1581
- case 3:
1582
- if (!(obj instanceof SimpleObject)) {
1583
- _context17.next = 7;
1584
- break;
1585
- }
1586
- _context17.next = 6;
1587
- return obj.setTemp(key, value, sendChanges);
1588
- case 6:
1589
- return _context17.abrupt("return", _context17.sent);
1590
- case 7:
1591
- //
1592
- if (obj.__temp == null) obj.__temp = {};
1593
- (0, _object.object_set)(obj.__temp, key, value);
1594
- case 9:
1595
- case "end":
1596
- return _context17.stop();
1597
- }
1598
- }, _callee17);
1599
- }));
1600
- function setTemp(_x27, _x28, _x29) {
1601
- return _setTemp2.apply(this, arguments);
1602
- }
1603
- return setTemp;
1604
- }())
1605
- }, {
1606
- key: "factoryClear",
1607
- value: function factoryClear(obj) {
1608
- obj.clear_changes();
1609
- SimpleObject.clearErrors(obj);
1610
- }
1611
- }, {
1612
- key: "delete_cache",
1613
- value: function () {
1614
- var _delete_cache = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee18(context) {
1615
- var cacheKey;
1616
- return _regeneratorRuntime().wrap(function _callee18$(_context18) {
1617
- while (1) switch (_context18.prev = _context18.next) {
1618
- case 0:
1619
- if (this.__db_name) {
1620
- _context18.next = 2;
1621
- break;
1622
- }
1623
- return _context18.abrupt("return");
1624
- case 2:
1625
- if (context) {
1626
- _context18.next = 7;
1627
- break;
1628
- }
1629
- _context18.next = 5;
1630
- return _global.gcache.delete_session_cache(this.__db_name);
1631
- case 5:
1632
- _context18.next = 10;
1633
- break;
1634
- case 7:
1635
- cacheKey = "".concat(this.__db_name, "-").concat(context);
1636
- _context18.next = 10;
1637
- return _global.gcache.delete_session_cache(cacheKey);
1638
- case 10:
1639
- case "end":
1640
- return _context18.stop();
1641
- }
1642
- }, _callee18, this);
1643
- }));
1644
- function delete_cache(_x30) {
1645
- return _delete_cache.apply(this, arguments);
1646
- }
1647
- return delete_cache;
1648
- }()
1649
- }, {
1650
- key: "get_canModify",
1651
- value: function get_canModify(o) {
1652
- if (o instanceof SimpleObject) return o.canModify;
1653
- return false;
1654
- }
1655
- /* -------------------------------------------------------------------------- */
1656
- }, {
1657
- key: "equals",
1658
- value: function equals(a, b) {
1659
- console.warn("Dont use the default equals method !");
1660
- if (a == undefined || b == undefined) return false;
1661
- return a === b;
1662
- }
1663
- }]);
1664
- }(_MapableObject2.MapableObject);
1665
- function _setDefaultProperty(key, value) {
1666
- //@ts-ignore
1667
- if (this[key] == undefined || this[key] === "" || this[key] === 0) {
1668
- this[key] = value;
1669
- return true;
1670
- }
1671
- return false;
1672
- }
1673
- function _setDefaultPropertyNow(key) {
1674
- //@ts-ignore
1675
- if (this[key] == undefined || this[key] === "" || this[key] === 0) {
1676
- this[key] = new Date();
1677
- return true;
1678
- }
1679
- return false;
1680
- }
1681
- function _getSubProperty(key, subkey) {
1682
- var original = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
1683
- var subobj = this.get(key, original);
1684
- if (subobj == null || _typeof(subobj) !== "object") return undefined;
1685
- return subobj[subkey];
1686
- }
1687
- /* -------------------------------------------------------------------------- */
1688
- /* set */
1689
- /* -------------------------------------------------------------------------- */
1690
- function _setSubProperty(key, subkey, value) {
1691
- var subobj = this.get(key);
1692
- //@ts-ignore
1693
- if (subobj == null || _typeof(subobj) !== "object") subobj = {};else subobj = _objectSpread({}, subobj); //make a clone so we dont update the original
1694
- subobj[subkey] = value;
1695
- _assertClassBrand(_SimpleObject_brand, this, _setProperty).call(this, key, subobj);
1696
- }
1697
- /**
1698
- * update a property on this object by updating the `__delta`
1699
- * or update the object property directly depending on `__use_delta` setting
1700
- *
1701
- * @param key
1702
- * @param value
1703
- */
1704
- function _setProperty(key, value) {
1705
- var checkIsChanged = false;
1706
- if (this.__use_delta) {
1707
- if (this[key] === value) {
1708
- /**
1709
- * we set something back to its original value
1710
- * no need to save it as delta
1711
- */
1712
- delete this.__delta[key];
1713
- ////checkIsChanged = true; //check if we should set __has_delta to false
1714
- } else {
1715
- this.__delta[key] = value; //always update delta to keep track of changes
1716
- }
1717
- } else {
1718
- this[key] = value; //on noDelta mode update the object itself
1719
- this.__delta[key] = value; //always update delta to keep track of changes
1720
- }
1721
- return true;
1722
- }
1723
- function _setSaveResultObject(toObj) {
1724
- if (toObj == null) toObj = null; //null or undefined
1725
- this.__saveResultObject = toObj;
1726
- return true;
1727
- }
1728
- _defineProperty(SimpleObject, "__db_name", "");
1729
- _defineProperty(SimpleObject, "__object_name", "");
1730
- //these properties should not be changed and are usually set by server
1731
- _defineProperty(SimpleObject, "__unchangeables", []);
1732
- //these properties can be directly changed and are included in deltaObject
1733
- _defineProperty(SimpleObject, "__changeables", []);
1734
- //these properties usually are not directly changed and sometimes are included in deltaObject
1735
- _defineProperty(SimpleObject, "__extraProperties", []);
1736
- //these properties are never sent to database but may be sent to client
1737
- _defineProperty(SimpleObject, "__tempProperties", []);
1738
- //these properties can only be changed by the _creator
1739
- _defineProperty(SimpleObject, "__protectedProperties", []);
1740
- //these properties will be evaluated when needed
1741
- _defineProperty(SimpleObject, "__functionProperties", []);
1742
- //apply these string formats
1743
- _defineProperty(SimpleObject, "__formatList", void 0);
1744
- //types for children can be used when importing children
1745
- _defineProperty(SimpleObject, "__childTypes", void 0);
1746
- //these fields are used when importing
1747
- _defineProperty(SimpleObject, "__importColumns", void 0);
1748
- //these fields can be used when importing and checking if an item exists
1749
- _defineProperty(SimpleObject, "__checkProperties", []);
1750
- _defineProperty(SimpleObject, "__use_delta", true);
1751
- var _default = exports["default"] = SimpleObject;
1084
+ */
1085
+ #setSaveResultObject(toObj) {
1086
+ if (toObj == null)
1087
+ toObj = null; //null or undefined
1088
+ this.__saveResultObject = toObj;
1089
+ return true;
1090
+ }
1091
+ getSaveResult(original = false) {
1092
+ if (this.isSaved)
1093
+ return this.__saveResultObject;
1094
+ return false;
1095
+ }
1096
+ getSaveResultType() {
1097
+ return this.__saveResultType || "nothing";
1098
+ }
1099
+ /** did we create on the last save */
1100
+ getIsLastSaveCreate() {
1101
+ return this.isSaved && this.getSaveResult().insertedId;
1102
+ }
1103
+ /* -------------------------------------------------------------------------- */
1104
+ /* statics */
1105
+ /* -------------------------------------------------------------------------- */
1106
+ static async setTemp(obj, key, value, sendChanges = false) {
1107
+ if (typeof obj !== "object" || !obj || Array.isArray(obj))
1108
+ return;
1109
+ if (obj instanceof SimpleObject)
1110
+ return await obj.setTemp(key, value, sendChanges);
1111
+ //
1112
+ if (obj.__temp == null)
1113
+ obj.__temp = {};
1114
+ object_set(obj.__temp, key, value);
1115
+ }
1116
+ static factoryClear(obj) {
1117
+ obj.clear_changes();
1118
+ SimpleObject.clearErrors(obj);
1119
+ }
1120
+ static async delete_cache(context) {
1121
+ if (!this.__db_name)
1122
+ return;
1123
+ if (!context)
1124
+ await gcache.delete_session_cache(this.__db_name);
1125
+ else {
1126
+ const cacheKey = `${this.__db_name}-${context}`;
1127
+ await gcache.delete_session_cache(cacheKey);
1128
+ }
1129
+ }
1130
+ static get_canModify(o) {
1131
+ if (o instanceof SimpleObject)
1132
+ return o.canModify;
1133
+ return false;
1134
+ }
1135
+ /* -------------------------------------------------------------------------- */
1136
+ static equals(a, b) {
1137
+ console.warn("Dont use the default equals method !");
1138
+ if (a == undefined || b == undefined)
1139
+ return false;
1140
+ return a === b;
1141
+ }
1142
+ }
1143
+ export default SimpleObject;