From 88bd1f94d0a0051dfe2975e3b5d2606542d699ee Mon Sep 17 00:00:00 2001 From: unpete Date: Sat, 3 Dec 2016 20:48:58 +0500 Subject: [PATCH] =?UTF-8?q?=D0=9C=D0=B5=D1=82=D0=BE=D0=B4=D1=8B=20=D0=BF?= =?UTF-8?q?=D0=BE=D0=B4=D0=B3=D0=BE=D1=82=D0=BE=D0=B2=D0=BA=D0=B8=20=D1=81?= =?UTF-8?q?=D0=B8=D1=81=D1=82=D0=B5=D0=BC=D0=BD=D1=8B=D1=85=20=D0=BC=D0=B5?= =?UTF-8?q?=D1=82=D0=B0=D0=B4=D0=B0=D0=BD=D0=BD=D1=8B=D1=85=20=D1=83=D0=B4?= =?UTF-8?q?=D0=B0=D0=BB=D0=B5=D0=BD=D1=8B=20=D0=B8=D0=B7=201=D0=A1=20?= =?UTF-8?q?=D0=B8=20=D0=BF=D0=B5=D1=80=D0=B5=D0=BC=D0=B5=D1=89=D0=B5=D0=BD?= =?UTF-8?q?=D1=8B=20=D0=B2=20=D0=BA=D0=BE=D0=BD=D1=81=D1=82=D1=80=D1=83?= =?UTF-8?q?=D0=BA=D1=82=D0=BE=D1=80=20=5FMeta=5F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- data/log.json | 68 -- dist/metadata.core.js | 1015 ++++++++++++++++------- dist/metadata.core.min.js | 10 +- dist/metadata.js | 1003 ++++++++++++++++------ dist/metadata.min.js | 21 +- gulpfile.js | 1 + history.md | 3 + lib/metadata.core.js | 1015 ++++++++++++++++------- lib/metadata.js | 1003 ++++++++++++++++------ lib/metadata.min.js | 21 +- package.json | 2 +- packages/metadata-core/src/common.js | 4 +- packages/metadata-core/src/meta.js | 28 +- packages/metadata-core/src/meta_sys.js | 420 ++++++++++ packages/metadata-core/src/mngrs.js | 106 +-- packages/metadata-core/src/sys_types.js | 273 ------ src/common.js | 23 +- src/common.ui.js | 2 +- src/meta_meta.js | 418 +++++++++- src/meta_mngrs.js | 446 +++++----- src/server/README.md | 2 +- src/server/build_meta.js | 13 +- src/utils/prebuild.js | 13 +- 23 files changed, 4090 insertions(+), 1820 deletions(-) delete mode 100644 data/log.json create mode 100644 packages/metadata-core/src/meta_sys.js delete mode 100644 packages/metadata-core/src/sys_types.js diff --git a/data/log.json b/data/log.json deleted file mode 100644 index e93c090f6..000000000 --- a/data/log.json +++ /dev/null @@ -1,68 +0,0 @@ -{ "ireg": { - "$log": { - "name": "$log", - "note": "", - "synonym": "Журнал событий", - "dimensions": { - "date": { - "synonym": "Дата", - "multiline_mode": false, - "tooltip": "Время события", - "type": { - "types": [ - "number" - ], - "digits": 15, - "fraction_figits": 0 - } - }, - "sequence": { - "synonym": "Порядок", - "multiline_mode": false, - "tooltip": "Порядок следования", - "type": { - "types": [ - "number" - ], - "digits": 6, - "fraction_figits": 0 - } - } - }, - "resources": { - "class": { - "synonym": "Класс", - "multiline_mode": false, - "tooltip": "Класс события", - "type": { - "types": [ - "string" - ], - "str_len": 100 - } - }, - "note": { - "synonym": "Комментарий", - "multiline_mode": true, - "tooltip": "Текст события", - "type": { - "types": [ - "string" - ], - "str_len": 0 - } - }, - "obj": { - "synonym": "Объект", - "tooltip": "Объект, к которому относится событие", - "type": { - "types": [ - "string" - ], - "str_len": 0 - } - } - } - } - } -} \ No newline at end of file diff --git a/dist/metadata.core.js b/dist/metadata.core.js index 233890e92..661282cbc 100644 --- a/dist/metadata.core.js +++ b/dist/metadata.core.js @@ -1,5 +1,5 @@ /*! - metadata.js v0.11.223, built:2016-12-02 © Evgeniy Malyarov http://www.oknosoft.ru 2014-2016 + metadata.js v0.12.225, built:2016-12-03 © Evgeniy Malyarov http://www.oknosoft.ru 2014-2016 metadata.js may be freely distributed under the AGPL-3.0. To obtain _Oknosoft Commercial license_, contact info@oknosoft.ru */ (function(root, factory) { @@ -289,7 +289,7 @@ function MetaEngine() { this.__define({ version: { - value: "0.11.223", + value: "0.12.225", writable: false }, @@ -653,8 +653,8 @@ function MetaEngine() { */ record_log: { value: function (err) { - if($p.ireg && $p.ireg.$log) - $p.ireg.$log.record(err); + if($p.ireg && $p.ireg.log) + $p.ireg.log.record(err); console.log(err); } }, @@ -954,6 +954,18 @@ function MetaEngine() { value: LogManager }, + MetaObjManager: { + value: MetaObjManager + }, + + MetaFieldManager: { + value: MetaFieldManager + }, + + SchemeSettingsManager: { + value: SchemeSettingsManager + }, + AccumRegManager: { value: AccumRegManager }, @@ -1023,6 +1035,7 @@ function MetaEngine() { } }); + } /** @@ -1366,16 +1379,16 @@ function Ajax() { if(typeof auth == "object" && auth.username && auth.hasOwnProperty("password")){ username = auth.username; password = auth.password; - + }else{ if($p.ajax.username && $p.ajax.authorized){ username = $p.ajax.username; password = $p.aes.Ctr.decrypt($p.ajax.password); - + }else{ username = $p.wsql.get_user_param("user_name"); password = $p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd")); - + if(!username && $p.job_prm && $p.job_prm.guest_name){ username = $p.job_prm.guest_name; password = $p.aes.Ctr.decrypt($p.job_prm.guest_pwd); @@ -2973,11 +2986,419 @@ function Pouch(){ */ function Meta() { - var _m; + var _m = { + enm: { + accumulation_record_type: [ + { + order: 0, + name: "debit", + synonym: "Приход" + }, + { + order: 1, + name: "credit", + synonym: "Расход" + } + ], + comparison_types: [ + { + order: 0, + name: "gt", + synonym: "Больше" + }, + { + order: 1, + name: "gte", + synonym: "Больше или равно" + }, + { + order: 2, + name: "lt", + synonym: "Меньше" + }, + { + order: 3, + name: "lte", + synonym: "Меньше или равно " + }, + { + order: 4, + name: "eq", + synonym: "Равно" + }, + { + order: 5, + name: "ne", + synonym: "Не равно" + }, + { + "order": 6, + "name": "in", + "synonym": "В списке" + }, + { + order: 7, + name: "nin", + synonym: "Не в списке" + }, + { + order: 8, + name: "lke", + synonym: "Подобно " + }, + { + order: 9, + name: "nlk", + synonym: "Не подобно" + } + ] + }, + cat: { + meta_objs: {}, + meta_fields: {}, + scheme_settings: { + name: "scheme_settings", + splitted: true, + synonym: "Настройки отчетов и списков", + illustration: "", + obj_presentation: "", + list_presentation: "", + input_by_string: [ + "name" + ], + hierarchical: false, + has_owners: false, + group_hierarchy: true, + main_presentation_name: true, + code_length: 0, + fields: { + obj: { + "synonym": "Объект", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 250 + } + }, + user: { + "synonym": "Пользователь", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 50 + } + }, + predefined_name: { + "synonym": "", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 256 + } + } + }, + tabular_sections: { + available_fields: { + "name": "available_fields", + "synonym": "Доступные поля", + "tooltip": "Состав, порядок и ширина колонок", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "Для плоского списка, родитель пустой", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "use": { + "synonym": "Использование", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "boolean" + ] + } + }, + "field": { + "synonym": "Поле", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "width": { + "synonym": "Ширина", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "number" + ], + "digits": 6, + "fraction_figits": 0 + } + }, + "caption": { + "synonym": "Заголовок", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + sort_fields: { + "name": "sort_fields", + "synonym": "Поля сортировки", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "field": { + "synonym": "Поле", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + grouping_fields: { + "name": "grouping_fields", + "synonym": "Поля группировки", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "field": { + "synonym": "Поле", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + selection: { + "name": "selection", + "synonym": "Отбор", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "use": { + "synonym": "Использование", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "boolean" + ] + } + }, + "left_value": { + "synonym": "Левое значение", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "comparison_type": { + "synonym": "Вид сравнения", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "right_value": { + "synonym": "Правое значение", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + scheme: { + "name": "scheme", + "synonym": "Структура", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 10 + } + }, + "kind": { + "synonym": "Вид раздела отчета", + "multiline_mode": false, + "tooltip": "список, таблица, группировка строк, группировка колонок", + "type": { + "types": [ + "string" + ], + "str_len": 10 + } + } + } + } + }, + cachable: "doc" + } + }, + doc: {}, + ireg: { + "log": { + name: "log", + note: "", + synonym: "Журнал событий", + dimensions: { + date: { + synonym: "Дата", + multiline_mode: false, + tooltip: "Время события", + type: { + types: [ + "number" + ], + digits: 15, + fraction_figits: 0 + } + }, + sequence: { + synonym: "Порядок", + multiline_mode: false, + tooltip: "Порядок следования", + type: { + types: [ + "number" + ], + digits: 6, + fraction_figits: 0 + } + } + }, + resources: { + "class": { + synonym: "Класс", + multiline_mode: false, + tooltip: "Класс события", + type: { + types: [ + "string" + ], + str_len: 100 + } + }, + note: { + synonym: "Комментарий", + multiline_mode: true, + tooltip: "Текст события", + type: { + types: [ + "string" + ], + str_len: 0 + } + }, + obj: { + synonym: "Объект", + multiline_mode: true, + tooltip: "Объект, к которому относится событие", + type: { + types: [ + "string" + ], + str_len: 0 + } + } + } + } + }, + areg: {}, + dp: {}, + rep: {}, + cch: {}, + cacc: {} + }; _md = this; - // загружает метаданные из pouchdb function meta_from_pouch(meta_db){ @@ -2987,7 +3408,7 @@ function Meta() { }) .then(function (doc) { - _m = doc; + $p._patch(_m, doc); doc = null; return meta_db.get('meta_patch'); @@ -3024,7 +3445,7 @@ function Meta() { function do_init(){ if(meta_db && !is_local && !is_remote){ - _m = meta_db; + $p._patch(_m, meta_db); meta_db = null; _md.create_managers(); @@ -3055,7 +3476,7 @@ function Meta() { if(!_m) do_init(); - else{ + else if($p.iface && $p.iface.do_reload){ // если изменились метаданные, запланировать перезагрузку setTimeout(function () { @@ -3700,7 +4121,7 @@ function DataManager(class_name){ * ### После чтения объекта с сервера * Имеет смысл для объектов с типом кеширования ("doc", "doc_remote", "meta", "e1cib"). * т.к. структура _DataObj_ может отличаться от прототипа в базе-источнике, в обработчике можно дозаполнить или пересчитать реквизиты прочитанного объекта - * + * * @event after_load * @for DataManager */ @@ -4068,7 +4489,7 @@ DataManager.prototype.sync_grid = function(attr, grid){ if(typeof attr.custom_selection == "function"){ return attr.custom_selection(attr); - + }else if(mgr.cachable == "ram"){ // запрос к alasql @@ -4132,7 +4553,7 @@ DataManager.prototype.sync_grid = function(attr, grid){ }); } - + // TODO: переделать обработку catch() return request() .then(to_grid) @@ -4425,8 +4846,8 @@ DataManager.prototype.print = function(ref, model, wnd){ // если _printing_plates содержит ссылку на обрабочтик печати, используем его if(this._printing_plates[model] instanceof DataObj) - model = this._printing_plates[model]; - + model = this._printing_plates[model]; + // если существует локальный обработчик, используем его if(model instanceof DataObj && model.execute){ @@ -4439,7 +4860,7 @@ DataManager.prototype.print = function(ref, model, wnd){ .then(tune_wnd_print); }else{ - + // иначе - печатаем средствами 1С или иного сервера var rattr = {}; $p.ajax.default_attr(rattr, $p.job_prm.irest_url()); @@ -4499,9 +4920,9 @@ DataManager.prototype.printing_plates = function(){ * @param class_name {string} - имя типа менеджера объекта */ function RefDataManager(class_name) { - + RefDataManager.superclass.constructor.call(this, class_name); - + } RefDataManager._extend(DataManager); @@ -4736,7 +5157,7 @@ RefDataManager.prototype.__define({ return this.get(); } }, - + /** * Возаращает массив запросов для создания таблиц объекта и его табличных частей * @method get_sql_struct @@ -5531,10 +5952,10 @@ function RegisterManager(class_name){ attr = {}; else if(typeof attr == "string") attr = {ref: attr}; - + if(attr.ref && return_row) return force_promise ? Promise.resolve(this.by_ref[attr.ref]) : this.by_ref[attr.ref]; - + attr.action = "select"; var arr = $p.wsql.alasql(this.get_sql_struct(attr), attr._values), @@ -5552,7 +5973,7 @@ function RegisterManager(class_name){ res.push(this.by_ref[this.get_ref(arr[i])]); } } - + return force_promise ? Promise.resolve(res) : res; }; @@ -6050,83 +6471,295 @@ InfoRegManager.prototype.slice_last = function(filter){ }; + /** - * ### Журнал событий - * Хранит и накапливает события сеанса
- * Является наследником регистра сведений - * @extends InfoRegManager - * @class LogManager - * @static + * ### Абстрактный менеджер регистра накопления + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "AccumRegs"}}{{/crossLink}} + * + * @class AccumRegManager + * @extends RegisterManager + * @constructor + * @param class_name {string} - имя типа менеджера объекта. например, "areg.goods_on_stores" */ -function LogManager(){ +function AccumRegManager(class_name){ + + AccumRegManager.superclass.constructor.call(this, class_name); +} +AccumRegManager._extend(RegisterManager); - LogManager.superclass.constructor.call(this, "ireg.$log"); - var smax; - this.__define({ +/** + * ### Абстрактный менеджер справочника + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Catalogs"}}{{/crossLink}} + * + * @class CatManager + * @extends RefDataManager + * @constructor + * @param class_name {string} + */ +function CatManager(class_name) { + + CatManager.superclass.constructor.call(this, class_name); + + // реквизиты по метаданным + if(this.metadata().hierarchical && this.metadata().group_hierarchy){ /** - * Добавляет запись в журнал - * @param msg {String|Object|Error} - текст + класс события - * @param [msg.obj] {Object} - дополнительный json объект + * ### Признак "это группа" + * @property is_folder + * @for CatObj + * @type {Boolean} */ - record: { - value: function(msg){ + $p[this.obj_constructor()].prototype.__define("is_folder", { + get : function(){ return this._obj.is_folder || false}, + set : function(v){ this._obj.is_folder = $p.utils.fix_boolean(v)}, + enumerable: true, + configurable: true + }); + } - if(msg instanceof Error){ - if(console) - console.log(msg); - msg = { - class: "error", - note: msg.toString() - } - }else if(typeof msg == "object" && !msg.class && !msg.obj){ - msg = { - class: "obj", - obj: msg, - note: msg.note - }; - }else if(typeof msg != "object") - msg = {note: msg}; +} +CatManager._extend(RefDataManager); - msg.date = Date.now() + $p.wsql.time_diff; +/** + * Возвращает объект по наименованию + * @method by_name + * @param name {String|Object} - искомое наименование + * @return {DataObj} + */ +CatManager.prototype.by_name = function(name){ - // уникальность ключа - if(!smax) - smax = alasql.compile("select MAX(`sequence`) as `sequence` from `ireg_$log` where `date` = ?"); - var res = smax([msg.date]); - if(!res.length || res[0].sequence === undefined) - msg.sequence = 0; - else - msg.sequence = parseInt(res[0].sequence) + 1; + var o; - // класс сообщения - if(!msg.class) - msg.class = "note"; + this.find_rows({name: name}, function (obj) { + o = obj; + return false; + }); - $p.wsql.alasql("insert into `ireg_$log` (`ref`, `date`, `sequence`, `class`, `note`, `obj`) values (?,?,?,?,?,?)", - [msg.date + "¶" + msg.sequence, msg.date, msg.sequence, msg.class, msg.note, msg.obj ? JSON.stringify(msg.obj) : ""]); + if(!o) + o = this.get(); - } - }, + return o; +}; - /** - * Сбрасывает события на сервер - * @method backup - * @param [dfrom] {Date} - * @param [dtill] {Date} - */ - backup: { - value: function(dfrom, dtill){ +/** + * Возвращает объект по коду + * @method by_id + * @param id {String|Object} - искомый код + * @return {DataObj} + */ +CatManager.prototype.by_id = function(id){ - } - }, + var o; - /** - * Восстанавливает события из архива на сервере - * @method restore - * @param [dfrom] {Date} + this.find_rows({id: id}, function (obj) { + o = obj; + return false; + }); + + if(!o) + o = this.get(); + + return o; +}; + +/** + * Для иерархических кешируемых справочников возвращает путь элемента + * @param ref {String|CatObj} - ссылка или объект данных + * @return {string} - строка пути элемента + */ +CatManager.prototype.path = function(ref){ + var res = [], tobj; + + if(ref instanceof DataObj) + tobj = ref; + else + tobj = this.get(ref, false, true); + if(tobj) + res.push({ref: tobj.ref, presentation: tobj.presentation}); + + if(tobj && this.metadata().hierarchical){ + while(true){ + tobj = tobj.parent; + if(tobj.empty()) + break; + res.push({ref: tobj.ref, presentation: tobj.presentation}); + } + } + return res; +}; + + + +/** + * ### Абстрактный менеджер плана видов характеристик + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "ChartsOfCharacteristics"}}{{/crossLink}} + * + * @class ChartOfCharacteristicManager + * @extends CatManager + * @constructor + * @param class_name {string} + */ +function ChartOfCharacteristicManager(class_name){ + + ChartOfCharacteristicManager.superclass.constructor.call(this, class_name); + +} +ChartOfCharacteristicManager._extend(CatManager); + + +/** + * ### Абстрактный менеджер плана счетов + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "ChartsOfAccounts"}}{{/crossLink}} + * + * @class ChartOfAccountManager + * @extends CatManager + * @constructor + * @param class_name {string} + */ +function ChartOfAccountManager(class_name){ + + ChartOfAccountManager.superclass.constructor.call(this, class_name); + +} +ChartOfAccountManager._extend(CatManager); + + +/** + * ### Абстрактный менеджер документов + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Documents"}}{{/crossLink}} + * + * @class DocManager + * @extends RefDataManager + * @constructor + * @param class_name {string} + */ +function DocManager(class_name) { + + + DocManager.superclass.constructor.call(this, class_name); + +} +DocManager._extend(RefDataManager); + +/** + * ### Абстрактный менеджер задач + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Tasks"}}{{/crossLink}} + * + * @class TaskManager + * @extends CatManager + * @constructor + * @param class_name {string} + */ +function TaskManager(class_name){ + + TaskManager.superclass.constructor.call(this, class_name); + +} +TaskManager._extend(CatManager); + +/** + * ### Абстрактный менеджер бизнес-процессов + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "BusinessProcesses"}}{{/crossLink}} + * + * @class BusinessProcessManager + * @extends CatManager + * @constructor + * @param class_name {string} + */ +function BusinessProcessManager(class_name){ + + BusinessProcessManager.superclass.constructor.call(this, class_name); + +} +BusinessProcessManager._extend(CatManager); + + +/** + * ### Журнал событий + * Хранит и накапливает события сеанса
+ * Является наследником регистра сведений + * @extends InfoRegManager + * @class LogManager + * @static + */ +function LogManager(){ + + LogManager.superclass.constructor.call(this, "ireg.log"); + + var smax; + + this.__define({ + + /** + * Добавляет запись в журнал + * @param msg {String|Object|Error} - текст + класс события + * @param [msg.obj] {Object} - дополнительный json объект + */ + record: { + value: function(msg){ + + if(msg instanceof Error){ + if(console) + console.log(msg); + msg = { + class: "error", + note: msg.toString() + } + }else if(typeof msg == "object" && !msg.class && !msg.obj){ + msg = { + class: "obj", + obj: msg, + note: msg.note + }; + }else if(typeof msg != "object") + msg = {note: msg}; + + msg.date = Date.now() + $p.wsql.time_diff; + + // уникальность ключа + if(!smax) + smax = alasql.compile("select MAX(`sequence`) as `sequence` from `ireg_log` where `date` = ?"); + var res = smax([msg.date]); + if(!res.length || res[0].sequence === undefined) + msg.sequence = 0; + else + msg.sequence = parseInt(res[0].sequence) + 1; + + // класс сообщения + if(!msg.class) + msg.class = "note"; + + $p.wsql.alasql("insert into `ireg_log` (`ref`, `date`, `sequence`, `class`, `note`, `obj`) values (?,?,?,?,?,?)", + [msg.date + "¶" + msg.sequence, msg.date, msg.sequence, msg.class, msg.note, msg.obj ? JSON.stringify(msg.obj) : ""]); + + } + }, + + /** + * Сбрасывает события на сервер + * @method backup + * @param [dfrom] {Date} + * @param [dtill] {Date} + */ + backup: { + value: function(dfrom, dtill){ + + } + }, + + /** + * Восстанавливает события из архива на сервере + * @method restore + * @param [dfrom] {Date} * @param [dtill] {Date} */ restore: { @@ -6165,7 +6798,7 @@ function LogManager(){ return undefined; var parts = ref.split("¶"); - $p.wsql.alasql("select * from `ireg_$log` where date=" + parts[0] + " and sequence=" + parts[1]).forEach(function (row) { + $p.wsql.alasql("select * from `ireg_log` where date=" + parts[0] + " and sequence=" + parts[1]).forEach(function (row) { new RegisterRow(row, this); }.bind(this)); } @@ -6178,7 +6811,7 @@ function LogManager(){ value: function(attr){ if(attr && attr.action == "get_selection"){ - var sql = "select * from `ireg_$log`"; + var sql = "select * from `ireg_log`"; if(attr.date_from){ if (attr.date_till) sql += " where `date` >= ? and `date` <= ?"; @@ -6237,223 +6870,45 @@ function LogManager(){ return xml + ""; } } + }); } LogManager._extend(InfoRegManager); - -/** - * ### Абстрактный менеджер регистра накопления - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "AccumRegs"}}{{/crossLink}} - * - * @class AccumRegManager - * @extends RegisterManager - * @constructor - * @param class_name {string} - имя типа менеджера объекта. например, "areg.goods_on_stores" - */ -function AccumRegManager(class_name){ - - AccumRegManager.superclass.constructor.call(this, class_name); -} -AccumRegManager._extend(RegisterManager); - - - - -/** - * ### Абстрактный менеджер справочника - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Catalogs"}}{{/crossLink}} - * - * @class CatManager - * @extends RefDataManager - * @constructor - * @param class_name {string} - */ -function CatManager(class_name) { - - CatManager.superclass.constructor.call(this, class_name); - - // реквизиты по метаданным - if(this.metadata().hierarchical && this.metadata().group_hierarchy){ - - /** - * ### Признак "это группа" - * @property is_folder - * @for CatObj - * @type {Boolean} - */ - $p[this.obj_constructor()].prototype.__define("is_folder", { - get : function(){ return this._obj.is_folder || false}, - set : function(v){ this._obj.is_folder = $p.utils.fix_boolean(v)}, - enumerable: true, - configurable: true - }); - } - -} -CatManager._extend(RefDataManager); - -/** - * Возвращает объект по наименованию - * @method by_name - * @param name {String|Object} - искомое наименование - * @return {DataObj} - */ -CatManager.prototype.by_name = function(name){ - - var o; - - this.find_rows({name: name}, function (obj) { - o = obj; - return false; - }); - - if(!o) - o = this.get(); - - return o; -}; - -/** - * Возвращает объект по коду - * @method by_id - * @param id {String|Object} - искомый код - * @return {DataObj} - */ -CatManager.prototype.by_id = function(id){ - - var o; - - this.find_rows({id: id}, function (obj) { - o = obj; - return false; - }); - - if(!o) - o = this.get(); - - return o; -}; - -/** - * Для иерархических кешируемых справочников возвращает путь элемента - * @param ref {String|CatObj} - ссылка или объект данных - * @return {string} - строка пути элемента - */ -CatManager.prototype.path = function(ref){ - var res = [], tobj; - - if(ref instanceof DataObj) - tobj = ref; - else - tobj = this.get(ref, false, true); - if(tobj) - res.push({ref: tobj.ref, presentation: tobj.presentation}); - - if(tobj && this.metadata().hierarchical){ - while(true){ - tobj = tobj.parent; - if(tobj.empty()) - break; - res.push({ref: tobj.ref, presentation: tobj.presentation}); - } - } - return res; -}; - - - /** - * ### Абстрактный менеджер плана видов характеристик - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "ChartsOfCharacteristics"}}{{/crossLink}} - * - * @class ChartOfCharacteristicManager - * @extends CatManager - * @constructor - * @param class_name {string} + * ### Менеджер объектов метаданных + * Используется для формирования списков типов документов, справочников и т.д. + * Например, при работе в интерфейсе с составными типами */ -function ChartOfCharacteristicManager(class_name){ - - ChartOfCharacteristicManager.superclass.constructor.call(this, class_name); +function MetaObjManager() { + MetaObjManager.superclass.constructor.call(this, "cat.meta_objs"); } -ChartOfCharacteristicManager._extend(CatManager); +MetaObjManager._extend(CatManager); /** - * ### Абстрактный менеджер плана счетов - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "ChartsOfAccounts"}}{{/crossLink}} - * - * @class ChartOfAccountManager - * @extends CatManager - * @constructor - * @param class_name {string} + * ### Менеджер доступных полей + * Используется при настройке отчетов и динамических списков */ -function ChartOfAccountManager(class_name){ - - ChartOfAccountManager.superclass.constructor.call(this, class_name); +function MetaFieldManager() { + MetaFieldManager.superclass.constructor.call(this, "cat.meta_fields"); } -ChartOfAccountManager._extend(CatManager); +MetaFieldManager._extend(CatManager); /** - * ### Абстрактный менеджер документов - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Documents"}}{{/crossLink}} - * - * @class DocManager - * @extends RefDataManager - * @constructor - * @param class_name {string} + * ### Менеджер настроек отчетов и динсписков */ -function DocManager(class_name) { - - - DocManager.superclass.constructor.call(this, class_name); +function SchemeSettingsManager() { + SchemeSettingsManager.superclass.constructor.call(this, "cat.scheme_settings"); } -DocManager._extend(RefDataManager); +SchemeSettingsManager._extend(CatManager); -/** - * ### Абстрактный менеджер задач - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Tasks"}}{{/crossLink}} - * - * @class TaskManager - * @extends CatManager - * @constructor - * @param class_name {string} - */ -function TaskManager(class_name){ - - TaskManager.superclass.constructor.call(this, class_name); - -} -TaskManager._extend(CatManager); - -/** - * ### Абстрактный менеджер бизнес-процессов - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "BusinessProcesses"}}{{/crossLink}} - * - * @class BusinessProcessManager - * @extends CatManager - * @constructor - * @param class_name {string} - */ -function BusinessProcessManager(class_name){ - - BusinessProcessManager.superclass.constructor.call(this, class_name); - -} -BusinessProcessManager._extend(CatManager); /** diff --git a/dist/metadata.core.min.js b/dist/metadata.core.min.js index 7ba05646a..5f6731a25 100644 --- a/dist/metadata.core.min.js +++ b/dist/metadata.core.min.js @@ -1,12 +1,12 @@ /*! - metadata.js v0.11.223, built:2016-12-02 © Evgeniy Malyarov http://www.oknosoft.ru 2014-2016 + metadata.js v0.12.225, built:2016-12-03 © Evgeniy Malyarov http://www.oknosoft.ru 2014-2016 metadata.js may be freely distributed under the AGPL-3.0. To obtain _Oknosoft Commercial license_, contact info@oknosoft.ru */ -!function(e,t){"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?module.exports=t():e.$p=t()}(this,function(){function e(){this.__define({version:{value:"0.11.223",writable:!1},toString:{value:function(){return"Oknosoft data engine. v:"+this.version},writable:!1},utils:{value:new t},injected_data:{value:{},writable:!1},ajax:{value:new n,writable:!1},msg:{value:new a,writable:!1},wsql:{value:new r,writable:!1},eve:{value:new N,writable:!1},aes:{value:new T("metadata.js"),writable:!1},moment:{get:function(){return this.utils.moment}},_patch:{value:function(e,t){for(var n in t)"object"==typeof t[n]&&e[n]&&"object"==typeof e[n]?M._patch(e[n],t[n]):e[n]=t[n];return e}},_find:{value:function(e,t,n){var r,a,i;if("object"!=typeof t)for(a in e){r=e[a];for(var o in r)if("function"!=typeof r[o]&&M.utils.is_equal(r[o],t))return r}else for(a in e){r=e[a],i=!0;for(var o in t)if("function"!=typeof r[o]&&!M.utils.is_equal(r[o],t[o])){i=!1;break}if(i)return r}}},_selection:{value:function(e,t){var n,r,a,i=!0;if(t)if("function"==typeof t)i=t.call(this,e);else for(n in t)if(r=t[n],a="object"==typeof r,"_"!=n.substr(0,1))if("function"==typeof r){if(i=r.call(this,e,n),!i)break}else if("or"==n&&Array.isArray(r)){if(i=r.some(function(t){var n=Object.keys(t)[0];return t[n].hasOwnProperty("like")?e[n]&&e[n].toLowerCase().indexOf(t[n].like.toLowerCase())!=-1:M.utils.is_equal(e[n],t[n])}),!i)break}else if(a&&r.hasOwnProperty("like")){if(!e[n]||e[n].toLowerCase().indexOf(r.like.toLowerCase())==-1){i=!1;break}}else if(a&&r.hasOwnProperty("not")){if(M.utils.is_equal(e[n],r.not)){i=!1;break}}else if(a&&r.hasOwnProperty("in")){if(i=r.in.some(function(t){return M.utils.is_equal(t,e[n])}),!i)break}else if(a&&r.hasOwnProperty("lt")){if(i=e[n]r.gt,!i)break}else if(a&&r.hasOwnProperty("between")){var o=e[n];if("number"!=typeof o&&(o=M.utils.fix_date(e[n])),i=o>=r.between[0]&&o<=r.between[1],!i)break}else if(!M.utils.is_equal(e[n],r)){i=!1;break}return i}},_find_rows:{value:function(e,t,n){var r,a,i=[],o=0;t&&(t._top?(a=t._top,delete t._top):a=300);for(var s in e)if(r=e[s],M._selection.call(this,r,t)){if(n){if(n.call(this,r)===!1)break}else i.push(r);if(a&&(o++,o>=a))break}return i}},on:{value:function(e,t){if("object"!=typeof e)return this.eve.attachEvent(e,t);for(var n in e)e[n]._evnts||(e[n]._evnts=[]),e[n]._evnts.push(this.eve.attachEvent(n,e[n]))}},off:{value:function(e){"function"==typeof e&&e._evnts?e._evnts.forEach(function(e){M.eve.detachEvent(e)}):e?M.eve.detachEvent(e):M.eve.detachAllEvents()}},record_log:{value:function(e){M.ireg&&M.ireg.$log&&M.ireg.$log.record(e),console.log(e)}},md:{value:new o},enm:{value:new function(){this.toString=function(){return M.msg.meta_enn_mgr}}},cat:{value:new function(){this.toString=function(){return M.msg.meta_cat_mgr}}},doc:{value:new function(){this.toString=function(){return M.msg.meta_doc_mgr}}},ireg:{value:new function(){this.toString=function(){return M.msg.meta_ireg_mgr}}},areg:{value:new function(){this.toString=function(){return M.msg.meta_areg_mgr}}},accreg:{value:new function(){this.toString=function(){return M.msg.meta_accreg_mgr}}},dp:{value:new function(){this.toString=function(){return M.msg.meta_dp_mgr}}},rep:{value:new function(){this.toString=function(){return M.msg.meta_reports_mgr}}},cacc:{value:new function(){this.toString=function(){return M.msg.meta_charts_of_accounts_mgr}}},cch:{value:new function(){this.toString=function(){return M.msg.meta_charts_of_characteristic_mgr}}},tsk:{value:new function(){this.toString=function(){return M.msg.meta_task_mgr}}},bp:{value:new function(){this.toString=function(){return M.msg.meta_bp_mgr}}},DataManager:{value:s},RefDataManager:{value:_},DataProcessorsManager:{value:l},EnumManager:{value:u},RegisterManager:{value:c},InfoRegManager:{value:f},LogManager:{value:d},AccumRegManager:{value:p},CatManager:{value:h},ChartOfCharacteristicManager:{value:m},ChartOfAccountManager:{value:y},DocManager:{value:g},TaskManager:{value:b},BusinessProcessManager:{value:v},DataObj:{value:j},CatObj:{value:O},DocObj:{value:k},DataProcessorObj:{value:q},TaskObj:{value:A},BusinessProcessObj:{value:D},EnumObj:{value:R},RegisterRow:{value:P},TabularSection:{value:w},TabularSectionRow:{value:x}})}function t(){this.moment="function"==typeof moment?moment:require("moment"),this.moment._masks={date:"DD.MM.YY",date_time:"DD.MM.YYYY HH:mm",ldt:"DD MMMM YYYY, HH:mm",iso:"YYYY-MM-DDTHH:mm:ss"},this.fix_date=function(e,t){if(e instanceof Date)return e;var n=this.moment(e,["DD-MM-YYYY","DD-MM-YYYY HH:mm","DD-MM-YYYY HH:mm:ss","DD-MM-YY HH:mm","YYYYDDMMHHmmss",this.moment.ISO_8601]);return n.isValid()?n.toDate():t?this.blank.date:e},this.fix_guid=function(e,t){if(e&&"string"==typeof e);else{if(e instanceof j)return e.ref;if(e&&"object"==typeof e)if(e.presentation){if(e.ref)return e.ref;if(e.name)return e.name}else e="object"==typeof e.ref&&e.ref.hasOwnProperty("ref")?e.ref.ref:e.ref}return this.is_guid(e)||t===!1?e:t?this.generate_guid():this.blank.guid},this.fix_number=function(e,t){var n=parseFloat(e);return isNaN(n)?t?0:e:n},this.fix_boolean=function(e){return"string"==typeof e?!(!e||"false"==e.toLowerCase()):!!e},this.blank={date:this.fix_date("0001-01-01T00:00:00"),guid:"00000000-0000-0000-0000-000000000000",by_type:function(e){var t;return t=e.is_ref?this.guid:e.date_part?this.date:e.digits?0:(!e.types||"boolean"!=e.types[0])&&""}},this.fetch_type=function(e,t){var n=e;return t.is_ref?n=this.fix_guid(e):t.date_part?n=this.fix_date(e,!0):t.digits?n=this.fix_number(e,!0):"boolean"==t.types[0]&&(n=this.fix_boolean(e)),n},this.date_add_day=function(e,t,n){var r=new Date(e);return r.setDate(e.getDate()+t),n&&r.setHours(0,-r.getTimezoneOffset(),0,0),r},this.generate_guid=function(){var e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var n=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?n:7&n|8).toString(16)})},this.is_guid=function(e){return!("string"!=typeof e||e.length<36)&&(e.length>36&&(e=e.substr(0,36)),/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(e))},this.is_empty_guid=function(e){return!e||e===this.blank.guid},this.is_data_obj=function(e){return e&&e instanceof j},this.is_data_mgr=function(e){return e&&e instanceof s},this.is_equal=function(e,t){return e==t||typeof e!=typeof t&&this.fix_guid(e,!1)==this.fix_guid(t,!1)},this.blob_as_text=function(e,t){return new Promise(function(n,r){var a=new FileReader;a.onload=function(e){n(a.result)},a.onerror=function(e){r(e)},"data_url"==t?a.readAsDataURL(e):a.readAsText(e)})}}function n(){function e(e,t,n,r,a){return new Promise(function(i,o){if("undefined"==typeof window&&r&&r.request)r.request({url:encodeURI(t),headers:{Authorization:r.auth}},function(e,t,n){e?o(e):200!=t.statusCode?o({message:t.statusMessage,description:n,status:t.statusCode}):i({response:n})});else{var s=new XMLHttpRequest;if(window.dhx4&&window.dhx4.isIE&&(t=encodeURI(t)),r){var _,l;"object"==typeof r&&r.username&&r.hasOwnProperty("password")?(_=r.username,l=r.password):M.ajax.username&&M.ajax.authorized?(_=M.ajax.username,l=M.aes.Ctr.decrypt(M.ajax.password)):(_=M.wsql.get_user_param("user_name"),l=M.aes.Ctr.decrypt(M.wsql.get_user_param("user_pwd")),!_&&M.job_prm&&M.job_prm.guest_name&&(_=M.job_prm.guest_name,l=M.aes.Ctr.decrypt(M.job_prm.guest_pwd))),s.open(e,t,!0,_,l),s.withCredentials=!0,s.setRequestHeader("Authorization","Basic "+btoa(unescape(encodeURIComponent(_+":"+l))))}else s.open(e,t,!0);a&&a.call(this,s),"GET"!=e?this.hide_headers||r.hide_headers||(s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.setRequestHeader("X-Requested-With","XMLHttpRequest")):n=null,s.onload=function(){200==s.status&&(s.response instanceof Blob||"62135622e6?this.js_time_diff:e}},set_user_param:{value:function(t,r){var a=r;"object"==typeof r?a=JSON.stringify(r):r===!1&&(a=""),e.setItem(M.job_prm.local_storage_prefix+t,a),n[t]=r}},get_user_param:{value:function(t,r){return!n.hasOwnProperty(t)&&e&&(n[t]=this.fetch_type(e.getItem(M.job_prm.local_storage_prefix+t),r)),n[t]}},promise:{value:function(e,n){return new Promise(function(r,a){t.alasql(e,n||[],function(e,t){t?a(t):r(e)})})}},save_options:{value:function(e,n){return t.set_user_param(e+"_"+n.name,n)}},restore_options:{value:function(e,n){var r=t.get_user_param(e+"_"+n.name,"object");for(var a in r)if("object"!=typeof r[a])n[a]=r[a];else{n[a]||(n[a]={});for(var i in r[a])n[a][i]=r[a][i]}return n}},fetch_type:{value:function(e,t){if("object"==t){try{e=JSON.parse(e)}catch(t){e={}}return e}return"number"==t?M.utils.fix_number(e,!0):"date"==t?M.utils.fix_date(e,!0):"boolean"==t?M.utils.fix_boolean(e):e}},alasql:{value:"undefined"!=typeof alasql?alasql:require("alasql")},init_params:{value:function(){if(!M.job_prm.local_storage_prefix&&!M.job_prm.create_tables)return Promise.resolve();e="undefined"==typeof localStorage?"undefined"==typeof WorkerGlobalScope?new require("node-localstorage").LocalStorage("./localstorage"):{setItem:function(e,t){},getItem:function(e){}}:localStorage;var n,r=[{p:"user_name",v:"",t:"string"},{p:"user_pwd",v:"",t:"string"},{p:"browser_uid",v:M.utils.generate_guid(),t:"string"},{p:"zone",v:M.job_prm.hasOwnProperty("zone")?M.job_prm.zone:1,t:M.job_prm.zone_is_string?"string":"number"},{p:"enable_save_pwd",v:M.job_prm.enable_save_pwd,t:"boolean"},{p:"autologin",v:"",t:"boolean"},{p:"skin",v:"dhx_web",t:"string"},{p:"rest_path",v:"",t:"string"}];M.job_prm.additional_params&&(r=r.concat(M.job_prm.additional_params)),e.getItem(M.job_prm.local_storage_prefix+"zone")||(n=M.job_prm.hasOwnProperty("zone")?M.job_prm.zone:1),M.job_prm.url_prm.hasOwnProperty("zone")&&(n=M.job_prm.zone_is_string?M.job_prm.url_prm.zone:M.utils.fix_number(M.job_prm.url_prm.zone,!0)),void 0!==n&&t.set_user_param("zone",n),r.forEach(function(e){(void 0==t.get_user_param(e.p,e.t)||!t.get_user_param(e.p,e.t)&&e.p.indexOf("url")!=-1)&&t.set_user_param(e.p,M.job_prm.hasOwnProperty(e.p)?M.job_prm[e.p]:e.v)});var a={path:t.get_user_param("couch_path","string")||M.job_prm.couch_path||"",zone:t.get_user_param("zone","number"),prefix:M.job_prm.local_storage_prefix,suffix:t.get_user_param("couch_suffix","string")||"",user_node:M.job_prm.user_node,noreplicate:M.job_prm.noreplicate};a.path&&(t.__define("pouch",{value:new i}),t.pouch.init(a)),this.create_tables&&(this.alasq(this.create_tables,[]),this.create_tables="")}},drop_tables:{value:function(e){function n(){i--,i<=0?setTimeout(e,10):r()}function r(){var e=o[i-1].tableid;"_"==e.substr(0,1)?n():t.alasql("drop table IF EXISTS "+e,[],n)}function a(e){o=e,(i=e.length)?r():n()}var i=0,o=[];t.alasql("SHOW TABLES",[],a)}}}),this.__define({aladb:{value:new this.alasql.Database("md")}})}function a(){this.toString=function(){return"Интернационализация сообщений"},"undefined"!=typeof window&&"dhtmlx"in window&&(this.show_msg=function(e,t){if(e){if("string"==typeof e){if(M.iface.synctxt)return void M.iface.synctxt.show_message(e);e={type:"info",text:e}}t&&"function"==typeof t.setText&&t.setText(e.text),dhtmlx.message(e)}},this.check_soap_result=function(e){return e?"limit_query"==e.error?(M.iface.docs.progressOff(),M.msg.show_msg({type:"alert-warning",text:M.msg.limit_query.replace("%1",e.queries).replace("%2",e.queries_avalable),title:M.msg.srv_overload}),!0):"network"==e.error||"empty"==e.error?(M.iface.docs.progressOff(),M.msg.show_msg({type:"alert-warning",text:M.msg.error_network,title:M.msg.error_critical}),!0):e.error&&e.error_description?(M.iface.docs.progressOff(),e.error_description.indexOf("Недостаточно прав")!=-1&&(e.error_type="alert-warning",e.error_title=M.msg.error_rights),M.msg.show_msg({type:e.error_type||"alert-error",text:e.error_description,title:e.error_title||M.msg.error_critical}),!0):e.error&&!e.messages?(M.iface.docs.progressOff(),M.msg.show_msg({type:"alert-error",title:M.msg.error_critical,text:M.msg.unknown_error.replace("%1","unknown_error")}),!0):void 0:(M.msg.show_msg({type:"alert-error",text:M.msg.empty_response,title:M.msg.error_critical}),!0)},this.show_not_implemented=function(){M.msg.show_msg({type:"alert-warning",text:M.msg.not_implemented,title:M.msg.main_title})})}function i(){var e,t,n,r,a=this,i={};a.__define({DB:{value:"undefined"==typeof PouchDB?require("pouchdb-core").plugin(require("pouchdb-adapter-memory")).plugin(require("pouchdb-adapter-http")).plugin(require("pouchdb-replication")).plugin(require("pouchdb-mapreduce")):PouchDB},init:{value:function(e){i._mixin(e),i.path&&0!=i.path.indexOf("http")&&"undefined"!=typeof location&&(i.path=location.protocol+"//"+location.host+i.path)}},local:{get:function(){if(!e){var t={auto_compaction:!0,revs_limit:2};e={ram:new a.DB(i.prefix+i.zone+"_ram",t),doc:new a.DB(i.prefix+i.zone+"_doc",t),meta:new a.DB(i.prefix+"meta",t),sync:{}}}return i.path&&!e._meta&&(e._meta=new a.DB(i.path+"meta",{auth:{username:"guest",password:"meta"},skip_setup:!0}),a.run_sync(e.meta,e._meta,"meta")),e}},remote:{get:function(){return!t&&n&&(t={ram:new a.DB(i.path+i.zone+"_ram",{auth:{username:n.username,password:n.password},skip_setup:!0}),doc:new a.DB(i.path+i.zone+"_doc"+i.suffix,{auth:{username:n.username,password:n.password},skip_setup:!0})}),t}},log_in:{value:function(e,t){return void 0==e&&void 0==t&&(e=M.job_prm.guest_name,t=M.aes.Ctr.decrypt(M.job_prm.guest_pwd)),n?n.username==e?Promise.resolve():Promise.reject():M.ajax.get_ex(i.path+i.zone+"_ram",{username:e,password:t}).then(function(r){return n={username:e,password:t},setTimeout(function(){dhx4.callEvent("log_in",[e])}),{ram:a.run_sync(a.local.ram,a.remote.ram,"ram"),doc:a.run_sync(a.local.doc,a.remote.doc,"doc")}})}},log_out:{value:function(){if(n){if(e.sync.doc)try{e.sync.doc.cancel()}catch(e){}if(e.sync.ram)try{e.sync.ram.cancel()}catch(e){}n=null}t&&t.ram&&delete t.ram,t&&t.doc&&delete t.doc,t=null,dhx4.callEvent("log_out")}},reset_local_data:{value:function(){var e=a.local.ram.destroy.bind(a.local.ram),t=a.local.doc.destroy.bind(a.local.doc),n=function(){setTimeout(function(){M.eve.redirect=!0,location.reload(!0)},1e3)};a.log_out(),setTimeout(function(){e().then(t).catch(t).then(n).catch(n)},1e3)}},load_data:{value:function(){var e={limit:800,include_docs:!0},t={total_rows:0,limit:e.limit,page:0,start:Date.now()};return new Promise(function(n,i){function o(){a.local.ram.allDocs(e,function(s,_){_?(t.page++,t.total_rows=_.total_rows,t.duration=Date.now()-t.start,M.eve.callEvent("pouch_load_data_page",[t]),a.load_changes(_,e)?o():(n(),r=!0,M.eve.callEvent("pouch_load_data_loaded",[t]),t.note="pouch_load_data_loaded",M.record_log(t))):s&&(i(s),M.eve.callEvent("pouch_load_data_error",[s]))})}a.local.ram.info().then(function(e){e.doc_count>=(M.job_prm.pouch_ram_doc_count||10)?(M.eve.callEvent("pouch_load_data_start",[t]),o()):(M.eve.callEvent("pouch_load_data_error",[e]),i(e))})})}},authorized:{get:function(){return n&&n.username}},data_loaded:{get:function(){return!!r}},run_sync:{value:function(t,n,i){var o,s;return t.info().then(function(e){return o=e,n.info()}).then(function(e){return"ram"!=i?e:n.get("data_version").then(function(t){return t.version!=M.wsql.get_user_param("couch_ram_data_version")&&(M.wsql.get_user_param("couch_ram_data_version")&&(e=a.reset_local_data()),M.wsql.set_user_param("couch_ram_data_version",t.version)),e}).catch(function(e){M.record_log(e)}).then(function(){return e})}).then(function(_){if(_){"ram"==i&&o.doc_count<(M.job_prm.pouch_ram_doc_count||10)?(s={total_rows:_.doc_count,local_rows:o.doc_count,docs_written:0,limit:200,page:0,start:Date.now()},M.eve.callEvent("pouch_load_data_start",[s])):"doc"==i&&setTimeout(function(){M.eve.callEvent("pouch_doc_sync_start")});var l={live:!0,retry:!0,batch_size:300,batches_limit:8};return"meta"==i?l.filter="auth/meta":M.job_prm.pouch_filter&&M.job_prm.pouch_filter[i]&&(l.filter=M.job_prm.pouch_filter[i]),"ram"==i||"meta"==i||M.wsql.get_user_param("zone")==M.job_prm.zone_demo?e.sync[i]=t.replicate.from(n,l):e.sync[i]=t.sync(n,l),e.sync[i].on("change",function(e){"ram"==i?(a.load_changes(e),o.doc_count<(M.job_prm.pouch_ram_doc_count||10)&&(s.page++,s.docs_written=e.docs_written,s.duration=Date.now()-s.start,M.eve.callEvent("pouch_load_data_page",[s]),s.docs_written>=s.total_rows&&(r=!0,M.eve.callEvent("pouch_load_data_loaded",[s]),s.note="pouch_load_data_loaded",M.record_log(s)))):(e.update_only=!0,a.load_changes(e)),M.eve.callEvent("pouch_change",[i,e])}).on("paused",function(e){e&&M.eve.callEvent("pouch_paused",[i,e])}).on("active",function(e){M.eve.callEvent("pouch_active",[i,e])}).on("denied",function(e){M.eve.callEvent("pouch_denied",[i,e])}).on("complete",function(e){M.eve.callEvent("pouch_complete",[i,e])}).on("error",function(e){M.eve.callEvent("pouch_error",[i,e])}),e.sync[i]}})}},load_obj:{value:function(e){return e._manager.pouch_db.get(e._manager.class_name+"|"+e.ref).then(function(t){delete t._id,delete t._rev,e._mixin(t)._set_loaded()}).catch(function(e){if(404!=e.status)throw e}).then(function(t){return e})}},save_obj:{value:function(e,t){var n=e._obj._clone(),r=t.db||e._manager.pouch_db;return n._id=e._manager.class_name+"|"+e.ref,delete n.ref,t.attachments&&(n._attachments=t.attachments),(e.is_new()?Promise.resolve():r.get(n._id)).then(function(e){if(e){n._rev=e._rev;for(var t in e._attachments)n._attachments||(n._attachments={}),n._attachments[t]||(n._attachments[t]=e._attachments[t])}}).catch(function(e){if(404!=e.status)throw e}).then(function(){return r.put(n)}).then(function(){if(e.is_new()&&e._set_loaded(e.ref),n._attachments){e._attachments||(e._attachments={});for(var r in n._attachments)e._attachments[r]&&n._attachments[r].stub||(e._attachments[r]=n._attachments[r])}return n=null,t=null,e})}},load_changes:{value:function(e,t){var n,r,a,i,o={};if(t)n=e.rows;else if(e.direction){if("pull"!=e.direction)return;n=e.change.docs}else n=e.docs;if(n.length>0){t&&(t.startkey=n[n.length-1].key,t.skip=1),n.forEach(function(e){if(r=t?e.doc:e,!r)if(e.value&&e.value.deleted)r={_id:e.id,_deleted:!0};else if(e.error)return;i=r._id.split("|"),a=i[0].split("."),r.ref=i[1],delete r._id,delete r._rev,o[a[0]]||(o[a[0]]={}),o[a[0]][a[1]]||(o[a[0]][a[1]]=[]),o[a[0]][a[1]].push(r)});for(var s in o)for(a in o[s])M[s]&&M[s][a]&&M[s][a].load_array(o[s][a],!e.update_only||"update_only");return o=e=n=r=null,!0}return!1}},backup_database:{value:function(e){}},restore_database:{value:function(e){}}})}function o(){function e(e){return e.info().then(function(){return e.get("meta")}).then(function(n){return t=n,n=null,e.get("meta_patch")}).then(function(e){return M._patch(t,e),e=null,delete t._id,delete t._rev,t})}var t;_md=this,_md.create_managers=function(){},_md.init=function(n){function r(){return!n||a||i?e(n||M.wsql.pouch.local.meta).then(function(){return a?void _md.create_managers():t}).catch(M.record_log):(t=n,n=null,_md.create_managers(),void 0)}var a=!n||M.wsql.pouch&&n==M.wsql.pouch.local.meta,i=n&&M.wsql.pouch&&n==M.wsql.pouch.local._meta;return M.on("pouch_change",function(e,n){"meta"==e&&(t?setTimeout(function(){M.iface.do_reload()},3e3):r())}),r()},_md.get=function(e,n){var r=e.split(".");if(!n)return t[r[0]][r[1]];var a={multiline_mode:!1,note:"",synonym:"",tooltip:"",type:{is_ref:!1,types:["string"]}},i="doc,tsk,bp".indexOf(r[0])!=-1,o="cat,cch,cacc,tsk".indexOf(r[0])!=-1;return i&&"number_doc"==n?(a.synonym="Номер",a.tooltip="Номер документа",a.type.str_len=11):i&&"date"==n?(a.synonym="Дата",a.tooltip="Дата документа",a.type.date_part="date_time",a.type.types[0]="date"):i&&"posted"==n?(a.synonym="Проведен",a.type.types[0]="boolean"):o&&"id"==n?a.synonym="Код":o&&"name"==n?a.synonym="Наименование":"_deleted"==n?(a.synonym="Пометка удаления",a.type.types[0]="boolean"):"is_folder"==n?(a.synonym="Это группа",a.type.types[0]="boolean"):"ref"==n?(a.synonym="Ссылка",a.type.is_ref=!0,a.type.types[0]=e):a=n?t[r[0]][r[1]].fields[n]:t[r[0]][r[1]],a},_md.get_classes=function(){var e={};for(var n in t){e[n]=[];for(var r in t[n])e[n].push(r)}return e},_md.sql_type=function(e,t,n,r){var a;return a="type"==t&&"cch_properties"==e.table_name||"svg"==t&&"cat_production_params"==e.table_name?" JSON":n.is_ref||n.types.indexOf("guid")!=-1?r?n.types.every(function(e){return 0==e.indexOf("enm.")})?" character varying(100)":n.hasOwnProperty("str_len")?" character varying("+Math.max(36,n.str_len)+")":" uuid":" CHAR":n.hasOwnProperty("str_len")?r?n.str_len?" character varying("+n.str_len+")":" text":" CHAR":n.date_part?r&&"date"!=n.date_part?"date_time"==n.date_part?" timestamp with time zone":" time without time zone":" Date":n.hasOwnProperty("digits")?0==n.fraction_figits?r?n.digits<7?" integer":" bigint":" INT":r?" numeric("+n.digits+","+n.fraction_figits+")":" FLOAT":n.types.indexOf("boolean")!=-1?" BOOLEAN":n.types.indexOf("json")!=-1?" JSON":r?" character varying(255)":" CHAR"},_md.sql_composite=function(e,t,n,r){var a="";return e[t].type.types.length>1&&"type"!=t&&(n=n?n.substr(0,29)+"_T":t.substr(0,29)+"_T",a=r?', "'+n+'" character varying(255)':_md.sql_mask(n)+" CHAR"),a},_md.sql_mask=function(e,t){return", "+(t?"_t_.":"")+("`"+e+"`")},_md.mgr_by_class_name=function(e){if(e){var t=e.split(".");if(t[1]&&M[t[0]])return M[t[0]][t[1]]}},_md.value_mgr=function(e,t,n,r,a){function i(e){return e&&1==n.types.length&&(n._mgr=e),e}var o,s,_,l,u;if(n._mgr)return n._mgr;if(1==n.types.length){if(_=n.types[0].split("."),_.length>1&&M[_[0]])return i(M[_[0]][_[1]])}else if(a&&a.type&&(_=a.type.split("."),_.length>1&&M[_[0]]))return i(M[_[0]][_[1]]);if(o=e.property||e.param,"value"==t&&o){if(M.utils.is_data_obj(o))s=o;else{if(!M.utils.is_guid(o))return;s=M.cch.properties.get(o,!1)}if(M.utils.is_data_obj(s)){if(s.is_new())return M.cat.property_values;if(l=[],s.type.types.forEach(function(e){_=e.split("."),_.length>1&&M[_[0]][_[1]]&&l.push(M[_[0]][_[1]])}),1==l.length||e[t]==M.utils.blank.guid)return i(l[0]);if(r)return l;if((o=e[t])instanceof j)return o._manager;if(M.utils.is_guid(o)&&o!=M.utils.blank.guid)for(var c in l)if(u=l[c],u.get(o,!1,!0))return u}}else{if(l=[],n.types.forEach(function(e){_=e.split("."),_.length>1&&M[_[0]][_[1]]&&l.push(M[_[0]][_[1]])}),1==l.length||e[t]==M.utils.blank.guid)return i(l[0]);if(r)return l;if((o=e[t])instanceof j)return o._manager;if(M.utils.is_guid(o)&&o!=M.utils.blank.guid)for(var c in l)if(u=l[c],u.get(o,!1,!0))return u}},_md.control_by_type=function(e,t){var n;return n="boolean"==typeof t&&e.types.indexOf("boolean")!=-1?"ch":"number"==typeof t&&e.digits?e.fraction_figits<5?"calck":"edn":t instanceof Date&&e.date_part?"dhxCalendar":e.is_ref?"ocombo":e.date_part?"dhxCalendar":e.digits?e.fraction_figits<5?"calck":"edn":"boolean"==e.types[0]?"ch":e.hasOwnProperty("str_len")&&(e.str_len>=100||0==e.str_len)?"txt":"ed"},_md.ts_captions=function(e,t,n){n||(n={});var r,a=_md.get(e).tabular_sections[t],i=_md.get(e).form,o=a.fields;if(i&&i.obj){if(!i.obj.tabular_sections[t])return;n._mixin(i.obj.tabular_sections[t])}else{"contact_information"===t&&(o={type:"",kind:"",presentation:""}),n.fields=["row"],n.headers="№",n.widths="40",n.min_widths="",n.aligns="",n.sortings="na",n.types="cntr";for(var s in o)r=a.fields[s],r.hide||(n.fields.push(s),n.headers+=","+(r.synonym?r.synonym.replace(/,/g," "):s),n.types+=","+_md.control_by_type(r.type),n.sortings+=",na")}return!0},_md.syns_js=function(e){var n={DeletionMark:"_deleted",Description:"name",DataVersion:"data_version",IsFolder:"is_folder",Number:"number_doc",Date:"date","Дата":"date",Posted:"posted",Code:"id",Parent_Key:"parent",Owner_Key:"owner",Owner:"owner",Ref_Key:"ref","Ссылка":"ref",LineNumber:"row"};return n[e]?n[e]:t.syns_js[t.syns_1с.indexOf(e)]||e},_md.syns_1с=function(e){var n={_deleted:"DeletionMark",name:"Description",is_folder:"IsFolder",number_doc:"Number",date:"Date",posted:"Posted",id:"Code",ref:"Ref_Key",parent:"Parent_Key",owner:"Owner_Key",row:"LineNumber"};return n[e]?n[e]:t.syns_1с[t.syns_js.indexOf(e)]||e},_md.printing_plates=function(e){if(e)for(var n in e.doc)t.doc[n].printing_plates=e.doc[n]},_md.class_name_from_1c=function(e){var t=e.split(".");return 1==t.length?"enm."+e:("Перечисление"==t[0]?e="enm.":"Справочник"==t[0]?e="cat.":"Документ"==t[0]?e="doc.":"РегистрСведений"==t[0]?e="ireg.":"РегистрНакопления"==t[0]?e="areg.":"РегистрБухгалтерии"==t[0]?e="accreg.":"ПланВидовХарактеристик"==t[0]?e="cch.":"ПланСчетов"==t[0]?e="cacc.":"Обработка"==t[0]?e="dp.":"Отчет"==t[0]&&(e="rep."),e+_md.syns_js(t[1]))},_md.class_name_to_1c=function(e){var t=e.split(".");return 1==t.length?"Перечисление."+e:("enm"==t[0]?e="Перечисление.":"cat"==t[0]?e="Справочник.":"doc"==t[0]?e="Документ.":"ireg"==t[0]?e="РегистрСведений.":"areg"==t[0]?e="РегистрНакопления.":"accreg"==t[0]?e="РегистрБухгалтерии.":"cch"==t[0]?e="ПланВидовХарактеристик.":"cacc"==t[0]?e="ПланСчетов.":"dp"==t[0]?e="Обработка.":"rep"==t[0]&&(e="Отчет."),e+_md.syns_1с(t[1]))},_md.create_tables=function(e,t){function n(){i--,0==i?e?e(_):alasql.utils.saveFile("create_tables.sql",_):r()}function r(){var e=o[i-1];_+=e.class[e.name].get_sql_struct(t)+"; ",n()}var a,i=0,o=[],s=_md.get_classes(),_=t&&t.postgres?"":"USE md; ";"enm,cch,cacc,cat,bp,tsk,doc,ireg,areg".split(",").forEach(function(e){for(a in s[e])o.push({class:M[e],name:s[e][a]})}),i=o.length,r()}}function s(e){var t=_md.get(e),n={after_create:[],after_load:[],before_save:[],after_save:[],value_change:[],add_row:[],del_row:[]};this.__define({cachable:{get:function(){return e.indexOf("enm.")!=-1?"ram":t.cachable?t.cachable:e.indexOf("doc.")!=-1||e.indexOf("dp.")!=-1||e.indexOf("rep.")!=-1?"doc":"ram"}},class_name:{value:e,writable:!1},alatable:{get:function(){return M.wsql.aladb.tables[this.table_name]?M.wsql.aladb.tables[this.table_name].data:[]}},metadata:{value:function(e){return e?t.fields[e]||t.tabular_sections[e]:t}},on:{value:function(e,t){if("object"==typeof e)for(var r in e)e.hasOwnProperty(r)&&n[r].push(e[r]);else n[e].push(t)}},off:{value:function(e,t){}},handle_event:{value:function(e,t,r){var a,i=[];return n[t].forEach(function(t){i!==!1&&(a=t.call(e,r),a===!1?i=a:a&&i.push(a))}),i===!1?i:i.length?1==i.length?i[0]:i.some(function(e){return"object"==typeof e&&e.then})?Promise.all(i):i:void 0}},by_ref:{value:{}}})}function _(e){_.superclass.constructor.call(this,e)}function l(e){l.superclass.constructor.call(this,e)}function u(e){u.superclass.constructor.call(this,e);var t=M.md.get(e);for(var n in t)new R(t[n],this)}function c(e){c.superclass.constructor.call(this,e),this.push=function(e,t){t&&t!=e.ref?(delete this.by_ref[e.ref],this.by_ref[t]=e):this.by_ref[e.ref]=e},this.get=function(e,t,n){if(e?"string"==typeof e&&(e={ref:e}):e={},e.ref&&n)return t?Promise.resolve(this.by_ref[e.ref]):this.by_ref[e.ref];e.action="select";var r,a=M.wsql.alasql(this.get_sql_struct(e),e._values);if(delete e.action,delete e._values,a.length)if(n)r=this.by_ref[this.get_ref(a[0])];else{r=[];for(var i in a)r.push(this.by_ref[this.get_ref(a[i])])}return t?Promise.resolve(r):r},this.unload_obj=function(e){delete this.by_ref[e],this.alatable.some(function(t,n,r){if(t.ref==e)return r.splice(n,1),!0})},this.load_array=function(e,t){for(var n,r,a=[],i=0;i= ? and `date` <= ?":" where `date` >= ?":e.date_till&&(t+=" where `date` <= ?"),t}return d.superclass.get_sql_struct.call(this,e)}},caption_flds:{value:function(e){var t='%6',n=[],r="";if(n.push(new Col_struct("date","200","ro","left","server","Дата")),n.push(new Col_struct("class","100","ro","left","server","Класс")),n.push(new Col_struct("note","*","ro","left","server","Событие")),e.get_header){r="";for(var a in n)r+=t.replace("%1",n[a].id).replace("%2",n[a].width).replace("%3",n[a].type).replace("%4",n[a].align).replace("%5",n[a].sort).replace("%6",n[a].caption);r+=""}return{head:r,acols:n}}},data_to_grid:{value:function(e,t){var n="".replace("%1",e.length).replace("%2",t.start).replace("%3",t.set_parent||""),r=this.caption_flds(t);return n+=r.head,e.forEach(function(e){n+=''+M.moment(e.date-M.wsql.time_diff).format("DD.MM.YYYY HH:mm:ss")+"."+e.sequence+""+(e.class||"")+""+(e.note||"")+""}),n+""}}})}function p(e){p.superclass.constructor.call(this,e)}function h(e){h.superclass.constructor.call(this,e), -this.metadata().hierarchical&&this.metadata().group_hierarchy&&M[this.obj_constructor()].prototype.__define("is_folder",{get:function(){return this._obj.is_folder||!1},set:function(e){this._obj.is_folder=M.utils.fix_boolean(e)},enumerable:!0,configurable:!0})}function m(e){m.superclass.constructor.call(this,e)}function y(e){y.superclass.constructor.call(this,e)}function g(e){g.superclass.constructor.call(this,e)}function b(e){b.superclass.constructor.call(this,e)}function v(e){v.superclass.constructor.call(this,e)}function w(e,t){t._obj[e]||(t._obj[e]=[]),this.__define("_name",{value:e,enumerable:!1}),this.__define("_owner",{value:t,enumerable:!1}),this.__define("_obj",{value:t._obj[e],writable:!1,enumerable:!1})}function x(e){var t={};this.__define("_owner",{value:e,enumerable:!1}),this.__define("_obj",{value:t,writable:!1,enumerable:!1})}function j(e,t){var n,r={},a={},i={_is_new:!(this instanceof R)};return t instanceof l||t instanceof u||(n=t.get(e,!1,!0)),n?(e=null,n):(t instanceof u?a.ref=e.name:t instanceof c?a.ref=t.get_ref(e):a.ref=M.utils.fix_guid(e),this.__define({_obj:{value:a,configurable:!0},_ts_:{value:function(e){return r[e]||(r[e]=new w(e,this)),r[e]},configurable:!0},_manager:{value:t},_data:{value:i,configurable:!0}}),t.alatable&&t.push&&(t.alatable.push(a),t.push(this,a.ref)),void(e=null))}function O(e,t){var n="";O.superclass.constructor.call(this,e,t),this.__define("presentation",{get:function(){return this.name||this.id?this.name||this.id||this._metadata.obj_presentation||this._metadata.synonym:n},set:function(e){e&&(n=String(e))}}),e&&"object"==typeof e&&(e._not_set_loaded?(delete e._not_set_loaded,this._mixin(e)):(this._mixin(e),M.utils.is_empty_guid(this.ref)||!e.id&&!e.name||this._set_loaded(this.ref))),e=null}function k(e,t){var n="";k.superclass.constructor.call(this,e,t),this.__define("presentation",{get:function(){return this.number_doc?(this._metadata.obj_presentation||this._metadata.synonym)+" №"+this.number_doc+" от "+M.moment(this.date).format(M.moment._masks.ldt):n},set:function(e){e&&(n=String(e))}}),e&&"object"==typeof e&&this._mixin(e),!M.utils.is_empty_guid(this.ref)&&e.number_doc&&this._set_loaded(this.ref),e=null}function E(e){e.__define({number_doc:{get:function(){return this._obj.number_doc||""},set:function(e){this.__notify("number_doc"),this._obj.number_doc=e},enumerable:!0},date:{get:function(){return this._obj.date||M.utils.blank.date},set:function(e){this.__notify("date"),this._obj.date=M.utils.fix_date(e,!0)},enumerable:!0}})}function q(e,t){q.superclass.constructor.call(this,e,t);var n,r=t.metadata();for(n in r.fields)e[n]=M.utils.fetch_type("",r.fields[n].type);for(n in r.tabular_sections)e[n]=[];this._mixin(e)}function A(e,t){A.superclass.constructor.call(this,e,t)}function D(e,t){D.superclass.constructor.call(this,e,t)}function R(e,t){R.superclass.constructor.call(this,e,t),e&&"object"==typeof e&&this._mixin(e)}function P(e,t){P.superclass.constructor.call(this,e,t),e&&"object"==typeof e&&this._mixin(e);for(var n in t.metadata().dimensions)if(!e.hasOwnProperty(n)&&e.ref){var r=e.ref.split("¶");Object.keys(t.metadata().dimensions).forEach(function(e,t){this[e]=r[t]}.bind(this));break}}function S(){this.filter_date=function(e,t,n){t||(t=new Date("2015-01-01"));var r=e+" gt datetime'"+M.moment(t).format(M.moment._masks.iso)+"'";return n&&(r+=" and "+e+" lt datetime'"+M.moment(n).format(M.moment._masks.iso)+"'"),r},this.to_data=function(e,t){var n,r,a,i,o,s,l={},u=t.metadata(),c=u.fields,f=u.tabular_sections;t instanceof _?(e.hasOwnProperty("DeletionMark")&&(l._deleted=e.DeletionMark),e.hasOwnProperty("DataVersion"),e.hasOwnProperty("Ref_Key")&&(l.ref=e.Ref_Key)):c={}._mixin(u.dimensions)._mixin(u.resources)._mixin(u.attributes),t instanceof g?(e.hasOwnProperty("Number")?l.number_doc=e.Number||e.number_doc:e.hasOwnProperty("number_doc")&&(l.number_doc=e.number_doc),e.hasOwnProperty("Date")?l.date=e.Date:e.hasOwnProperty("date")&&(l.date=e.date),e.hasOwnProperty("Posted")?l.posted=e.Posted:e.hasOwnProperty("posted")&&(l.posted=e.posted)):(u.main_presentation_name&&(e.hasOwnProperty("Description")?l.name=e.Description:e.hasOwnProperty("name")&&(l.name=e.name)),u.code_length&&(e.hasOwnProperty("Code")?l.id=e.Code:e.hasOwnProperty("id")&&(l.id=e.id)));for(r in c)if(e.hasOwnProperty(r))l[r]=e[r];else{if(o=_md.syns_1с(r),o.indexOf("_Key")==-1&&c[r].type.is_ref&&e[o+"_Key"]&&(o+="_Key"),!e.hasOwnProperty(o))continue;l[r]=e[o]}for(n in f)s="extra_fields"==n||e.hasOwnProperty(n)?n:_md.syns_1с(n),e.hasOwnProperty(s)&&(l[n]=[],e[s]&&(e[s].sort(function(e,t){return(e.LineNumber||e.row)>(t.LineNumber||t.row)}),e[s].forEach(function(e){i={};for(a in f[n].fields)o=e.hasOwnProperty(a)||"extra_fields"==n&&("property"==a||"value"==a)?a:_md.syns_1с(a),o.indexOf("_Key")==-1&&f[n].fields[a].type.is_ref&&e[o+"_Key"]&&(o+="_Key"),i[a]=e[o];l[n].push(i)})));return l},this.ajax_to_data=function(e,t){return M.ajax.get_ex(e.url,e).then(function(e){return JSON.parse(e.response)}).then(function(e){var n=[];return e.value.forEach(function(e){n.push(L.to_data(e,t))}),n})},this.build_select=function(e,t){function n(e,r){"function"==typeof r?i+=r(t,e):(o=_md.syns_1с(e),s=_md.get(t.class_name,e),s&&(s=s.type,s.is_ref&&o.indexOf("_Key")==-1&&s.types.length&&s.types[0].indexOf("enm.")==-1&&(o+="_Key"),s.types.length&&(["boolean","number"].indexOf(typeof r)!=-1?i+=o+" eq "+r:s.is_ref&&"object"!=typeof r||r instanceof j?i+=o+" eq guid'"+r+"'":"string"==typeof r?i+=o+" eq '"+r+"'":"object"==typeof r&&(r.hasOwnProperty("like")?i+=o+" like '%"+r.like+"%'":r.hasOwnProperty("not")?i+=" not ("+n(e,r.not)+") ":r.hasOwnProperty("in")&&(i+=o+" in ("+(s.is_ref?r.in.map(function(e){return"guid'"+e+"'"}).join(","):r.in.join(","))+") ")))))}function r(e){for(var t in e)if(i?i+=" and ":i="&$filter=","or"==t&&Array.isArray(e[t])){var r=!0;e[t].forEach(function(e){r?(i+=" ( ",r=!1):i+=" or ";var t=Object.keys(e)[0];n(t,e[t])}),i+=" ) "}else n(t,e[t])}var a,i,o,s,_="";e||(e={}),e.fields&&(e.fields.forEach(function(e){"ref"==e?o="Ref_Key":(o=_md.syns_1с(e),s=_md.get(t.class_name,e).type,s.is_ref&&o.indexOf("_Key")==-1&&s.types.length&&s.types[0].indexOf("enm.")==-1&&(o+="_Key")),a?a+=",":a="&$select=",a+=o}),_+=a),e.selection&&("function"==typeof e.selection||(Array.isArray(e.selection)?e.selection.forEach(r):r(e.selection)),i&&(_+=i)),M.job_prm.rest&&t.rest_name.indexOf("Module_")==-1&&t.rest_name.indexOf("DataProcessor_")==-1&&t.rest_name.indexOf("Report_")==-1&&_.indexOf(" like ")==-1&&_.indexOf(" in ")==-1&&!t.metadata().irest?M.ajax.default_attr(e,M.job_prm.rest_url()):M.ajax.default_attr(e,M.job_prm.irest_url()),e.url+=t.rest_name+"?allowedOnly=true&$format=json&$top="+(e.top||300)+_},this.load_array=function(e,t){return L.build_select(e,t),L.ajax_to_data(e,t)},this.load_obj=function(e){var t={};return M.ajax.default_attr(t,!e._metadata.irest&&M.job_prm.rest?M.job_prm.rest_url():M.job_prm.irest_url()),t.url+=e._manager.rest_name+"(guid'"+e.ref+"')?$format=json",M.ajax.get_ex(t.url,t).then(function(e){return JSON.parse(e.response)}).then(function(t){return e._mixin(L.to_data(t,e._manager))._set_loaded(),e}).catch(function(t){return 404==t.status?e:void M.record_log(t)})},this.save_irest=function(e,t){var n=JSON.stringify(e),r=(void 0!=t.post?",post="+t.post:"")+(void 0!=t.operational?",operational="+t.operational:"");return M.ajax.default_attr(t,M.job_prm.irest_url()),t.url+=e._manager.rest_name+"(guid'"+e.ref+"'"+r+")",M.ajax.post_ex(t.url,n,t).then(function(e){return JSON.parse(e.response)}).then(function(t){return e._mixin(t)})},this.save_rest=function(e,t){var n,r=e.to_atom();return M.ajax.default_attr(t,M.job_prm.rest_url()),n=t.url+e._manager.rest_name,t.url=n+"(guid'"+e.ref+"')?$format=json&$select=Ref_Key,DeletionMark",M.ajax.get_ex(t.url,t).catch(function(e){return 404==e.status?{response:JSON.stringify({is_new:!0})}:Promise.reject(e)}).then(function(e){return JSON.parse(e.response)}).then(function(a){return a.is_new?M.ajax.post_ex(n,r,t):M.ajax.patch_ex(n+"(guid'"+e.ref+"')",r,t)}).then(function(t){var n=xmlToJSON.parseString(t.response,{mergeCDATA:!1,grokAttr:!0,grokText:!1,normalize:!0,xmlns:!1,namespaceKey:"_ns",textKey:"_text",valueKey:"_value",attrKey:"_attr",cdataKey:"_cdata",attrsAsObject:!1,stripAttrPrefix:!0,stripElemPrefix:!0,childrenAsArray:!1});if(n.entry&&n.entry.content&&n.entry.updated){var r,a=n.entry.content.properties,i={};for(var o in a)if(0!=o.indexOf("_"))if(r=a[o].element)if(i[o]=[],Array.isArray(r))for(var s in r){i[o][s]={};for(var _ in r[s])0!=_.indexOf("_")&&(i[o][s][_]="false"!==r[s][_]._text&&r[s][_]._text)}else{i[o][0]={};for(var _ in r)0!=_.indexOf("_")&&(i[o][0][_]="false"!==r[_]._text&&r[_]._text)}else i[o]="false"!==a[o]._text&&a[o]._text;return L.to_data(i,e._manager)}}).then(function(t){return e._mixin(t)})}}function N(){if(this.__define({init:{value:function(){M.__define("job_prm",{value:new C,writable:!1}),M.wsql.init_params()}},do_eventable:{value:function(e){function t(e,t){e=String(e).toLowerCase(),this._evnts.data[e]||(this._evnts.data[e]={});var n=M.utils.generate_guid();return this._evnts.data[e][n]=t,n}function n(e){if(!e)return r.call(this);for(var t in this._evnts.data){var n=0;for(var a in this._evnts.data[t])a==e?(this._evnts.data[t][a]=null,delete this._evnts.data[t][a]):n++;0==n&&(this._evnts.data[t]=null,delete this._evnts.data[t])}}function r(){for(var e in this._evnts.data){for(var t in this._evnts.data[e])this._evnts.data[e][t]=null,delete this._evnts.data[e][t];this._evnts.data[e]=null,delete this._evnts.data[e]}}function a(e,t){if(e=String(e).toLowerCase(),null==this._evnts.data[e])return!0;var n=!0;for(var r in this._evnts.data[e])n=this._evnts.data[e][r].apply(this,t)&&n;return n}function i(){for(var e in this._evnts.evnts){var t=this._evnts.evnts[e].length;if(t){for(var n=0;n2){t=decodeURI(e).split("&");for(var a in t)if(r=t[a].split("="),"m"==r[0])try{n[r[0]]=JSON.parse(r[1])}catch(e){n[r[0]]={}}else n[r[0]]=r[1]||""}return n}return e(location.search)._mixin(e(location.hash))}this.__define({parse_url:{value:t},offline:{value:!1,writable:!0},local_storage_prefix:{value:"",writable:!0},create_tables:{value:!0,writable:!0},url_prm:{value:"undefined"!=typeof window?t():{}},rest_url:{value:function(){var t=e(),n=M.wsql.get_user_param("zone",M.job_prm.zone_is_string?"string":"number");return n?t.replace("%1",n):t.replace("%1/","")}},irest_url:{value:function(){var t=e(),n=M.wsql.get_user_param("zone",M.job_prm.zone_is_string?"string":"number");return t=t.replace("odata/standard.odata","hs/rest"),n?t.replace("%1",n):t.replace("%1/","")}}}),M.eve.callEvent("settings",[this]);for(var n in this)"url_prm"!==n&&"function"!=typeof this[n]&&this.url_prm.hasOwnProperty[n]&&(this[n]=this.url_prm[n])}/** +!function(e,t){"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?module.exports=t():e.$p=t()}(this,function(){function e(){this.__define({version:{value:"0.12.225",writable:!1},toString:{value:function(){return"Oknosoft data engine. v:"+this.version},writable:!1},utils:{value:new t},injected_data:{value:{},writable:!1},ajax:{value:new n,writable:!1},msg:{value:new a,writable:!1},wsql:{value:new r,writable:!1},eve:{value:new M,writable:!1},aes:{value:new I("metadata.js"),writable:!1},moment:{get:function(){return this.utils.moment}},_patch:{value:function(e,t){for(var n in t)"object"==typeof t[n]&&e[n]&&"object"==typeof e[n]?K._patch(e[n],t[n]):e[n]=t[n];return e}},_find:{value:function(e,t,n){var r,a,i;if("object"!=typeof t)for(a in e){r=e[a];for(var o in r)if("function"!=typeof r[o]&&K.utils.is_equal(r[o],t))return r}else for(a in e){r=e[a],i=!0;for(var o in t)if("function"!=typeof r[o]&&!K.utils.is_equal(r[o],t[o])){i=!1;break}if(i)return r}}},_selection:{value:function(e,t){var n,r,a,i=!0;if(t)if("function"==typeof t)i=t.call(this,e);else for(n in t)if(r=t[n],a="object"==typeof r,"_"!=n.substr(0,1))if("function"==typeof r){if(i=r.call(this,e,n),!i)break}else if("or"==n&&Array.isArray(r)){if(i=r.some(function(t){var n=Object.keys(t)[0];return t[n].hasOwnProperty("like")?e[n]&&e[n].toLowerCase().indexOf(t[n].like.toLowerCase())!=-1:K.utils.is_equal(e[n],t[n])}),!i)break}else if(a&&r.hasOwnProperty("like")){if(!e[n]||e[n].toLowerCase().indexOf(r.like.toLowerCase())==-1){i=!1;break}}else if(a&&r.hasOwnProperty("not")){if(K.utils.is_equal(e[n],r.not)){i=!1;break}}else if(a&&r.hasOwnProperty("in")){if(i=r.in.some(function(t){return K.utils.is_equal(t,e[n])}),!i)break}else if(a&&r.hasOwnProperty("lt")){if(i=e[n]r.gt,!i)break}else if(a&&r.hasOwnProperty("between")){var o=e[n];if("number"!=typeof o&&(o=K.utils.fix_date(e[n])),i=o>=r.between[0]&&o<=r.between[1],!i)break}else if(!K.utils.is_equal(e[n],r)){i=!1;break}return i}},_find_rows:{value:function(e,t,n){var r,a,i=[],o=0;t&&(t._top?(a=t._top,delete t._top):a=300);for(var s in e)if(r=e[s],K._selection.call(this,r,t)){if(n){if(n.call(this,r)===!1)break}else i.push(r);if(a&&(o++,o>=a))break}return i}},on:{value:function(e,t){if("object"!=typeof e)return this.eve.attachEvent(e,t);for(var n in e)e[n]._evnts||(e[n]._evnts=[]),e[n]._evnts.push(this.eve.attachEvent(n,e[n]))}},off:{value:function(e){"function"==typeof e&&e._evnts?e._evnts.forEach(function(e){K.eve.detachEvent(e)}):e?K.eve.detachEvent(e):K.eve.detachAllEvents()}},record_log:{value:function(e){K.ireg&&K.ireg.log&&K.ireg.log.record(e),console.log(e)}},md:{value:new o},enm:{value:new function(){this.toString=function(){return K.msg.meta_enn_mgr}}},cat:{value:new function(){this.toString=function(){return K.msg.meta_cat_mgr}}},doc:{value:new function(){this.toString=function(){return K.msg.meta_doc_mgr}}},ireg:{value:new function(){this.toString=function(){return K.msg.meta_ireg_mgr}}},areg:{value:new function(){this.toString=function(){return K.msg.meta_areg_mgr}}},accreg:{value:new function(){this.toString=function(){return K.msg.meta_accreg_mgr}}},dp:{value:new function(){this.toString=function(){return K.msg.meta_dp_mgr}}},rep:{value:new function(){this.toString=function(){return K.msg.meta_reports_mgr}}},cacc:{value:new function(){this.toString=function(){return K.msg.meta_charts_of_accounts_mgr}}},cch:{value:new function(){this.toString=function(){return K.msg.meta_charts_of_characteristic_mgr}}},tsk:{value:new function(){this.toString=function(){return K.msg.meta_task_mgr}}},bp:{value:new function(){this.toString=function(){return K.msg.meta_bp_mgr}}},DataManager:{value:s},RefDataManager:{value:l},DataProcessorsManager:{value:_},EnumManager:{value:u},RegisterManager:{value:c},InfoRegManager:{value:f},LogManager:{value:v},MetaObjManager:{value:w},MetaFieldManager:{value:x},SchemeSettingsManager:{value:j},AccumRegManager:{value:d},CatManager:{value:p},ChartOfCharacteristicManager:{value:h},ChartOfAccountManager:{value:m},DocManager:{value:y},TaskManager:{value:g},BusinessProcessManager:{value:b},DataObj:{value:E},CatObj:{value:q},DocObj:{value:A},DataProcessorObj:{value:R},TaskObj:{value:P},BusinessProcessObj:{value:S},EnumObj:{value:N},RegisterRow:{value:C},TabularSection:{value:O},TabularSectionRow:{value:k}})}function t(){this.moment="function"==typeof moment?moment:require("moment"),this.moment._masks={date:"DD.MM.YY",date_time:"DD.MM.YYYY HH:mm",ldt:"DD MMMM YYYY, HH:mm",iso:"YYYY-MM-DDTHH:mm:ss"},this.fix_date=function(e,t){if(e instanceof Date)return e;var n=this.moment(e,["DD-MM-YYYY","DD-MM-YYYY HH:mm","DD-MM-YYYY HH:mm:ss","DD-MM-YY HH:mm","YYYYDDMMHHmmss",this.moment.ISO_8601]);return n.isValid()?n.toDate():t?this.blank.date:e},this.fix_guid=function(e,t){if(e&&"string"==typeof e);else{if(e instanceof E)return e.ref;if(e&&"object"==typeof e)if(e.presentation){if(e.ref)return e.ref;if(e.name)return e.name}else e="object"==typeof e.ref&&e.ref.hasOwnProperty("ref")?e.ref.ref:e.ref}return this.is_guid(e)||t===!1?e:t?this.generate_guid():this.blank.guid},this.fix_number=function(e,t){var n=parseFloat(e);return isNaN(n)?t?0:e:n},this.fix_boolean=function(e){return"string"==typeof e?!(!e||"false"==e.toLowerCase()):!!e},this.blank={date:this.fix_date("0001-01-01T00:00:00"),guid:"00000000-0000-0000-0000-000000000000",by_type:function(e){var t;return t=e.is_ref?this.guid:e.date_part?this.date:e.digits?0:(!e.types||"boolean"!=e.types[0])&&""}},this.fetch_type=function(e,t){var n=e;return t.is_ref?n=this.fix_guid(e):t.date_part?n=this.fix_date(e,!0):t.digits?n=this.fix_number(e,!0):"boolean"==t.types[0]&&(n=this.fix_boolean(e)),n},this.date_add_day=function(e,t,n){var r=new Date(e);return r.setDate(e.getDate()+t),n&&r.setHours(0,-r.getTimezoneOffset(),0,0),r},this.generate_guid=function(){var e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var n=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?n:7&n|8).toString(16)})},this.is_guid=function(e){return!("string"!=typeof e||e.length<36)&&(e.length>36&&(e=e.substr(0,36)),/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(e))},this.is_empty_guid=function(e){return!e||e===this.blank.guid},this.is_data_obj=function(e){return e&&e instanceof E},this.is_data_mgr=function(e){return e&&e instanceof s},this.is_equal=function(e,t){return e==t||typeof e!=typeof t&&this.fix_guid(e,!1)==this.fix_guid(t,!1)},this.blob_as_text=function(e,t){return new Promise(function(n,r){var a=new FileReader;a.onload=function(e){n(a.result)},a.onerror=function(e){r(e)},"data_url"==t?a.readAsDataURL(e):a.readAsText(e)})}}function n(){function e(e,t,n,r,a){return new Promise(function(i,o){if("undefined"==typeof window&&r&&r.request)r.request({url:encodeURI(t),headers:{Authorization:r.auth}},function(e,t,n){e?o(e):200!=t.statusCode?o({message:t.statusMessage,description:n,status:t.statusCode}):i({response:n})});else{var s=new XMLHttpRequest;if(window.dhx4&&window.dhx4.isIE&&(t=encodeURI(t)),r){var l,_;"object"==typeof r&&r.username&&r.hasOwnProperty("password")?(l=r.username,_=r.password):K.ajax.username&&K.ajax.authorized?(l=K.ajax.username,_=K.aes.Ctr.decrypt(K.ajax.password)):(l=K.wsql.get_user_param("user_name"),_=K.aes.Ctr.decrypt(K.wsql.get_user_param("user_pwd")),!l&&K.job_prm&&K.job_prm.guest_name&&(l=K.job_prm.guest_name,_=K.aes.Ctr.decrypt(K.job_prm.guest_pwd))),s.open(e,t,!0,l,_),s.withCredentials=!0,s.setRequestHeader("Authorization","Basic "+btoa(unescape(encodeURIComponent(l+":"+_))))}else s.open(e,t,!0);a&&a.call(this,s),"GET"!=e?this.hide_headers||r.hide_headers||(s.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),s.setRequestHeader("X-Requested-With","XMLHttpRequest")):n=null,s.onload=function(){200==s.status&&(s.response instanceof Blob||"62135622e6?this.js_time_diff:e}},set_user_param:{value:function(t,r){var a=r;"object"==typeof r?a=JSON.stringify(r):r===!1&&(a=""),e.setItem(K.job_prm.local_storage_prefix+t,a),n[t]=r}},get_user_param:{value:function(t,r){return!n.hasOwnProperty(t)&&e&&(n[t]=this.fetch_type(e.getItem(K.job_prm.local_storage_prefix+t),r)),n[t]}},promise:{value:function(e,n){return new Promise(function(r,a){t.alasql(e,n||[],function(e,t){t?a(t):r(e)})})}},save_options:{value:function(e,n){return t.set_user_param(e+"_"+n.name,n)}},restore_options:{value:function(e,n){var r=t.get_user_param(e+"_"+n.name,"object");for(var a in r)if("object"!=typeof r[a])n[a]=r[a];else{n[a]||(n[a]={});for(var i in r[a])n[a][i]=r[a][i]}return n}},fetch_type:{value:function(e,t){if("object"==t){try{e=JSON.parse(e)}catch(t){e={}}return e}return"number"==t?K.utils.fix_number(e,!0):"date"==t?K.utils.fix_date(e,!0):"boolean"==t?K.utils.fix_boolean(e):e}},alasql:{value:"undefined"!=typeof alasql?alasql:require("alasql")},init_params:{value:function(){if(!K.job_prm.local_storage_prefix&&!K.job_prm.create_tables)return Promise.resolve();e="undefined"==typeof localStorage?"undefined"==typeof WorkerGlobalScope?new require("node-localstorage").LocalStorage("./localstorage"):{setItem:function(e,t){},getItem:function(e){}}:localStorage;var n,r=[{p:"user_name",v:"",t:"string"},{p:"user_pwd",v:"",t:"string"},{p:"browser_uid",v:K.utils.generate_guid(),t:"string"},{p:"zone",v:K.job_prm.hasOwnProperty("zone")?K.job_prm.zone:1,t:K.job_prm.zone_is_string?"string":"number"},{p:"enable_save_pwd",v:K.job_prm.enable_save_pwd,t:"boolean"},{p:"autologin",v:"",t:"boolean"},{p:"skin",v:"dhx_web",t:"string"},{p:"rest_path",v:"",t:"string"}];K.job_prm.additional_params&&(r=r.concat(K.job_prm.additional_params)),e.getItem(K.job_prm.local_storage_prefix+"zone")||(n=K.job_prm.hasOwnProperty("zone")?K.job_prm.zone:1),K.job_prm.url_prm.hasOwnProperty("zone")&&(n=K.job_prm.zone_is_string?K.job_prm.url_prm.zone:K.utils.fix_number(K.job_prm.url_prm.zone,!0)),void 0!==n&&t.set_user_param("zone",n),r.forEach(function(e){(void 0==t.get_user_param(e.p,e.t)||!t.get_user_param(e.p,e.t)&&e.p.indexOf("url")!=-1)&&t.set_user_param(e.p,K.job_prm.hasOwnProperty(e.p)?K.job_prm[e.p]:e.v)});var a={path:t.get_user_param("couch_path","string")||K.job_prm.couch_path||"",zone:t.get_user_param("zone","number"),prefix:K.job_prm.local_storage_prefix,suffix:t.get_user_param("couch_suffix","string")||"",user_node:K.job_prm.user_node,noreplicate:K.job_prm.noreplicate};a.path&&(t.__define("pouch",{value:new i}),t.pouch.init(a)),this.create_tables&&(this.alasq(this.create_tables,[]),this.create_tables="")}},drop_tables:{value:function(e){function n(){i--,i<=0?setTimeout(e,10):r()}function r(){var e=o[i-1].tableid;"_"==e.substr(0,1)?n():t.alasql("drop table IF EXISTS "+e,[],n)}function a(e){o=e,(i=e.length)?r():n()}var i=0,o=[];t.alasql("SHOW TABLES",[],a)}}}),this.__define({aladb:{value:new this.alasql.Database("md")}})}function a(){this.toString=function(){return"Интернационализация сообщений"},"undefined"!=typeof window&&"dhtmlx"in window&&(this.show_msg=function(e,t){if(e){if("string"==typeof e){if(K.iface.synctxt)return void K.iface.synctxt.show_message(e);e={type:"info",text:e}}t&&"function"==typeof t.setText&&t.setText(e.text),dhtmlx.message(e)}},this.check_soap_result=function(e){return e?"limit_query"==e.error?(K.iface.docs.progressOff(),K.msg.show_msg({type:"alert-warning",text:K.msg.limit_query.replace("%1",e.queries).replace("%2",e.queries_avalable),title:K.msg.srv_overload}),!0):"network"==e.error||"empty"==e.error?(K.iface.docs.progressOff(),K.msg.show_msg({type:"alert-warning",text:K.msg.error_network,title:K.msg.error_critical}),!0):e.error&&e.error_description?(K.iface.docs.progressOff(),e.error_description.indexOf("Недостаточно прав")!=-1&&(e.error_type="alert-warning",e.error_title=K.msg.error_rights),K.msg.show_msg({type:e.error_type||"alert-error",text:e.error_description,title:e.error_title||K.msg.error_critical}),!0):e.error&&!e.messages?(K.iface.docs.progressOff(),K.msg.show_msg({type:"alert-error",title:K.msg.error_critical,text:K.msg.unknown_error.replace("%1","unknown_error")}),!0):void 0:(K.msg.show_msg({type:"alert-error",text:K.msg.empty_response,title:K.msg.error_critical}),!0)},this.show_not_implemented=function(){K.msg.show_msg({type:"alert-warning",text:K.msg.not_implemented,title:K.msg.main_title})})}function i(){var e,t,n,r,a=this,i={};a.__define({DB:{value:"undefined"==typeof PouchDB?require("pouchdb-core").plugin(require("pouchdb-adapter-memory")).plugin(require("pouchdb-adapter-http")).plugin(require("pouchdb-replication")).plugin(require("pouchdb-mapreduce")):PouchDB},init:{value:function(e){i._mixin(e),i.path&&0!=i.path.indexOf("http")&&"undefined"!=typeof location&&(i.path=location.protocol+"//"+location.host+i.path)}},local:{get:function(){if(!e){var t={auto_compaction:!0,revs_limit:2};e={ram:new a.DB(i.prefix+i.zone+"_ram",t),doc:new a.DB(i.prefix+i.zone+"_doc",t),meta:new a.DB(i.prefix+"meta",t),sync:{}}}return i.path&&!e._meta&&(e._meta=new a.DB(i.path+"meta",{auth:{username:"guest",password:"meta"},skip_setup:!0}),a.run_sync(e.meta,e._meta,"meta")),e}},remote:{get:function(){return!t&&n&&(t={ram:new a.DB(i.path+i.zone+"_ram",{auth:{username:n.username,password:n.password},skip_setup:!0}),doc:new a.DB(i.path+i.zone+"_doc"+i.suffix,{auth:{username:n.username,password:n.password},skip_setup:!0})}),t}},log_in:{value:function(e,t){return void 0==e&&void 0==t&&(e=K.job_prm.guest_name,t=K.aes.Ctr.decrypt(K.job_prm.guest_pwd)),n?n.username==e?Promise.resolve():Promise.reject():K.ajax.get_ex(i.path+i.zone+"_ram",{username:e,password:t}).then(function(r){return n={username:e,password:t},setTimeout(function(){dhx4.callEvent("log_in",[e])}),{ram:a.run_sync(a.local.ram,a.remote.ram,"ram"),doc:a.run_sync(a.local.doc,a.remote.doc,"doc")}})}},log_out:{value:function(){if(n){if(e.sync.doc)try{e.sync.doc.cancel()}catch(e){}if(e.sync.ram)try{e.sync.ram.cancel()}catch(e){}n=null}t&&t.ram&&delete t.ram,t&&t.doc&&delete t.doc,t=null,dhx4.callEvent("log_out")}},reset_local_data:{value:function(){var e=a.local.ram.destroy.bind(a.local.ram),t=a.local.doc.destroy.bind(a.local.doc),n=function(){setTimeout(function(){K.eve.redirect=!0,location.reload(!0)},1e3)};a.log_out(),setTimeout(function(){e().then(t).catch(t).then(n).catch(n)},1e3)}},load_data:{value:function(){var e={limit:800,include_docs:!0},t={total_rows:0,limit:e.limit,page:0,start:Date.now()};return new Promise(function(n,i){function o(){a.local.ram.allDocs(e,function(s,l){l?(t.page++,t.total_rows=l.total_rows,t.duration=Date.now()-t.start,K.eve.callEvent("pouch_load_data_page",[t]),a.load_changes(l,e)?o():(n(),r=!0,K.eve.callEvent("pouch_load_data_loaded",[t]),t.note="pouch_load_data_loaded",K.record_log(t))):s&&(i(s),K.eve.callEvent("pouch_load_data_error",[s]))})}a.local.ram.info().then(function(e){e.doc_count>=(K.job_prm.pouch_ram_doc_count||10)?(K.eve.callEvent("pouch_load_data_start",[t]),o()):(K.eve.callEvent("pouch_load_data_error",[e]),i(e))})})}},authorized:{get:function(){return n&&n.username}},data_loaded:{get:function(){return!!r}},run_sync:{value:function(t,n,i){var o,s;return t.info().then(function(e){return o=e,n.info()}).then(function(e){return"ram"!=i?e:n.get("data_version").then(function(t){return t.version!=K.wsql.get_user_param("couch_ram_data_version")&&(K.wsql.get_user_param("couch_ram_data_version")&&(e=a.reset_local_data()),K.wsql.set_user_param("couch_ram_data_version",t.version)),e}).catch(function(e){K.record_log(e)}).then(function(){return e})}).then(function(l){if(l){"ram"==i&&o.doc_count<(K.job_prm.pouch_ram_doc_count||10)?(s={total_rows:l.doc_count,local_rows:o.doc_count,docs_written:0,limit:200,page:0,start:Date.now()},K.eve.callEvent("pouch_load_data_start",[s])):"doc"==i&&setTimeout(function(){K.eve.callEvent("pouch_doc_sync_start")});var _={live:!0,retry:!0,batch_size:300,batches_limit:8};return"meta"==i?_.filter="auth/meta":K.job_prm.pouch_filter&&K.job_prm.pouch_filter[i]&&(_.filter=K.job_prm.pouch_filter[i]),"ram"==i||"meta"==i||K.wsql.get_user_param("zone")==K.job_prm.zone_demo?e.sync[i]=t.replicate.from(n,_):e.sync[i]=t.sync(n,_),e.sync[i].on("change",function(e){"ram"==i?(a.load_changes(e),o.doc_count<(K.job_prm.pouch_ram_doc_count||10)&&(s.page++,s.docs_written=e.docs_written,s.duration=Date.now()-s.start,K.eve.callEvent("pouch_load_data_page",[s]),s.docs_written>=s.total_rows&&(r=!0,K.eve.callEvent("pouch_load_data_loaded",[s]),s.note="pouch_load_data_loaded",K.record_log(s)))):(e.update_only=!0,a.load_changes(e)),K.eve.callEvent("pouch_change",[i,e])}).on("paused",function(e){e&&K.eve.callEvent("pouch_paused",[i,e])}).on("active",function(e){K.eve.callEvent("pouch_active",[i,e])}).on("denied",function(e){K.eve.callEvent("pouch_denied",[i,e])}).on("complete",function(e){K.eve.callEvent("pouch_complete",[i,e])}).on("error",function(e){K.eve.callEvent("pouch_error",[i,e])}),e.sync[i]}})}},load_obj:{value:function(e){return e._manager.pouch_db.get(e._manager.class_name+"|"+e.ref).then(function(t){delete t._id,delete t._rev,e._mixin(t)._set_loaded()}).catch(function(e){if(404!=e.status)throw e}).then(function(t){return e})}},save_obj:{value:function(e,t){var n=e._obj._clone(),r=t.db||e._manager.pouch_db;return n._id=e._manager.class_name+"|"+e.ref,delete n.ref,t.attachments&&(n._attachments=t.attachments),(e.is_new()?Promise.resolve():r.get(n._id)).then(function(e){if(e){n._rev=e._rev;for(var t in e._attachments)n._attachments||(n._attachments={}),n._attachments[t]||(n._attachments[t]=e._attachments[t])}}).catch(function(e){if(404!=e.status)throw e}).then(function(){return r.put(n)}).then(function(){if(e.is_new()&&e._set_loaded(e.ref),n._attachments){e._attachments||(e._attachments={});for(var r in n._attachments)e._attachments[r]&&n._attachments[r].stub||(e._attachments[r]=n._attachments[r])}return n=null,t=null,e})}},load_changes:{value:function(e,t){var n,r,a,i,o={};if(t)n=e.rows;else if(e.direction){if("pull"!=e.direction)return;n=e.change.docs}else n=e.docs;if(n.length>0){t&&(t.startkey=n[n.length-1].key,t.skip=1),n.forEach(function(e){if(r=t?e.doc:e,!r)if(e.value&&e.value.deleted)r={_id:e.id,_deleted:!0};else if(e.error)return;i=r._id.split("|"),a=i[0].split("."),r.ref=i[1],delete r._id,delete r._rev,o[a[0]]||(o[a[0]]={}),o[a[0]][a[1]]||(o[a[0]][a[1]]=[]),o[a[0]][a[1]].push(r)});for(var s in o)for(a in o[s])K[s]&&K[s][a]&&K[s][a].load_array(o[s][a],!e.update_only||"update_only");return o=e=n=r=null,!0}return!1}},backup_database:{value:function(e){}},restore_database:{value:function(e){}}})}function o(){function e(e){return e.info().then(function(){return e.get("meta")}).then(function(n){return K._patch(t,n),n=null,e.get("meta_patch")}).then(function(e){return K._patch(t,e),e=null,delete t._id,delete t._rev,t})}var t={enm:{accumulation_record_type:[{order:0,name:"debit",synonym:"Приход"},{order:1,name:"credit",synonym:"Расход"}],comparison_types:[{order:0,name:"gt",synonym:"Больше"},{order:1,name:"gte",synonym:"Больше или равно"},{order:2,name:"lt",synonym:"Меньше"},{order:3,name:"lte",synonym:"Меньше или равно "},{order:4,name:"eq",synonym:"Равно"},{order:5,name:"ne",synonym:"Не равно"},{order:6,name:"in",synonym:"В списке"},{order:7,name:"nin",synonym:"Не в списке"},{order:8,name:"lke",synonym:"Подобно "},{order:9,name:"nlk",synonym:"Не подобно"}]},cat:{meta_objs:{},meta_fields:{},scheme_settings:{name:"scheme_settings",splitted:!0,synonym:"Настройки отчетов и списков",illustration:"",obj_presentation:"",list_presentation:"",input_by_string:["name"],hierarchical:!1,has_owners:!1,group_hierarchy:!0,main_presentation_name:!0,code_length:0,fields:{obj:{synonym:"Объект",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:250}},user:{synonym:"Пользователь",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:50}},predefined_name:{synonym:"",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:256}}},tabular_sections:{available_fields:{name:"available_fields",synonym:"Доступные поля",tooltip:"Состав, порядок и ширина колонок",fields:{parent:{synonym:"Родитель",multiline_mode:!1,tooltip:"Для плоского списка, родитель пустой",type:{types:["string"],str_len:100}},use:{synonym:"Использование",multiline_mode:!1,tooltip:"",type:{types:["boolean"]}},field:{synonym:"Поле",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}},width:{synonym:"Ширина",multiline_mode:!1,tooltip:"",type:{types:["number"],digits:6,fraction_figits:0}},caption:{synonym:"Заголовок",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}}}},sort_fields:{name:"sort_fields",synonym:"Поля сортировки",tooltip:"",fields:{parent:{synonym:"Родитель",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}},field:{synonym:"Поле",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}}}},grouping_fields:{name:"grouping_fields",synonym:"Поля группировки",tooltip:"",fields:{parent:{synonym:"Родитель",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}},field:{synonym:"Поле",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}}}},selection:{name:"selection",synonym:"Отбор",tooltip:"",fields:{parent:{synonym:"Родитель",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}},use:{synonym:"Использование",multiline_mode:!1,tooltip:"",type:{types:["boolean"]}},left_value:{synonym:"Левое значение",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}},comparison_type:{synonym:"Вид сравнения",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}},right_value:{synonym:"Правое значение",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}}}},scheme:{name:"scheme",synonym:"Структура",tooltip:"",fields:{parent:{synonym:"Родитель",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:10}},kind:{synonym:"Вид раздела отчета",multiline_mode:!1,tooltip:"список, таблица, группировка строк, группировка колонок",type:{types:["string"],str_len:10}}}}},cachable:"doc"}},doc:{},ireg:{log:{name:"log",note:"",synonym:"Журнал событий",dimensions:{date:{synonym:"Дата",multiline_mode:!1,tooltip:"Время события",type:{types:["number"],digits:15,fraction_figits:0}},sequence:{synonym:"Порядок",multiline_mode:!1,tooltip:"Порядок следования",type:{types:["number"],digits:6,fraction_figits:0}}},resources:{class:{synonym:"Класс",multiline_mode:!1,tooltip:"Класс события",type:{types:["string"],str_len:100}},note:{synonym:"Комментарий",multiline_mode:!0,tooltip:"Текст события",type:{types:["string"],str_len:0}},obj:{synonym:"Объект",multiline_mode:!0,tooltip:"Объект, к которому относится событие",type:{types:["string"],str_len:0}}}}},areg:{},dp:{},rep:{},cch:{},cacc:{}};_md=this,_md.create_managers=function(){},_md.init=function(n){function r(){return!n||a||i?e(n||K.wsql.pouch.local.meta).then(function(){return a?void _md.create_managers():t}).catch(K.record_log):(K._patch(t,n),n=null,_md.create_managers(),void 0)}var a=!n||K.wsql.pouch&&n==K.wsql.pouch.local.meta,i=n&&K.wsql.pouch&&n==K.wsql.pouch.local._meta;return K.on("pouch_change",function(e,n){"meta"==e&&(t?K.iface&&K.iface.do_reload&&setTimeout(function(){K.iface.do_reload()},3e3):r())}),r()},_md.get=function(e,n){var r=e.split(".");if(!n)return t[r[0]][r[1]];var a={multiline_mode:!1,note:"",synonym:"",tooltip:"",type:{is_ref:!1,types:["string"]}},i="doc,tsk,bp".indexOf(r[0])!=-1,o="cat,cch,cacc,tsk".indexOf(r[0])!=-1;return i&&"number_doc"==n?(a.synonym="Номер",a.tooltip="Номер документа",a.type.str_len=11):i&&"date"==n?(a.synonym="Дата",a.tooltip="Дата документа",a.type.date_part="date_time",a.type.types[0]="date"):i&&"posted"==n?(a.synonym="Проведен",a.type.types[0]="boolean"):o&&"id"==n?a.synonym="Код":o&&"name"==n?a.synonym="Наименование":"_deleted"==n?(a.synonym="Пометка удаления",a.type.types[0]="boolean"):"is_folder"==n?(a.synonym="Это группа",a.type.types[0]="boolean"):"ref"==n?(a.synonym="Ссылка",a.type.is_ref=!0,a.type.types[0]=e):a=n?t[r[0]][r[1]].fields[n]:t[r[0]][r[1]],a},_md.get_classes=function(){var e={};for(var n in t){e[n]=[];for(var r in t[n])e[n].push(r)}return e},_md.sql_type=function(e,t,n,r){var a;return a="type"==t&&"cch_properties"==e.table_name||"svg"==t&&"cat_production_params"==e.table_name?" JSON":n.is_ref||n.types.indexOf("guid")!=-1?r?n.types.every(function(e){return 0==e.indexOf("enm.")})?" character varying(100)":n.hasOwnProperty("str_len")?" character varying("+Math.max(36,n.str_len)+")":" uuid":" CHAR":n.hasOwnProperty("str_len")?r?n.str_len?" character varying("+n.str_len+")":" text":" CHAR":n.date_part?r&&"date"!=n.date_part?"date_time"==n.date_part?" timestamp with time zone":" time without time zone":" Date":n.hasOwnProperty("digits")?0==n.fraction_figits?r?n.digits<7?" integer":" bigint":" INT":r?" numeric("+n.digits+","+n.fraction_figits+")":" FLOAT":n.types.indexOf("boolean")!=-1?" BOOLEAN":n.types.indexOf("json")!=-1?" JSON":r?" character varying(255)":" CHAR"},_md.sql_composite=function(e,t,n,r){var a="";return e[t].type.types.length>1&&"type"!=t&&(n=n?n.substr(0,29)+"_T":t.substr(0,29)+"_T",a=r?', "'+n+'" character varying(255)':_md.sql_mask(n)+" CHAR"),a},_md.sql_mask=function(e,t){return", "+(t?"_t_.":"")+("`"+e+"`")},_md.mgr_by_class_name=function(e){if(e){var t=e.split(".");if(t[1]&&K[t[0]])return K[t[0]][t[1]]}},_md.value_mgr=function(e,t,n,r,a){function i(e){return e&&1==n.types.length&&(n._mgr=e),e}var o,s,l,_,u;if(n._mgr)return n._mgr;if(1==n.types.length){if(l=n.types[0].split("."),l.length>1&&K[l[0]])return i(K[l[0]][l[1]])}else if(a&&a.type&&(l=a.type.split("."),l.length>1&&K[l[0]]))return i(K[l[0]][l[1]]);if(o=e.property||e.param,"value"==t&&o){if(K.utils.is_data_obj(o))s=o;else{if(!K.utils.is_guid(o))return;s=K.cch.properties.get(o,!1)}if(K.utils.is_data_obj(s)){if(s.is_new())return K.cat.property_values;if(_=[],s.type.types.forEach(function(e){l=e.split("."),l.length>1&&K[l[0]][l[1]]&&_.push(K[l[0]][l[1]])}),1==_.length||e[t]==K.utils.blank.guid)return i(_[0]);if(r)return _;if((o=e[t])instanceof E)return o._manager;if(K.utils.is_guid(o)&&o!=K.utils.blank.guid)for(var c in _)if(u=_[c],u.get(o,!1,!0))return u}}else{if(_=[],n.types.forEach(function(e){l=e.split("."),l.length>1&&K[l[0]][l[1]]&&_.push(K[l[0]][l[1]])}),1==_.length||e[t]==K.utils.blank.guid)return i(_[0]);if(r)return _;if((o=e[t])instanceof E)return o._manager;if(K.utils.is_guid(o)&&o!=K.utils.blank.guid)for(var c in _)if(u=_[c],u.get(o,!1,!0))return u}},_md.control_by_type=function(e,t){var n;return n="boolean"==typeof t&&e.types.indexOf("boolean")!=-1?"ch":"number"==typeof t&&e.digits?e.fraction_figits<5?"calck":"edn":t instanceof Date&&e.date_part?"dhxCalendar":e.is_ref?"ocombo":e.date_part?"dhxCalendar":e.digits?e.fraction_figits<5?"calck":"edn":"boolean"==e.types[0]?"ch":e.hasOwnProperty("str_len")&&(e.str_len>=100||0==e.str_len)?"txt":"ed"},_md.ts_captions=function(e,t,n){n||(n={});var r,a=_md.get(e).tabular_sections[t],i=_md.get(e).form,o=a.fields;if(i&&i.obj){if(!i.obj.tabular_sections[t])return;n._mixin(i.obj.tabular_sections[t])}else{"contact_information"===t&&(o={type:"",kind:"",presentation:""}),n.fields=["row"],n.headers="№",n.widths="40",n.min_widths="",n.aligns="",n.sortings="na",n.types="cntr";for(var s in o)r=a.fields[s],r.hide||(n.fields.push(s),n.headers+=","+(r.synonym?r.synonym.replace(/,/g," "):s),n.types+=","+_md.control_by_type(r.type),n.sortings+=",na")}return!0},_md.syns_js=function(e){var n={DeletionMark:"_deleted",Description:"name",DataVersion:"data_version",IsFolder:"is_folder",Number:"number_doc",Date:"date","Дата":"date",Posted:"posted",Code:"id",Parent_Key:"parent",Owner_Key:"owner",Owner:"owner",Ref_Key:"ref","Ссылка":"ref",LineNumber:"row"};return n[e]?n[e]:t.syns_js[t.syns_1с.indexOf(e)]||e},_md.syns_1с=function(e){var n={_deleted:"DeletionMark",name:"Description",is_folder:"IsFolder",number_doc:"Number",date:"Date",posted:"Posted",id:"Code",ref:"Ref_Key",parent:"Parent_Key",owner:"Owner_Key",row:"LineNumber"};return n[e]?n[e]:t.syns_1с[t.syns_js.indexOf(e)]||e},_md.printing_plates=function(e){if(e)for(var n in e.doc)t.doc[n].printing_plates=e.doc[n]},_md.class_name_from_1c=function(e){var t=e.split(".");return 1==t.length?"enm."+e:("Перечисление"==t[0]?e="enm.":"Справочник"==t[0]?e="cat.":"Документ"==t[0]?e="doc.":"РегистрСведений"==t[0]?e="ireg.":"РегистрНакопления"==t[0]?e="areg.":"РегистрБухгалтерии"==t[0]?e="accreg.":"ПланВидовХарактеристик"==t[0]?e="cch.":"ПланСчетов"==t[0]?e="cacc.":"Обработка"==t[0]?e="dp.":"Отчет"==t[0]&&(e="rep."),e+_md.syns_js(t[1]))},_md.class_name_to_1c=function(e){var t=e.split(".");return 1==t.length?"Перечисление."+e:("enm"==t[0]?e="Перечисление.":"cat"==t[0]?e="Справочник.":"doc"==t[0]?e="Документ.":"ireg"==t[0]?e="РегистрСведений.":"areg"==t[0]?e="РегистрНакопления.":"accreg"==t[0]?e="РегистрБухгалтерии.":"cch"==t[0]?e="ПланВидовХарактеристик.":"cacc"==t[0]?e="ПланСчетов.":"dp"==t[0]?e="Обработка.":"rep"==t[0]&&(e="Отчет."),e+_md.syns_1с(t[1]))},_md.create_tables=function(e,t){function n(){i--,0==i?e?e(l):alasql.utils.saveFile("create_tables.sql",l):r()}function r(){var e=o[i-1];l+=e.class[e.name].get_sql_struct(t)+"; ",n()}var a,i=0,o=[],s=_md.get_classes(),l=t&&t.postgres?"":"USE md; ";"enm,cch,cacc,cat,bp,tsk,doc,ireg,areg".split(",").forEach(function(e){for(a in s[e])o.push({class:K[e],name:s[e][a]})}),i=o.length,r()}}function s(e){var t=_md.get(e),n={after_create:[],after_load:[],before_save:[],after_save:[],value_change:[],add_row:[],del_row:[]};this.__define({cachable:{get:function(){return e.indexOf("enm.")!=-1?"ram":t.cachable?t.cachable:e.indexOf("doc.")!=-1||e.indexOf("dp.")!=-1||e.indexOf("rep.")!=-1?"doc":"ram"}},class_name:{value:e,writable:!1},alatable:{get:function(){return K.wsql.aladb.tables[this.table_name]?K.wsql.aladb.tables[this.table_name].data:[]}},metadata:{value:function(e){return e?t.fields[e]||t.tabular_sections[e]:t}},on:{value:function(e,t){if("object"==typeof e)for(var r in e)e.hasOwnProperty(r)&&n[r].push(e[r]);else n[e].push(t)}},off:{value:function(e,t){}},handle_event:{value:function(e,t,r){var a,i=[];return n[t].forEach(function(t){ +i!==!1&&(a=t.call(e,r),a===!1?i=a:a&&i.push(a))}),i===!1?i:i.length?1==i.length?i[0]:i.some(function(e){return"object"==typeof e&&e.then})?Promise.all(i):i:void 0}},by_ref:{value:{}}})}function l(e){l.superclass.constructor.call(this,e)}function _(e){_.superclass.constructor.call(this,e)}function u(e){u.superclass.constructor.call(this,e);var t=K.md.get(e);for(var n in t)new N(t[n],this)}function c(e){c.superclass.constructor.call(this,e),this.push=function(e,t){t&&t!=e.ref?(delete this.by_ref[e.ref],this.by_ref[t]=e):this.by_ref[e.ref]=e},this.get=function(e,t,n){if(e?"string"==typeof e&&(e={ref:e}):e={},e.ref&&n)return t?Promise.resolve(this.by_ref[e.ref]):this.by_ref[e.ref];e.action="select";var r,a=K.wsql.alasql(this.get_sql_struct(e),e._values);if(delete e.action,delete e._values,a.length)if(n)r=this.by_ref[this.get_ref(a[0])];else{r=[];for(var i in a)r.push(this.by_ref[this.get_ref(a[i])])}return t?Promise.resolve(r):r},this.unload_obj=function(e){delete this.by_ref[e],this.alatable.some(function(t,n,r){if(t.ref==e)return r.splice(n,1),!0})},this.load_array=function(e,t){for(var n,r,a=[],i=0;i= ? and `date` <= ?":" where `date` >= ?":e.date_till&&(t+=" where `date` <= ?"),t}return v.superclass.get_sql_struct.call(this,e)}},caption_flds:{value:function(e){var t='%6',n=[],r="";if(n.push(new Col_struct("date","200","ro","left","server","Дата")),n.push(new Col_struct("class","100","ro","left","server","Класс")),n.push(new Col_struct("note","*","ro","left","server","Событие")),e.get_header){r="";for(var a in n)r+=t.replace("%1",n[a].id).replace("%2",n[a].width).replace("%3",n[a].type).replace("%4",n[a].align).replace("%5",n[a].sort).replace("%6",n[a].caption);r+=""}return{head:r,acols:n}}},data_to_grid:{value:function(e,t){var n="".replace("%1",e.length).replace("%2",t.start).replace("%3",t.set_parent||""),r=this.caption_flds(t);return n+=r.head,e.forEach(function(e){n+=''+K.moment(e.date-K.wsql.time_diff).format("DD.MM.YYYY HH:mm:ss")+"."+e.sequence+""+(e.class||"")+""+(e.note||"")+""}),n+""}}})}function w(){w.superclass.constructor.call(this,"cat.meta_objs")}function x(){x.superclass.constructor.call(this,"cat.meta_fields")}function j(){j.superclass.constructor.call(this,"cat.scheme_settings")}function O(e,t){t._obj[e]||(t._obj[e]=[]),this.__define("_name",{value:e,enumerable:!1}),this.__define("_owner",{value:t,enumerable:!1}),this.__define("_obj",{value:t._obj[e],writable:!1,enumerable:!1})}function k(e){var t={};this.__define("_owner",{value:e,enumerable:!1}),this.__define("_obj",{value:t,writable:!1,enumerable:!1})}function E(e,t){var n,r={},a={},i={_is_new:!(this instanceof N)};return t instanceof _||t instanceof u||(n=t.get(e,!1,!0)),n?(e=null,n):(t instanceof u?a.ref=e.name:t instanceof c?a.ref=t.get_ref(e):a.ref=K.utils.fix_guid(e),this.__define({_obj:{value:a,configurable:!0},_ts_:{value:function(e){return r[e]||(r[e]=new O(e,this)),r[e]},configurable:!0},_manager:{value:t},_data:{value:i,configurable:!0}}),t.alatable&&t.push&&(t.alatable.push(a),t.push(this,a.ref)),void(e=null))}function q(e,t){var n="";q.superclass.constructor.call(this,e,t),this.__define("presentation",{get:function(){return this.name||this.id?this.name||this.id||this._metadata.obj_presentation||this._metadata.synonym:n},set:function(e){e&&(n=String(e))}}),e&&"object"==typeof e&&(e._not_set_loaded?(delete e._not_set_loaded,this._mixin(e)):(this._mixin(e),K.utils.is_empty_guid(this.ref)||!e.id&&!e.name||this._set_loaded(this.ref))),e=null}function A(e,t){var n="";A.superclass.constructor.call(this,e,t),this.__define("presentation",{get:function(){return this.number_doc?(this._metadata.obj_presentation||this._metadata.synonym)+" №"+this.number_doc+" от "+K.moment(this.date).format(K.moment._masks.ldt):n},set:function(e){e&&(n=String(e))}}),e&&"object"==typeof e&&this._mixin(e),!K.utils.is_empty_guid(this.ref)&&e.number_doc&&this._set_loaded(this.ref),e=null}function D(e){e.__define({number_doc:{get:function(){return this._obj.number_doc||""},set:function(e){this.__notify("number_doc"),this._obj.number_doc=e},enumerable:!0},date:{get:function(){return this._obj.date||K.utils.blank.date},set:function(e){this.__notify("date"),this._obj.date=K.utils.fix_date(e,!0)},enumerable:!0}})}function R(e,t){R.superclass.constructor.call(this,e,t);var n,r=t.metadata();for(n in r.fields)e[n]=K.utils.fetch_type("",r.fields[n].type);for(n in r.tabular_sections)e[n]=[];this._mixin(e)}function P(e,t){P.superclass.constructor.call(this,e,t)}function S(e,t){S.superclass.constructor.call(this,e,t)}function N(e,t){N.superclass.constructor.call(this,e,t),e&&"object"==typeof e&&this._mixin(e)}function C(e,t){C.superclass.constructor.call(this,e,t),e&&"object"==typeof e&&this._mixin(e);for(var n in t.metadata().dimensions)if(!e.hasOwnProperty(n)&&e.ref){var r=e.ref.split("¶");Object.keys(t.metadata().dimensions).forEach(function(e,t){this[e]=r[t]}.bind(this));break}}function T(){this.filter_date=function(e,t,n){t||(t=new Date("2015-01-01"));var r=e+" gt datetime'"+K.moment(t).format(K.moment._masks.iso)+"'";return n&&(r+=" and "+e+" lt datetime'"+K.moment(n).format(K.moment._masks.iso)+"'"),r},this.to_data=function(e,t){var n,r,a,i,o,s,_={},u=t.metadata(),c=u.fields,f=u.tabular_sections;t instanceof l?(e.hasOwnProperty("DeletionMark")&&(_._deleted=e.DeletionMark),e.hasOwnProperty("DataVersion"),e.hasOwnProperty("Ref_Key")&&(_.ref=e.Ref_Key)):c={}._mixin(u.dimensions)._mixin(u.resources)._mixin(u.attributes),t instanceof y?(e.hasOwnProperty("Number")?_.number_doc=e.Number||e.number_doc:e.hasOwnProperty("number_doc")&&(_.number_doc=e.number_doc),e.hasOwnProperty("Date")?_.date=e.Date:e.hasOwnProperty("date")&&(_.date=e.date),e.hasOwnProperty("Posted")?_.posted=e.Posted:e.hasOwnProperty("posted")&&(_.posted=e.posted)):(u.main_presentation_name&&(e.hasOwnProperty("Description")?_.name=e.Description:e.hasOwnProperty("name")&&(_.name=e.name)),u.code_length&&(e.hasOwnProperty("Code")?_.id=e.Code:e.hasOwnProperty("id")&&(_.id=e.id)));for(r in c)if(e.hasOwnProperty(r))_[r]=e[r];else{if(o=_md.syns_1с(r),o.indexOf("_Key")==-1&&c[r].type.is_ref&&e[o+"_Key"]&&(o+="_Key"),!e.hasOwnProperty(o))continue;_[r]=e[o]}for(n in f)s="extra_fields"==n||e.hasOwnProperty(n)?n:_md.syns_1с(n),e.hasOwnProperty(s)&&(_[n]=[],e[s]&&(e[s].sort(function(e,t){return(e.LineNumber||e.row)>(t.LineNumber||t.row)}),e[s].forEach(function(e){i={};for(a in f[n].fields)o=e.hasOwnProperty(a)||"extra_fields"==n&&("property"==a||"value"==a)?a:_md.syns_1с(a),o.indexOf("_Key")==-1&&f[n].fields[a].type.is_ref&&e[o+"_Key"]&&(o+="_Key"),i[a]=e[o];_[n].push(i)})));return _},this.ajax_to_data=function(e,t){return K.ajax.get_ex(e.url,e).then(function(e){return JSON.parse(e.response)}).then(function(e){var n=[];return e.value.forEach(function(e){n.push(Y.to_data(e,t))}),n})},this.build_select=function(e,t){function n(e,r){"function"==typeof r?i+=r(t,e):(o=_md.syns_1с(e),s=_md.get(t.class_name,e),s&&(s=s.type,s.is_ref&&o.indexOf("_Key")==-1&&s.types.length&&s.types[0].indexOf("enm.")==-1&&(o+="_Key"),s.types.length&&(["boolean","number"].indexOf(typeof r)!=-1?i+=o+" eq "+r:s.is_ref&&"object"!=typeof r||r instanceof E?i+=o+" eq guid'"+r+"'":"string"==typeof r?i+=o+" eq '"+r+"'":"object"==typeof r&&(r.hasOwnProperty("like")?i+=o+" like '%"+r.like+"%'":r.hasOwnProperty("not")?i+=" not ("+n(e,r.not)+") ":r.hasOwnProperty("in")&&(i+=o+" in ("+(s.is_ref?r.in.map(function(e){return"guid'"+e+"'"}).join(","):r.in.join(","))+") ")))))}function r(e){for(var t in e)if(i?i+=" and ":i="&$filter=","or"==t&&Array.isArray(e[t])){var r=!0;e[t].forEach(function(e){r?(i+=" ( ",r=!1):i+=" or ";var t=Object.keys(e)[0];n(t,e[t])}),i+=" ) "}else n(t,e[t])}var a,i,o,s,l="";e||(e={}),e.fields&&(e.fields.forEach(function(e){"ref"==e?o="Ref_Key":(o=_md.syns_1с(e),s=_md.get(t.class_name,e).type,s.is_ref&&o.indexOf("_Key")==-1&&s.types.length&&s.types[0].indexOf("enm.")==-1&&(o+="_Key")),a?a+=",":a="&$select=",a+=o}),l+=a),e.selection&&("function"==typeof e.selection||(Array.isArray(e.selection)?e.selection.forEach(r):r(e.selection)),i&&(l+=i)),K.job_prm.rest&&t.rest_name.indexOf("Module_")==-1&&t.rest_name.indexOf("DataProcessor_")==-1&&t.rest_name.indexOf("Report_")==-1&&l.indexOf(" like ")==-1&&l.indexOf(" in ")==-1&&!t.metadata().irest?K.ajax.default_attr(e,K.job_prm.rest_url()):K.ajax.default_attr(e,K.job_prm.irest_url()),e.url+=t.rest_name+"?allowedOnly=true&$format=json&$top="+(e.top||300)+l},this.load_array=function(e,t){return Y.build_select(e,t),Y.ajax_to_data(e,t)},this.load_obj=function(e){var t={};return K.ajax.default_attr(t,!e._metadata.irest&&K.job_prm.rest?K.job_prm.rest_url():K.job_prm.irest_url()),t.url+=e._manager.rest_name+"(guid'"+e.ref+"')?$format=json",K.ajax.get_ex(t.url,t).then(function(e){return JSON.parse(e.response)}).then(function(t){return e._mixin(Y.to_data(t,e._manager))._set_loaded(),e}).catch(function(t){return 404==t.status?e:void K.record_log(t)})},this.save_irest=function(e,t){var n=JSON.stringify(e),r=(void 0!=t.post?",post="+t.post:"")+(void 0!=t.operational?",operational="+t.operational:"");return K.ajax.default_attr(t,K.job_prm.irest_url()),t.url+=e._manager.rest_name+"(guid'"+e.ref+"'"+r+")",K.ajax.post_ex(t.url,n,t).then(function(e){return JSON.parse(e.response)}).then(function(t){return e._mixin(t)})},this.save_rest=function(e,t){var n,r=e.to_atom();return K.ajax.default_attr(t,K.job_prm.rest_url()),n=t.url+e._manager.rest_name,t.url=n+"(guid'"+e.ref+"')?$format=json&$select=Ref_Key,DeletionMark",K.ajax.get_ex(t.url,t).catch(function(e){return 404==e.status?{response:JSON.stringify({is_new:!0})}:Promise.reject(e)}).then(function(e){return JSON.parse(e.response)}).then(function(a){return a.is_new?K.ajax.post_ex(n,r,t):K.ajax.patch_ex(n+"(guid'"+e.ref+"')",r,t)}).then(function(t){var n=xmlToJSON.parseString(t.response,{mergeCDATA:!1,grokAttr:!0,grokText:!1,normalize:!0,xmlns:!1,namespaceKey:"_ns",textKey:"_text",valueKey:"_value",attrKey:"_attr",cdataKey:"_cdata",attrsAsObject:!1,stripAttrPrefix:!0,stripElemPrefix:!0,childrenAsArray:!1});if(n.entry&&n.entry.content&&n.entry.updated){var r,a=n.entry.content.properties,i={};for(var o in a)if(0!=o.indexOf("_"))if(r=a[o].element)if(i[o]=[],Array.isArray(r))for(var s in r){i[o][s]={};for(var l in r[s])0!=l.indexOf("_")&&(i[o][s][l]="false"!==r[s][l]._text&&r[s][l]._text)}else{i[o][0]={};for(var l in r)0!=l.indexOf("_")&&(i[o][0][l]="false"!==r[l]._text&&r[l]._text)}else i[o]="false"!==a[o]._text&&a[o]._text;return Y.to_data(i,e._manager)}}).then(function(t){return e._mixin(t)})}}function M(){if(this.__define({init:{value:function(){K.__define("job_prm",{value:new L,writable:!1}),K.wsql.init_params()}},do_eventable:{value:function(e){function t(e,t){e=String(e).toLowerCase(),this._evnts.data[e]||(this._evnts.data[e]={});var n=K.utils.generate_guid();return this._evnts.data[e][n]=t,n}function n(e){if(!e)return r.call(this);for(var t in this._evnts.data){var n=0;for(var a in this._evnts.data[t])a==e?(this._evnts.data[t][a]=null,delete this._evnts.data[t][a]):n++;0==n&&(this._evnts.data[t]=null,delete this._evnts.data[t])}}function r(){for(var e in this._evnts.data){for(var t in this._evnts.data[e])this._evnts.data[e][t]=null,delete this._evnts.data[e][t];this._evnts.data[e]=null,delete this._evnts.data[e]}}function a(e,t){if(e=String(e).toLowerCase(),null==this._evnts.data[e])return!0;var n=!0;for(var r in this._evnts.data[e])n=this._evnts.data[e][r].apply(this,t)&&n;return n}function i(){for(var e in this._evnts.evnts){var t=this._evnts.evnts[e].length;if(t){for(var n=0;n2){t=decodeURI(e).split("&");for(var a in t)if(r=t[a].split("="),"m"==r[0])try{n[r[0]]=JSON.parse(r[1])}catch(e){n[r[0]]={}}else n[r[0]]=r[1]||""}return n}return e(location.search)._mixin(e(location.hash))}this.__define({parse_url:{value:t},offline:{value:!1,writable:!0},local_storage_prefix:{value:"",writable:!0},create_tables:{value:!0,writable:!0},url_prm:{value:"undefined"!=typeof window?t():{}},rest_url:{value:function(){var t=e(),n=K.wsql.get_user_param("zone",K.job_prm.zone_is_string?"string":"number");return n?t.replace("%1",n):t.replace("%1/","")}},irest_url:{value:function(){var t=e(),n=K.wsql.get_user_param("zone",K.job_prm.zone_is_string?"string":"number");return t=t.replace("odata/standard.odata","hs/rest"),n?t.replace("%1",n):t.replace("%1/","")}}}),K.eve.callEvent("settings",[this]);for(var n in this)"url_prm"!==n&&"function"!=typeof this[n]&&this.url_prm.hasOwnProperty[n]&&(this[n]=this.url_prm[n])}/** * AES implementation in JavaScript (c) Chris Veness 2005-2016 * MIT Licence * www.movable-type.co.uk/scripts/aes.html */ -function T(e){"use strict";function t(e){return encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode("0x"+t)})}function n(e){try{return decodeURIComponent(escape(e))}catch(t){return e}}function r(e){if("undefined"!=typeof btoa)return btoa(e);if("undefined"!=typeof Buffer)return new Buffer(e,"binary").toString("base64");throw new Error("No Base64 Encode")}function a(e){if("undefined"!=typeof atob)return atob(e);if("undefined"!=typeof Buffer)return new Buffer(e,"base64").toString("binary");throw new Error("No Base64 Decode")}var i=this;i.cipher=function(e,t){for(var n=4,r=t.length/n-1,a=[[],[],[],[]],o=0;o<4*n;o++)a[o%4][Math.floor(o/4)]=e[o];a=i.addRoundKey(a,t,0,n);for(var s=1;s6&&s%n==4&&(o=i.subWord(o));for(var l=0;l<4;l++)a[s][l]=a[s-n][l]^o[l]}return a},i.subBytes=function(e,t){for(var n=0;n<4;n++)for(var r=0;r>>8*u&255;for(var u=0;u<2;u++)f[u+2]=m>>>8*u&255;for(var u=0;u<4;u++)f[u+4]=h>>>8*u&255;for(var y="",u=0;u<8;u++)y+=String.fromCharCode(f[u]);for(var g=i.keyExpansion(c),b=Math.ceil(n.length/s),v="",w=0;w>>8*x&255;for(var x=0;x<4;x++)f[15-x-4]=w/4294967296>>>8*x;for(var j=i.cipher(f,g),O=w>>8*v&255;for(var v=0;v<4;v++)d[15-v-4]=(g+1)/4294967296-1>>>8*v&255;for(var w=i.cipher(d,h),x=new Array(r[g].length),c=0;cприложениях Google Chrome",e.unknown_error="Неизвестная ошибка в функции '%1'",e.value="Значение"}(M.msg),s.prototype.__define({family_name:{get:function(){return M.msg["meta_"+this.class_name.split(".")[0]+"_mgr"].replace(M.msg.meta_mgr+" ","")}},table_name:{get:function(){return this.class_name.replace(".","_")}},find_rows:{value:function(e,t){return M._find_rows.call(this,this.by_ref,e,t)}},extra_fields:{value:function(e){var t=M.cat.destinations||M.cch.destinations,n=_md.class_name_to_1c(this.class_name).replace(".","_"),r=[];return t&&t.find_rows({predefined_name:n},function(e){var t=e.extra_fields||e.ДополнительныеРеквизиты;return t&&t.each(function(e){e._deleted||e.ПометкаУдаления||r.push(e.property||e.Свойство)}),!1}),r}},extra_properties:{value:function(e){return[]}},obj_constructor:{value:function(e){var t=this.class_name.split("."),n=t[0].charAt(0).toUpperCase()+t[0].substr(1)+t[1].charAt(0).toUpperCase()+t[1].substr(1);return e?n+e.charAt(0).toUpperCase()+e.substr(1)+"Row":n}}}),s.prototype.sync_grid=function(e,t){function n(){if("function"==typeof e.custom_selection)return e.custom_selection(e);if("ram"==a.cachable){if("get_tree"==e.action)return M.wsql.promise(a.get_sql_struct(e),[]).then(M.iface.data_to_tree);if("get_selection"==e.action)return M.wsql.promise(a.get_sql_struct(e),[]).then(function(t){return M.iface.data_to_grid.call(a,t,e)})}else if(0==a.cachable.indexOf("doc")){if("get_tree"==e.action)return a.pouch_tree(e);if("get_selection"==e.action)return a.pouch_selection(e)}else{if("get_tree"==e.action)return a.rest_tree(e);if("get_selection"==e.action)return a.rest_selection(e)}}function r(e){return new Promise(function(n,r){"string"==typeof e?("{"==e.substr(0,1)&&(e=JSON.parse(e)),t&&t.parse?(t.xmlFileUrl="exec",t.parse(e,function(){n(e)},"xml")):n(e)):t instanceof dhtmlXTreeView&&t.loadStruct?t.loadStruct(e,function(){n(e)}):n(e)})}var a=this;return n().then(r).catch(M.record_log)},s.prototype.get_option_list=function(e,t){function n(t){return M.utils.is_equal(t.value,e)&&(t.selected=!0),t}var r,a,i,o=this,s=[];if(t.presentation&&(r=o.metadata().input_by_string)&&(a=t.presentation.like,delete t.presentation,t.or=[],r.forEach(function(e){i={},i[e]={like:a},t.or.push(i)})),"ram"==o.cachable||t&&t._local)return o.find_rows(t,function(e){s.push(n({text:e.presentation,value:e.ref}))}),Promise.resolve(s);if("e1cib"!=o.cachable)return o.pouch_find_rows(t).then(function(e){return e.forEach(function(e){s.push(n({text:e.presentation,value:e.ref}))}),s});var _={selection:t,top:t._top},l=o instanceof g||o instanceof v;return delete t._top,l?_.fields=["ref","date","number_doc"]:o.metadata().main_presentation_name?_.fields=["ref","name"]:_.fields=["ref","id"],L.load_array(_,o).then(function(e){return e.forEach(function(e){s.push(n({text:l?e.number_doc+" от "+M.moment(e.date).format(M.moment._masks.ldt):e.name||e.id,value:e.ref}))}),s})},s.prototype.tabular_captions=function(e,t){},s.prototype.get_property_grid_xml=function(e,t,n){var r,a,i,o,s,_,l,u=this,c="",f=function(){if(!e)if(i=u.metadata(),i.form&&i.form.obj&&i.form.obj.head)e=i.form.obj.head;else{if(e={" ":[]},t instanceof O?(i.code_length&&e[" "].push("id"),i.main_presentation_name&&e[" "].push("name")):t instanceof k&&(e[" "].push("number_doc"),e[" "].push("date")),!t.is_folder)for(r in i.fields)"predefined_name"==r||i.fields[r].hide||e[" "].push(r);i.tabular_sections&&i.tabular_sections.extra_fields&&(e["Дополнительные реквизиты"]=[])}},d=function(e,t){_=M.utils.is_data_obj(e)?e.presentation:e,t.type.is_ref||(t.type.date_part?_=M.moment(_).format(M.moment._masks[t.type.date_part]):"boolean"==t.type.types[0]&&(_=_?"1":"0"))},p=function(e){s=_md.control_by_type(i.type,e),d(e,i)},h=function(e,r){if(r){var a=e.property||e.param||e.Параметр||e.Свойство,f=void 0!=e.value?e.value:e.Значение;a.empty()?(l=r+"|empty",s="ro",_="",i={synonym:"?"}):(i={synonym:a.presentation,type:a.type},l=r+"|"+a.ref,p(f),"edn"==s&&(s="calck"),a.mandatory&&(s+='" class="cell_mandatory'))}else if("object"==typeof e)l=e.id,i=n&&n.metadata&&n.metadata[l],i?e.synonym&&(i.synonym=e.synonym):i={synonym:e.synonym},s=e.type,_="",e.hasOwnProperty("txt")?_=e.txt:void 0!==(o=t[l])&&d(o,i.type?i:_md.get(u.class_name,l));else if(n&&n.metadata&&void 0!==(i=n.metadata[e]))l=e,p(o=t[e]);else{if(void 0===(o=t[e]))return;i=_md.get(u.class_name,l=e),p(o)}c+=''+(i.synonym||i.name)+''+_+""};f();for(r in e){" "!=r&&(c+=''+r+"");for(a in e[r])h(e[r][a]);if(n&&r==n.title&&t[n.ts]){var m,y=u.extra_fields(t),g="property,param,Свойство,Параметр".split(","),b=t[n.ts]._owner._metadata.tabular_sections[t[n.ts]._name].fields;g.some(function(e){if(b[e])return m=e,!0})&&(t[n.ts].forEach(function(e){var t=y.indexOf(e[m]);t!=-1&&y.splice(t,1)}),y.forEach(function(e){var r=t[n.ts].add();r[m]=e})),t[n.ts].find_rows(n.selection,function(e){h(e,n.ts)})}" "!=r&&(c+="")}return c+=""},s.prototype.print=function(e,t,n){function r(e){n&&n.progressOff&&n.progressOff(),e&&e.focus()}if(n&&n.progressOn&&n.progressOn(),setTimeout(r,3e3),this._printing_plates[t]instanceof j&&(t=this._printing_plates[t]),t instanceof j&&t.execute)return e instanceof j?t.execute(e).then(r):this.get(e,!0,!0).then(t.execute.bind(t)).then(r);var a={};return M.ajax.default_attr(a,M.job_prm.irest_url()),a.url+=this.rest_name+"(guid'"+M.utils.fix_guid(e)+"')/Print(model="+t+", browser_uid="+M.wsql.get_user_param("browser_uid")+")",M.ajax.get_and_show_blob(a.url,a,"get").then(r)},s.prototype.printing_plates=function(){var e={},t=this;return t._printing_plates||(t.metadata().printing_plates?t._printing_plates=t.metadata().printing_plates:("ram"==t.metadata().cachable||t.metadata().cachable&&0==t.metadata().cachable.indexOf("doc"))&&(t._printing_plates={})),!t._printing_plates&&M.ajax.authorized?(M.ajax.default_attr(e,M.job_prm.irest_url()),e.url+=t.rest_name+"/Print()",M.ajax.get_ex(e.url,e).then(function(e){return t._printing_plates=JSON.parse(e.response),t._printing_plates}).catch(function(){}).then(function(e){return e||(t._printing_plates={})})):Promise.resolve(t._printing_plates)},_._extend(s),_.prototype.__define({push:{value:function(e,t){t&&t!=e.ref?(delete this.by_ref[e.ref],this.by_ref[t]=e):this.by_ref[e.ref]=e}},each:{value:function(e){for(var t in this.by_ref)if(t&&t!=M.utils.blank.guid&&1==e.call(this,this.by_ref[t]))break}},forEach:{value:function(e){return this.each.call(this,e)}},get:{value:function(e,t,n){var r=this.by_ref[e]||this.by_ref[e=M.utils.fix_guid(e)];if(!r){if(n&&!t)return;r=new(M[this.obj_constructor()])(e,this,(!0))}return t===!1?r:void 0===t&&e===M.utils.blank.guid?r:r.is_new()?r.load():t?Promise.resolve(r):r}},create:{value:function(e,t,n){e&&"object"==typeof e||(e={}),e.ref&&M.utils.is_guid(e.ref)&&!M.utils.is_empty_guid(e.ref)||(e.ref=M.utils.generate_guid());var r=this.by_ref[e.ref];if(!r)if(r=new(M[this.obj_constructor()])(e,this),!t&&e.ref&&e.presentation&&2==Object.keys(e).length);else{r instanceof k&&r.date==M.utils.blank.date&&(r.date=new Date);var a=this.handle_event(r,"after_create");if(this instanceof g||this instanceof b||this instanceof v?r.number_doc||r.new_number_doc():!r.id&&r._metadata.code_length&&r.new_number_doc(),a===!1)return Promise.resolve(r);if("object"==typeof a&&a.then)return a;if("e1cib"==this.cachable&&t){var i={};return M.ajax.default_attr(i,M.job_prm.irest_url()),i.url+=this.rest_name+"/Create()",M.ajax.get_ex(i.url,i).then(function(e){return r._mixin(JSON.parse(e.response),void 0,["ref"])})}}return n?r:Promise.resolve(r)}},unload_obj:{value:function(e){delete this.by_ref[e],this.alatable.some(function(t,n,r){if(t.ref==e)return r.splice(n,1),!0})}},find:{value:function(e,t){return M._find(this.by_ref,e,t)}},load_array:{value:function(e,t){for(var n,r,a=[],i=0;i1&&(t&&(t+="\n"),t+="left outer join "+e[0][0]+" on "+e[0][0]+".ref = _t_."+e[1]));return t}function r(){var t;return t=o instanceof y?" WHERE ("+(f?0:1):s.hierarchical?s.has_owners?" WHERE ("+(l||f?1:0)+" OR _t_.parent = '"+u+"') AND ("+(_==M.utils.blank.guid?1:0)+" OR _t_.owner = '"+_+"') AND ("+(f?0:1):" WHERE ("+(l||f?1:0)+" OR _t_.parent = '"+u+"') AND ("+(f?0:1):s.has_owners?" WHERE ("+(_==M.utils.blank.guid?1:0)+" OR _t_.owner = '"+_+"') AND ("+(f?0:1):" WHERE ("+(f?0:1),o.sql_selection_where_flds?t+=o.sql_selection_where_flds(f):o instanceof g?t+=" OR _t_.number_doc LIKE '"+f+"'":((s.main_presentation_name||o instanceof y)&&(t+=" OR _t_.name LIKE '"+f+"'"),s.code_length&&(t+=" OR _t_.id LIKE '"+f+"'")),t+=") AND (_t_.ref != '"+M.utils.blank.guid+"')",e.selection&&("function"==typeof e.selection||e.selection.forEach(function(e){for(var n in e)if("function"==typeof e[n])t+="\n AND "+e[n](o,n)+" ";else if(s.fields.hasOwnProperty(n)||"ref"===n)if(e[n]===!0)t+="\n AND _t_."+n+" ";else if(e[n]===!1)t+="\n AND (not _t_."+n+") ";else if("object"==typeof e[n])if(M.utils.is_data_obj(e[n])||M.utils.is_guid(e[n]))t+="\n AND (_t_."+n+" = '"+e[n]+"') ";else{var r,a=Object.keys(e[n]),i=e[n][a[0]],_=s.fields[n];_&&_.type.is_ref&&(r=_md.value_mgr({},n,_.type,!0,i)),t+="not"==a[0]?"\n AND (not _t_."+n+" = '"+i+"') ":"in"==a[0]?"\n AND (_t_."+n+" in ("+e[n].in.reduce(function(e,t){return e&&(e+=","),e+="number"==typeof t?t.toString():"'"+t+"'"},"")+")) ":"\n AND (_t_."+n+" = '"+i+"') "}else t+="string"==typeof e[n]?"\n AND (_t_."+n+" = '"+e[n]+"') ":"\n AND (_t_."+n+" = "+e[n]+") ";else"is_folder"==n&&s.hierarchical&&s.group_hierarchy})),t}function a(){return o instanceof y?"ORDER BY id":s.hierarchical?s.group_hierarchy?"ORDER BY _t_.is_folder desc, is_initial_value, presentation":"ORDER BY _t_.parent desc, is_initial_value, presentation":"ORDER BY is_initial_value, presentation"}function i(){function t(t){t&&(d=e.set_parent=t.parent.ref,u=d,l=!1),f&&f.indexOf("%")==-1&&(f="%"+f+"%")}s.has_owners&&(_=e.owner,e.selection&&"function"!=typeof e.selection&&e.selection.forEach(function(e){e.owner&&(_="object"==typeof e.owner?e.owner.valueOf():e.owner,delete e.owner)}),_||(_=M.utils.blank.guid)),c!=M.utils.blank.guid&&l&&s.hierarchical?t(o.get(c,!1)):t()}var _,l=!e.parent,u=e.parent||M.utils.blank.guid,c=e.initial_value||M.utils.blank.guid,f=e.filter||"",d=M.utils.blank.guid;i();var p;return p=o.sql_selection_list_flds?o.sql_selection_list_flds(c):("SELECT %2, case when _t_.ref = '"+c+"' then 0 else 1 end as is_initial_value FROM `"+o.table_name+"` AS _t_ %j %3 %4 LIMIT 300").replace("%2",t()).replace("%j",n()),p.replace("%3",r()).replace("%4",a())}function n(){var t="CREATE TABLE IF NOT EXISTS ";if(e&&e.postgres){t+=o.table_name+" (ref uuid PRIMARY KEY NOT NULL, _deleted boolean",o instanceof g?t+=", posted boolean, date timestamp with time zone, number_doc character(11)":(s.code_length&&(t+=", id character("+s.code_length+")"),t+=", name character varying(50), is_folder boolean");for(a in s.fields)a.length>30?s.fields[a].short_name?i=s.fields[a].short_name:(l++,i=a[0]+l+a.substr(a.length-27)):i=a,t+=", "+i+_md.sql_type(o,a,s.fields[a].type,!0)+_md.sql_composite(s.fields,a,i,!0);for(a in s.tabular_sections)t+=", ts_"+a+" JSON"}else{t+="`"+o.table_name+"` (ref CHAR PRIMARY KEY NOT NULL, `_deleted` BOOLEAN",t+=o instanceof g?", posted boolean, date Date, number_doc CHAR":", id CHAR, name CHAR, is_folder BOOLEAN";for(a in s.fields)t+=_md.sql_mask(a)+_md.sql_type(o,a,s.fields[a].type)+_md.sql_composite(s.fields,a);for(a in s.tabular_sections)t+=", `ts_"+a+"` JSON"}return t+=")"}function r(){var e=["ref","_deleted"],t="INSERT INTO `"+o.table_name+"` (ref, `_deleted`",n="(?";"cat"==o.class_name.substr(0,3)?(t+=", id, name, is_folder",e.push("id"),e.push("name"),e.push("is_folder")):"doc"==o.class_name.substr(0,3)&&(t+=", posted, date, number_doc",e.push("posted"),e.push("date"),e.push("number_doc"));for(a in s.fields)t+=_md.sql_mask(a),e.push(a);for(a in s.tabular_sections)t+=", `ts_"+a+"`",e.push("ts_"+a);for(t+=") VALUES ",a=1;a%6',r=[],a="";if(t.form&&t.form.selection?r=t.form.selection.cols:this instanceof g?(r.push(new Col_struct("date","160","ro","left","server","Дата")),r.push(new Col_struct("number_doc","140","ro","left","server","Номер")),t.fields.note&&r.push(new Col_struct("note","*","ro","left","server",t.fields.note.synonym)),t.fields.responsible&&r.push(new Col_struct("responsible","*","ro","left","server",t.fields.responsible.synonym))):this instanceof y?(r.push(new Col_struct("id","140","ro","left","server","Код")),r.push(new Col_struct("presentation","*","ro","left","server","Наименование"))):r.push(new Col_struct("presentation","*","ro","left","server","Наименование")),e.get_header&&r.length){a="";for(var i in r)a+=n.replace("%1",r[i].id).replace("%2",r[i].width).replace("%3",r[i].type).replace("%4",r[i].align).replace("%5",r[i].sort).replace("%6",r[i].caption);a+=""}return{head:a,acols:r}}},load_cached_server_array:{value:function(e,t){var n,r=[],a=this,i=t?{class_name:a.class_name,rest_name:t}:a,o=!t;if(e.forEach(function(e){n=a.get(e.ref||e,!1,!0),(!n||o&&n.is_new())&&r.push(e.ref||e)}),r.length){var s={url:"",selection:{ref:{in:r}}};return o&&(s.fields=["ref"]),M.rest.build_select(s,i),M.ajax.get_ex(s.url,s).then(function(t){var n=JSON.parse(t.response);if(o)n=n.value;else{n=n.data;for(var r in n)!n[r].ref&&n[r].id&&(n[r].ref=n[r].id),n[r].Код&&(n[r].id=n[r].Код,delete n[r].Код),n[r]._not_set_loaded=!0}return a.load_array(n),e})}return Promise.resolve(e)}},predefined:{value:function(e){return this._predefined||(this._predefined={}),this._predefined[e]||(this._predefined[e]=this.get(),this.find_rows({predefined_name:e},function(t){return this._predefined[e]=t,!1})),this._predefined[e]}}}),l._extend(s),l.prototype.__define({create:{value:function(){return new(M[this.obj_constructor()])({},this)}},unload_obj:{value:function(){}}}),u._extend(_),u.prototype.__define({get:{value:function(e){if(e instanceof R)return e;e&&e!=M.utils.blank.guid||(e="_");var t=this[e];return t||(t=new R({name:e},this)),t}},push:{value:function(e,t){this.__define(t,{value:e})}},each:{value:function(e){this.alatable.forEach(function(t){t.ref&&"_"!=t.ref&&t.ref!=M.utils.blank.guid&&e.call(this[t.ref])}.bind(this))}}}),u.prototype.get_sql_struct=function(e){var t="CREATE TABLE IF NOT EXISTS ",n=e&&e.action?e.action:"create_table";return e&&e.postgres?"create_table"==n?t+=this.table_name+" (ref character varying(255) PRIMARY KEY NOT NULL, sequence INT, synonym character varying(255))":["insert","update","replace"].indexOf(n)!=-1?(t={},t[this.table_name]={sql:"INSERT INTO "+this.table_name+" (ref, sequence, synonym) VALUES ($1, $2, $3)",fields:["ref","sequence","synonym"],values:"($1, $2, $3)"}):"delete"==n&&(t="DELETE FROM "+this.table_name+" WHERE ref = $1"):"create_table"==n?t+="`"+this.table_name+"` (ref CHAR PRIMARY KEY NOT NULL, sequence INT, synonym CHAR)":["insert","update","replace"].indexOf(n)!=-1?(t={},t[this.table_name]={sql:"INSERT INTO `"+this.table_name+"` (ref, sequence, synonym) VALUES (?, ?, ?)",fields:["ref","sequence","synonym"],values:"(?, ?, ?)"}):"delete"==n&&(t="DELETE FROM `"+this.table_name+"` WHERE ref = ?"),t},u.prototype.get_option_list=function(e,t){function n(t){return M.utils.is_equal(t.value,e)&&(t.selected=!0),t}var r,a=[],i="";if(t)for(var o in t)"_"!=o.substr(0,1)&&("ref"==o?r=t[o].hasOwnProperty("in")?t[o].in:t[o]:i=t[o]);return"object"==typeof i&&(i=i.like?i.like:""),i=i.toLowerCase(),this.alatable.forEach(function(e){if(!i||e.synonym&&e.synonym.toLowerCase().indexOf(i)!=-1){if(r)if(Array.isArray(r)){if(!r.some(function(t){return t.name==e.ref||t.ref==e.ref||t==e.ref}))return}else if(r.name!=e.ref&&r.ref!=e.ref&&r!=e.ref)return; -a.push(n({text:e.synonym||"",value:e.ref}))}}),Promise.resolve(a)},c._extend(s),c.prototype.__define({get_sql_struct:{value:function(e){function t(){function t(){var e=[],t="_t_.ref";if(s.form&&s.form.selection)s.form.selection.fields.forEach(function(t){e.push(t)});else for(var n in s.dimensions)e.push(n);return e.forEach(function(e){t+=e.indexOf(" as ")!=-1?", "+e:_md.sql_mask(e,!0)}),t}function n(){var e,t="";if(s.form&&s.form.selection)for(var n in s.form.selection.fields)s.form.selection.fields[n].indexOf(" as ")!=-1&&s.form.selection.fields[n].indexOf("_t_.")==-1&&(e=s.form.selection.fields[n].split(" as "),e[0]=e[0].split("."),e[0].length>1&&(t&&(t+="\n"),t+="left outer join "+e[0][0]+" on "+e[0][0]+".ref = _t_."+e[1]));return t}function r(){var t=" WHERE ("+(i?0:1);return o.sql_selection_where_flds&&(t+=o.sql_selection_where_flds(i)),t+=")",e.selection&&("function"==typeof e.selection||e.selection.forEach(function(e){for(var n in e)if("function"==typeof e[n])t+="\n AND "+e[n](o,n)+" ";else if(s.fields.hasOwnProperty(n))if(e[n]===!0)t+="\n AND _t_."+n+" ";else if(e[n]===!1)t+="\n AND (not _t_."+n+") ";else if("object"==typeof e[n])if(M.utils.is_data_obj(e[n]))t+="\n AND (_t_."+n+" = '"+e[n]+"') ";else{var r,a=Object.keys(e[n]),i=e[n][a[0]],_=s.fields[n];_&&_.type.is_ref&&(r=_md.value_mgr({},n,_.type,!0,i)),t+="not"==a[0]?"\n AND (not _t_."+n+" = '"+i+"') ":"\n AND (_t_."+n+" = '"+i+"') "}else t+="string"==typeof e[n]?"\n AND (_t_."+n+" = '"+e[n]+"') ":"\n AND (_t_."+n+" = "+e[n]+") ";else"is_folder"==n&&s.hierarchical&&s.group_hierarchy})),t}function a(){return""}var i=e.filter||"";i&&i.indexOf("%")==-1&&(i="%"+i+"%");var _;return _=o.sql_selection_list_flds?o.sql_selection_list_flds():("SELECT %2 FROM `"+o.table_name+"` AS _t_ %j %3 %4 LIMIT 300").replace("%2",t()).replace("%j",n()),_.replace("%3",r()).replace("%4",a())}function n(){var t="CREATE TABLE IF NOT EXISTS ",n=!0;if(e&&e.postgres){t+=o.table_name+" (",s.splitted&&(t+="zone integer",n=!1);for(i in s.dimensions)n?(t+=i,n=!1):t+=", "+i,t+=_md.sql_type(o,i,s.dimensions[i].type,!0)+_md.sql_composite(s.dimensions,i,"",!0);for(i in s.resources)t+=", "+i+_md.sql_type(o,i,s.resources[i].type,!0)+_md.sql_composite(s.resources,i,"",!0);for(i in s.attributes)t+=", "+i+_md.sql_type(o,i,s.attributes[i].type,!0)+_md.sql_composite(s.attributes,i,"",!0);t+=", PRIMARY KEY (",n=!0,s.splitted&&(t+="zone",n=!1);for(i in s.dimensions)n?(t+=i,n=!1):t+=", "+i}else{t+="`"+o.table_name+"` (ref CHAR PRIMARY KEY NOT NULL, `_deleted` BOOLEAN";for(i in s.dimensions)t+=_md.sql_mask(i)+_md.sql_type(o,i,s.dimensions[i].type);for(i in s.resources)t+=_md.sql_mask(i)+_md.sql_type(o,i,s.resources[i].type);for(i in s.attributes)t+=_md.sql_mask(i)+_md.sql_type(o,i,s.attributes[i].type)}return t+=")"}function r(){var e="INSERT OR REPLACE INTO `"+o.table_name+"` (",t=[],n=!0;for(i in s.dimensions)n?(e+=i,n=!1):e+=", "+i,t.push(i);for(i in s.resources)e+=", "+i,t.push(i);for(i in s.attributes)e+=", "+i,t.push(i);for(e+=") VALUES (?",i=1;i%6',r=[],a="";if(t.form&&t.form.selection)r=t.form.selection.cols;else for(var i in t.dimensions)r.push(new Col_struct(i,"*","ro","left","server",t.dimensions[i].synonym));if(e.get_header&&r.length){a="";for(var o in r)a+=n.replace("%1",r[o].id).replace("%2",r[o].width).replace("%3",r[o].type).replace("%4",r[o].align).replace("%5",r[o].sort).replace("%6",r[o].caption);a+=""}return{head:a,acols:r}}},create:{value:function(e){e&&"object"==typeof e||(e={});var t=this.by_ref[e.ref];if(!t){t=new(M[this.obj_constructor()])(e,this);var n=this.handle_event(t,"after_create");if(n===!1)return Promise.resolve(t);if("object"==typeof n&&n.then)return n}return Promise.resolve(t)}}}),f._extend(c),f.prototype.slice_first=function(e){},f.prototype.slice_last=function(e){},d._extend(f),p._extend(c),h._extend(_),h.prototype.by_name=function(e){var t;return this.find_rows({name:e},function(e){return t=e,!1}),t||(t=this.get()),t},h.prototype.by_id=function(e){var t;return this.find_rows({id:e},function(e){return t=e,!1}),t||(t=this.get()),t},h.prototype.path=function(e){var t,n=[];if(t=e instanceof j?e:this.get(e,!1,!0),t&&n.push({ref:t.ref,presentation:t.presentation}),t&&this.metadata().hierarchical)for(;;){if(t=t.parent,t.empty())break;n.push({ref:t.ref,presentation:t.presentation})}return n},m._extend(h),y._extend(h),g._extend(_),b._extend(h),v._extend(h),w.prototype.toString=function(){return"Табличная часть "+this._owner._manager.class_name+"."+this._name},w.prototype.get=function(e){return this._obj[e]?this._obj[e]._row:null},w.prototype.count=function(){return this._obj.length},w.prototype.clear=function(e){for(var t in this._obj)delete this._obj[t];return this._obj.length=0,e||this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name}),this},w.prototype.del=function(e,t){var n,r=this._obj;if("undefined"!=typeof e){if("number"==typeof e)n=e;else if(r[e.row-1]._row===e)n=e.row-1;else for(var a in r)if(r[a]._row===e){n=Number(a),delete r[a]._row;break}void 0!=n&&(r.splice(n,1),r.forEach(function(e,t){e.row=t+1}),t||this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name}),this._owner._data._modified=!0)}},w.prototype.find=function(e,t){var n=M._find(this._obj,e,t);if(n)return n._row},w.prototype.find_rows=function(e,t){var n=this,r=t?function(e){return t.call(n,e._row)}:null;return M._find_rows.call(n,n._obj,e,r)},w.prototype.swap=function(e,t){var n=this._obj[e];this._obj[e]=this._obj[t],this._obj[t]=n,this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name})},w.prototype.add=function(e,t){var n=new(M[this._owner._manager.obj_constructor(this._name)])(this);e||(e={});for(var r in n._metadata.fields)n[r]=e[r]||"";return n._obj.row=this._obj.push(n._obj),n._obj.__define("_row",{value:n,enumerable:!1}),t||this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name}),e=null,this._owner._data._modified=!0,n},w.prototype.each=function(e){var t=this;t._obj.forEach(function(n){return e.call(t,n._row)})},w.prototype.forEach=w.prototype.each,w.prototype.group_by=function(e,t){try{var n=this.aggregate(e,t,"SUM",!0);return this.clear(!0).load(n)}catch(e){}},w.prototype.sort=function(e){"string"==typeof e&&(e=e.split(","));var t="select * from ? order by ",n=!0;e.forEach(function(e){e=e.trim().replace(/\s{1,}/g," ").split(" "),n?n=!1:t+=", ",t+="`"+e[0]+"`",e[1]&&(t+=" "+e[1])});try{return n=M.wsql.alasql(t,[this._obj]),this.clear(!0).load(n)}catch(e){M.record_log(e)}},w.prototype.aggregate=function(e,t,n,r){if("string"==typeof e&&(e=e.split(",")),"string"==typeof t&&(t=t.split(",")),n||(n="sum"),!e.length&&1==t.length&&"sum"==n)return this._obj.reduce(function(e,n,r,a){return e+n[t[0]]},0);var a,i=!0;t.forEach(function(e){a?a+=", "+n+"(`"+e+"`) `"+e+"`":a="select "+n+"(`"+e+"`) `"+e+"`"}),e.forEach(function(e){a?a+=", `"+e+"`":a="select `"+e+"`"}),a+=" from ? ",e.forEach(function(e){i?(a+="group by ",i=!1):a+=", ",a+="`"+e+"`"});try{return i=M.wsql.alasql(a,[this._obj]),r||(i=1==t.length?i.length?i[0][t[0]]:0:i.length?i[0]:{}),i}catch(e){M.record_log(e)}},w.prototype.load=function(e){var t,n=this;return n.clear(!0),e instanceof w?t=e._obj:Array.isArray(e)&&(t=e),t&&t.forEach(function(e){n.add(e,!0)}),this._owner._data._silent||Object.getNotifier(n._owner).notify({type:"rows",tabular:n._name}),n},w.prototype.sync_grid=function(e,t){for(var n={rows:[]},r=[],a=0;a"+_+""}}var n,r,a,i,o,s,_,l='\t\t\t\t\n<updated>%d</updated><author/><summary/><content type="application/xml">\t\t\t\t\n<m:properties xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">\t\t\t%p\t\t\t\n</m:properties></content></entry>'.replace("%n",this._manager.rest_name).replace("%d",M.moment().format(M.moment.defaultFormatUtc)),u="\n<d:Ref_Key>"+this.ref+"</d:Ref_Key>\n<d:DeletionMark>"+this._deleted+"</d:DeletionMark>";this instanceof k?(u+="\n<d:Date>"+M.moment(this.date).format(M.moment.defaultFormatUtc)+"</d:Date>",u+="\n<d:Number>"+this.number_doc+"</d:Number>"):(this._metadata.main_presentation_name&&(u+="\n<d:Description>"+this.name+"</d:Description>"),this._metadata.code_length&&(u+="\n<d:Code>"+this.id+"</d:Code>"),this._metadata.hierarchical&&this._metadata.group_hierarchy&&(u+="\n<d:IsFolder>"+this.is_folder+"</d:IsFolder>")),t(this);for(a in this._metadata.tabular_sections)o=this._metadata.tabular_sections[a],s="StandardODATA."+this._manager.rest_name+"_"+_md.syns_1с(a)+"_RowType",i=this[a],i.count()?(u+="\n<d:"+_md.syns_1с(a)+' m:type="Collection('+s+')">',i.each(function(e){u+='\n\t<d:element m:type="'+s+'">',u+="\n\t<d:LineNumber>"+e.row+"</d:LineNumber>",t(e),u+="\n\t</d:element>"}),u+="\n</d:"+_md.syns_1с(a)+">"):u+="\n<d:"+_md.syns_1с(a)+' m:type="Collection('+s+')" />';return l.replace("%p",u)},s.prototype.__define({pouch_load_array:{value:function(e,t){var n={limit:e.length+1,include_docs:!0,keys:e.map(function(e){return this.class_name+"|"+e}.bind(this))};return t&&(n.attachments=!0,n.binary=!0),this.pouch_db.allDocs(n).then(function(e){return M.wsql.pouch.load_changes(e,{})})}},pouch_load_view:{value:function(e){var t,n=this,r=[],a={limit:1e3,include_docs:!0,startkey:n.class_name+"|",endkey:n.class_name+"|￿"};return new Promise(function(i,o){function s(_,l){l?l.rows.length?(a.startkey=l.rows[l.rows.length-1].key,a.skip=1,l.rows.forEach(function(e){t=e.doc,key=t._id.split("|"),t.ref=key[1],r.push(t)}),n.load_array(r),r.length=0,n.pouch_db.query(e,a,s)):i():_&&o(_)}n.pouch_db.query(e,a,s)})}},pouch_db:{get:function(){return this.cachable.indexOf("_remote")!=-1?M.wsql.pouch.remote[this.cachable.replace("_remote","")]:M.wsql.pouch.local[this.cachable]||M.wsql.pouch.remote[this.cachable]}},pouch_find_rows:{value:function(e){var t,n,r,a,i,o,s=this,_=[],l=0,u=0,c=0,f={limit:100,include_docs:!0,startkey:s.class_name+"|",endkey:s.class_name+"|￿"};return e&&(e._top?(i=e._top,delete e._top):i=300,e._raw&&(n=e._raw,delete e._raw),e._total_count&&(a=e._total_count,delete e._total_count),e._view&&(r=e._view,delete e._view),e._key&&("des"==e._key._order_by?(f.startkey=e._key.endkey||e._key+"￿",f.endkey=e._key.startkey||e._key,f.descending=!0):(f.startkey=e._key.startkey||e._key,f.endkey=e._key.endkey||e._key+"￿")),"number"==typeof e._skip&&(u=e._skip,delete e._skip),e._attachments&&(f.attachments=!0,f.binary=!0,delete e._attachments)),a&&(o=!0,a=0,Object.keys(e).length<=1&&e._key&&e._key.hasOwnProperty("_search"))?(f.include_docs=!1,f.limit=1e5,s.pouch_db.query(r,f).then(function(t){return t.rows.forEach(function(t){if(!e._key._search||t.key[t.key.length-1].toLowerCase().indexOf(e._key._search)!=-1){if(a++,u&&(c++,c<u))return;if(i&&(l++,l>i))return;_.push(t.id)}}),delete f.startkey,delete f.endkey,f.descending&&delete f.descending,f.keys=_,f.include_docs=!0,s.pouch_db.allDocs(f)}).then(function(e){return{rows:e.rows.map(function(e){var t=e.doc;return t.ref=t._id.split("|")[1],n||(delete t._id,delete t._rev),t}),_total_count:a}})):new Promise(function(d,p){function h(r,h){h?h.rows.length?(f.startkey=h.rows[h.rows.length-1].key,f.skip=1,h.rows.forEach(function(r){t=r.doc,key=t._id.split("|"),t.ref=key[1],n||(delete t._id,delete t._rev),M._selection.call(s,t,e)&&(o&&a++,u&&(c++,c<u)||i&&(l++,l>i)||_.push(t))}),i&&l>i&&!o?d(n?_:s.load_array(_)):m()):d(o?{rows:n?_:s.load_array(_),_total_count:a}:n?_:s.load_array(_)):r&&p(r)}function m(){r?s.pouch_db.query(r,f,h):s.pouch_db.allDocs(f,h)}m()})}},pouch_selection:{value:function(e){var t,n,r,a=this,i=e.metadata||a.metadata(),o=["ref","_deleted"],s={_raw:!0,_total_count:!0,_top:e.count||30,_skip:e.start||0},_=[];if(i.form&&i.form.selection?i.form.selection.fields.forEach(function(e){o.push(e)}):a instanceof g?(o.push("posted"),o.push("date"),o.push("number_doc")):a instanceof b?(o.push("name as presentation"),o.push("date"),o.push("number_doc"),o.push("completed")):a instanceof v?(o.push("date"),o.push("number_doc"),o.push("started"),o.push("finished")):(i.hierarchical&&i.group_hierarchy?o.push("is_folder"):o.push("0 as is_folder"),i.main_presentation_name?o.push("name as presentation"):i.code_length?o.push("id as presentation"):o.push("'...' as presentation"),i.has_owners&&o.push("owner"),i.code_length&&o.push("id")),_md.get(a.class_name,"date")&&(e.date_from||e.date_till)&&(e.date_from||(e.date_from=new Date("2015-01-01")),e.date_till||(e.date_till=M.utils.date_add_day(new Date,1)),s.date={between:[e.date_from,e.date_till]}),i.hierarchical&&e.parent&&(s.parent=e.parent),e.selection)if(Array.isArray(e.selection))e.selection.forEach(function(e){for(r in e)"_"==r[0]&&"_view"!=r&&"_key"!=r||(s[r]=e[r])});else for(r in e.selection)"_"==r[0]&&"_view"!=r&&"_key"!=r||(s[r]=e.selection[r]);return s._key&&s._key._drop_date&&s.date&&delete s.date,!e.filter||s._key&&s._key._search||(1==i.input_by_string.length?s[i.input_by_string]={like:e.filter}:(s.or=[],i.input_by_string.forEach(function(t){var n={};n[t]={like:e.filter},s.or.push(n)}))),s._key&&s._key._order_by&&(s._key._order_by=e.direction),a.pouch_find_rows(s).then(function(i){return i.hasOwnProperty("_total_count")&&i.hasOwnProperty("rows")&&(e._total_count=i._total_count,i=i.rows),i.forEach(function(e){t={},o.forEach(function(i){if("ref"==i)return void(t[i]=e[i]);if(i.indexOf(" as ")!=-1?(r=i.split(" as ")[1],i=i.split(" as ")[0].split("."),i=i[i.length-1]):r=i,n=_md.get(a.class_name,i))if(n.type.date_part)t[r]=M.moment(e[i]).format(M.moment._masks[n.type.date_part]);else if(n.type.is_ref)if(e[i]&&e[i]!=M.utils.blank.guid){var o=_md.value_mgr(t,i,n.type,!1,e[i]);o?t[r]=o.get(e[i]).presentation:t[r]=""}else t[r]="";else"number"==typeof e[i]&&n.type.fraction_figits?t[r]=e[i].toFixed(n.type.fraction_figits):t[r]=e[i]}),_.push(t)}),M.iface.data_to_grid.call(a,_,e)}).catch(M.record_log)}},pouch_tree:{value:function(e){return this.pouch_find_rows({is_folder:!0,_raw:!0,_top:e.count||300,_skip:e.start||0}).then(function(e){return e.sort(function(e,t){return e.parent==M.utils.blank.guid&&t.parent!=M.utils.blank.guid?-1:t.parent==M.utils.blank.guid&&e.parent!=M.utils.blank.guid?1:e.name<t.name?-1:e.name>t.name?1:0}),e.map(function(e){return{ref:e.ref,parent:e.parent,presentation:e.name}})}).then(M.iface.data_to_tree)}},save_attachment:{value:function(e,t,n,r){r||(r={type:"text/plain"}),n instanceof Blob||r.indexOf("text")!=-1||(n=new Blob([n],{type:r}));var a,i=this.pouch_db;return e=this.class_name+"|"+M.utils.fix_guid(e),i.get(e).then(function(e){e&&(a=e._rev)}).catch(function(e){if(404!=e.status)throw e}).then(function(){return i.putAttachment(e,t,a,n,r)})}},get_attachment:{value:function(e,t){return this.pouch_db.getAttachment(this.class_name+"|"+M.utils.fix_guid(e),t)}},delete_attachment:{value:function(e,t){var n,r=this.pouch_db;return e=this.class_name+"|"+M.utils.fix_guid(e),r.get(e).then(function(e){e&&(n=e._rev)}).catch(function(e){if(404!=e.status)throw e}).then(function(){return r.removeAttachment(e,t,n)})}}}),j.prototype.__define({new_number_doc:{value:function(e){if(this._metadata.code_length){e||(e=(M.current_acl&&M.current_acl.prefix||"")+(this.organization&&this.organization.prefix?this.organization.prefix:M.wsql.get_user_param("zone")+"-"));var t=this,n="",r=this.date instanceof Date?this.date.getFullYear():0,a=this._metadata.code_length-e.length;return"ram"==this._manager.cachable?Promise.resolve(this.new_cat_id(e)):t._manager.pouch_db.query("doc/number_doc",{limit:1,include_docs:!1,startkey:[t._manager.class_name,r,e+"￿"],endkey:[t._manager.class_name,r,e],descending:!0}).then(function(r){if(r.rows.length){for(var i=r.rows[0].key[2],o=i.length-1;o>0&&!isNaN(parseInt(i[o]));o--)n=i[o]+n;n=(parseInt(n||0)+1).toFixed(0)}else n="1";for(;n.length<a;)n="0"+n;return t instanceof k||t instanceof A||t instanceof D?t.number_doc=e+n:t.id=e+n,t})}}},new_cat_id:{value:function(e){e||(e=(M.current_acl&&M.current_acl.prefix||"")+(this.organization&&this.organization.prefix?this.organization.prefix:M.wsql.get_user_param("zone")+"-"));var t=this._metadata.code_length-e.length,n=this instanceof k||this instanceof A||this instanceof D?"number_doc":"id",r="",a=M.wsql.alasql("select top 1 "+n+" as id from ? where "+n+" like '"+e+"%' order by "+n+" desc",[this._manager.alatable]);if(a.length){for(var i=a[0].id||"",o=i.length-1;o>0&&!isNaN(parseInt(i[o]));o--)r=i[o]+r;r=(parseInt(r||0)+1).toFixed(0)}else r="1";for(;r.length<t;)r="0"+r;return this[n]=e+r,this}}}),"undefined"!=typeof module&&module.exports&&(module.exports=T),M}); \ No newline at end of file +function I(e){"use strict";function t(e){return encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode("0x"+t)})}function n(e){try{return decodeURIComponent(escape(e))}catch(t){return e}}function r(e){if("undefined"!=typeof btoa)return btoa(e);if("undefined"!=typeof Buffer)return new Buffer(e,"binary").toString("base64");throw new Error("No Base64 Encode")}function a(e){if("undefined"!=typeof atob)return atob(e);if("undefined"!=typeof Buffer)return new Buffer(e,"base64").toString("binary");throw new Error("No Base64 Decode")}var i=this;i.cipher=function(e,t){for(var n=4,r=t.length/n-1,a=[[],[],[],[]],o=0;o<4*n;o++)a[o%4][Math.floor(o/4)]=e[o];a=i.addRoundKey(a,t,0,n);for(var s=1;s<r;s++)a=i.subBytes(a,n),a=i.shiftRows(a,n),a=i.mixColumns(a,n),a=i.addRoundKey(a,t,s,n);a=i.subBytes(a,n),a=i.shiftRows(a,n),a=i.addRoundKey(a,t,r,n);for(var l=new Array(4*n),o=0;o<4*n;o++)l[o]=a[o%4][Math.floor(o/4)];return l},i.keyExpansion=function(e){for(var t=4,n=e.length/4,r=n+6,a=new Array(t*(r+1)),o=new Array(4),s=0;s<n;s++){var l=[e[4*s],e[4*s+1],e[4*s+2],e[4*s+3]];a[s]=l}for(var s=n;s<t*(r+1);s++){a[s]=new Array(4);for(var _=0;_<4;_++)o[_]=a[s-1][_];if(s%n==0){o=i.subWord(i.rotWord(o));for(var _=0;_<4;_++)o[_]^=i.rCon[s/n][_]}else n>6&&s%n==4&&(o=i.subWord(o));for(var _=0;_<4;_++)a[s][_]=a[s-n][_]^o[_]}return a},i.subBytes=function(e,t){for(var n=0;n<4;n++)for(var r=0;r<t;r++)e[n][r]=i.sBox[e[n][r]];return e},i.shiftRows=function(e,t){for(var n=new Array(4),r=1;r<4;r++){for(var a=0;a<4;a++)n[a]=e[r][(a+r)%t];for(var a=0;a<4;a++)e[r][a]=n[a]}return e},i.mixColumns=function(e,t){for(var n=0;n<4;n++){for(var r=new Array(4),a=new Array(4),i=0;i<4;i++)r[i]=e[i][n],a[i]=128&e[i][n]?e[i][n]<<1^283:e[i][n]<<1;e[0][n]=a[0]^r[1]^a[1]^r[2]^r[3],e[1][n]=r[0]^a[1]^r[2]^a[2]^r[3],e[2][n]=r[0]^r[1]^a[2]^r[3]^a[3],e[3][n]=r[0]^a[0]^r[1]^r[2]^a[3]}return e},i.addRoundKey=function(e,t,n,r){for(var a=0;a<4;a++)for(var i=0;i<r;i++)e[a][i]^=t[4*n+i][a];return e},i.subWord=function(e){for(var t=0;t<4;t++)e[t]=i.sBox[e[t]];return e},i.rotWord=function(e){for(var t=e[0],n=0;n<3;n++)e[n]=e[n+1];return e[3]=t,e},i.sBox=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],i.rCon=[[0,0,0,0],[1,0,0,0],[2,0,0,0],[4,0,0,0],[8,0,0,0],[16,0,0,0],[32,0,0,0],[64,0,0,0],[128,0,0,0],[27,0,0,0],[54,0,0,0]],i.Ctr={},i.Ctr.encrypt=function(n,a,o){var s=16;128!=o&&192!=o&&256!=o&&(o=128),n=t(n),a=t(a||e);for(var l=o/8,_=new Array(l),u=0;u<l;u++)_[u]=u<a.length?a.charCodeAt(u):0;var c=i.cipher(_,i.keyExpansion(_));c=c.concat(c.slice(0,l-16));for(var f=new Array(s),d=(new Date).getTime(),p=d%1e3,h=Math.floor(d/1e3),m=Math.floor(65535*Math.random()),u=0;u<2;u++)f[u]=p>>>8*u&255;for(var u=0;u<2;u++)f[u+2]=m>>>8*u&255;for(var u=0;u<4;u++)f[u+4]=h>>>8*u&255;for(var y="",u=0;u<8;u++)y+=String.fromCharCode(f[u]);for(var g=i.keyExpansion(c),b=Math.ceil(n.length/s),v="",w=0;w<b;w++){for(var x=0;x<4;x++)f[15-x]=w>>>8*x&255;for(var x=0;x<4;x++)f[15-x-4]=w/4294967296>>>8*x;for(var j=i.cipher(f,g),O=w<b-1?s:(n.length-1)%s+1,k=new Array(O),u=0;u<O;u++)k[u]=j[u]^n.charCodeAt(w*s+u),k[u]=String.fromCharCode(k[u]);v+=k.join(""),"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&w%1e3==0&&self.postMessage({progress:w/b})}return v=r(y+v)},i.Ctr.decrypt=function(r,o,s){var l=16;128!=s&&192!=s&&256!=s&&(s=128),r=a(r),o=t(o||e);for(var _=s/8,u=new Array(_),c=0;c<_;c++)u[c]=c<o.length?o.charCodeAt(c):0;var f=i.cipher(u,i.keyExpansion(u));f=f.concat(f.slice(0,_-16));for(var d=new Array(8),p=r.slice(0,8),c=0;c<8;c++)d[c]=p.charCodeAt(c);for(var h=i.keyExpansion(f),m=Math.ceil((r.length-8)/l),y=new Array(m),g=0;g<m;g++)y[g]=r.slice(8+g*l,8+g*l+l);r=y;for(var b="",g=0;g<m;g++){for(var v=0;v<4;v++)d[15-v]=g>>>8*v&255;for(var v=0;v<4;v++)d[15-v-4]=(g+1)/4294967296-1>>>8*v&255;for(var w=i.cipher(d,h),x=new Array(r[g].length),c=0;c<r[g].length;c++)x[c]=w[c]^r[g].charCodeAt(c),x[c]=String.fromCharCode(x[c]);b+=x.join(""),"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&g%1e3==0&&self.postMessage({progress:g/m})}return b=n(b)}}Object.defineProperties(Object.prototype,{__define:{value:function(e,t){return t?Object.defineProperty(this,e,t):Object.defineProperties(this,e),this}},_extend:{value:function(e){var t=function(){};t.prototype=e.prototype,this.prototype=new t,this.prototype.constructor=this,this.__define("superclass",{value:e.prototype,enumerable:!1})}},_mixin:{value:function(e,t,n){var r,a,i={};if(t&&t.length)for(r=0;r<t.length;r++)a=t[r],n&&n.indexOf(a)!=-1||"undefined"!=typeof i[a]&&i[a]==e[a]||(this[a]=e[a]);else for(a in e)n&&n.indexOf(a)!=-1||"undefined"!=typeof i[a]&&i[a]==e[a]||(this[a]=e[a]);return this}},_clone:{value:function(){if(!this||"object"!=typeof this)return this;var e,t,n="function"==typeof this.pop?[]:{};for(e in this)this.hasOwnProperty(e)&&(t=this[e],t?"function"==typeof t||t instanceof E||t instanceof s||t instanceof Date?n[e]=t:"object"==typeof t?n[e]=t._clone():n[e]=t:n[e]=t);return n}}}),Number.prototype.round||(Number.prototype.round=function(e){var t=Math.pow(10,e);return Math.round(this*t)/t}),Number.prototype.pad||(Number.prototype.pad=function(e){for(var t=String(this);t.length<(e||2);)t="0"+t;return t}),Object.observe||Object.unobserve||Object.getNotifier||Object.prototype.__define({observe:{value:function(e,t){e._observers||e.__define({_observers:{value:[],enumerable:!1},_notis:{value:[],enumerable:!1}}),e._observers.push(t)},enumerable:!1},unobserve:{value:function(e,t){if(e._observers){t||(e._observers.length=0);for(var n=0;n<e._observers.length;n++)if(e._observers[n]===t){e._observers.splice(n,1);break}}},enumerable:!1},getNotifier:{value:function(e){var t;return{notify:function(n){e._observers&&n&&(n.object||(n.object=e),e._notis.push(n),n=null,t&&clearTimeout(t),t=setTimeout(function(){e._notis.length&&(e._observers.forEach(function(t){t(e._notis)}),e._notis.length=0),t=!1},4))}}},enumerable:!1}});var K=new e;"undefined"!=typeof window&&window.dhx4&&(dhx4.dateFormat.ru="%d.%m.%Y",dhx4.dateLang="ru",dhx4.dateStrings={ru:{monthFullName:["Январь","Февраль","Март","Апрель","Maй","Июнь","Июль","Август","Сентябрь","Oктябрь","Ноябрь","Декабрь"],monthShortName:["Янв","Фев","Maр","Aпр","Maй","Июн","Июл","Aвг","Сен","Окт","Ноя","Дек"],dayFullName:["Воскресенье","Понедельник","Вторник","Среда","Четверг","Пятница","Суббота"],dayShortName:["Вс","Пн","Вт","Ср","Чт","Пт","Сб"]}}),K.fias=function(){},function(e){e.toString=function(){return"Коды адресного классификатора"},e.types=["владение","здание","помещение"],e[1010]={name:"дом",type:1,order:1,fid:2,syn:[" д."," д "," дом"]},e[1020]={name:"владение",type:1,order:2,fid:1,syn:[" вл."," вл "," влад."," влад "," владен."," владен "," владение"]},e[1030]={name:"домовладение",type:1,order:3,fid:3},e[1050]={name:"корпус",type:2,order:1,syn:[" к."," к "," корп."," корп ","корпус"]},e[1060]={name:"строение",type:2,order:2,fid:1,syn:[" стр."," стр "," строен."," строен ","строение"]},e[1080]={name:"литера",type:2,order:3,fid:3,syn:[" л."," л "," лит."," лит ","литера"]},e[1070]={name:"сооружение",type:2,order:4,fid:2,syn:[" соор."," соор "," сооруж."," сооруж ","сооружение"]},e[1040]={name:"участок",type:2,order:5,syn:[" уч."," уч ","участок"]},e[2010]={name:"квартира",type:3,order:1,syn:["кв.","кв ","кварт.","кварт ","квартира","-"]},e[2030]={name:"офис",type:3,order:2,syn:["оф.","оф ","офис","-"]},e[2040]={name:"бокс",type:3,order:3},e[2020]={name:"помещение",type:3,order:4},e[2050]={name:"комната",type:3,order:5,syn:["комн.","комн ","комната"]},e[101e5]={name:"Почтовый индекс"},e[102e5]={name:"Адресная точка"},e[103e5]={name:"Садовое товарищество"},e[104e5]={name:"Элемент улично-дорожной сети, планировочной структуры дополнительного адресного элемента"},e[105e5]={name:"Промышленная зона"},e[106e5]={name:"Гаражно-строительный кооператив"},e[107e5]={name:"Территория"}}(K.fias),function(e){e.store_url_od="https://chrome.google.com/webstore/detail/hcncallbdlondnoadgjomnhifopfaage",e.argument_is_not_ref="Аргумент не является ссылкой",e.addr_title="Ввод адреса",e.cache_update_title="Обновление кеша браузера",e.cache_update="Выполняется загрузка измененных файлов<br/>и их кеширование в хранилище браузера",e.cancel="Отмена",e.delivery_area_empty="Укажите район доставки",e.empty_login_password="Не указаны имя пользователя или пароль",e.empty_response="Пустой ответ сервера",e.empty_geocoding="Пустой ответ геокодера. Вероятно, отслеживание адреса запрещено в настройках браузера",e.error_geocoding="Ошибка геокодера",e.error_auth="Авторизация пользователя не выполнена",e.error_critical="Критическая ошибка",e.error_metadata="Ошибка загрузки метаданных конфигурации",e.error_network="Ошибка сети или сервера - запрос отклонен",e.error_rights="Ограничение доступа",e.error_low_acl="Недостаточно прав для выполнения операции",e.file_size="Запрещена загрузка файлов<br/>размером более ",e.file_confirm_delete="Подтвердите удаление файла ",e.file_new_date="Файлы на сервере обновлены<br /> Рекомендуется закрыть браузер и войти<br />повторно для применения обновления",e.file_new_date_title="Версия файлов",e.init_catalogues="Загрузка справочников с сервера",e.init_catalogues_meta=": Метаданные объектов",e.init_catalogues_tables=": Реструктуризация таблиц",e.init_catalogues_nom=": Базовые типы + номенклатура",e.init_catalogues_sys=": Технологические справочники",e.init_login="Укажите имя пользователя и пароль",e.requery="Повторите попытку через 1-2 минуты",e.limit_query="Превышено число обращений к серверу<br/>Запросов за минуту:%1<br/>Лимит запросов:%2<br/>"+e.requery,e.long_operation="Длительная операция",e.logged_in="Авторизован под именем: ",e.log_out_title="Отключиться от сервера?",e.log_out_break="<br/>Завершить синхронизацию?",e.sync_title="Обмен с сервером",e.sync_complite="Синхронизация завершена",e.main_title="Окнософт: заказ дилера ",e.mark_delete_confirm="Пометить объект %1 на удаление?",e.mark_undelete_confirm="Снять пометку удаления с объекта %1?",e.meta={cat:"Справочник",doc:"Документ",cch:"План видов характеристик",cacc:"Планы счетов",tsk:"Задача",ireg:"Регистр сведений",areg:"Регистр накопления",bp:"Бизнес процесс",ts_row:"Строка табличной части",dp:"Обработка",rep:"Отчет"},e.meta_cat="Справочники",e.meta_doc="Документы",e.meta_cch="Планы видов характеристик",e.meta_cacc="Планы счетов",e.meta_tsk="Задачи",e.meta_ireg="Регистры сведений",e.meta_areg="Регистры накопления",e.meta_mgr="Менеджер",e.meta_cat_mgr="Менеджер справочников",e.meta_doc_mgr="Менеджер документов",e.meta_enn_mgr="Менеджер перечислений",e.meta_ireg_mgr="Менеджер регистров сведений",e.meta_areg_mgr="Менеджер регистров накопления",e.meta_accreg_mgr="Менеджер регистров бухгалтерии",e.meta_dp_mgr="Менеджер обработок",e.meta_task_mgr="Менеджер задач",e.meta_bp_mgr="Менеджер бизнес-процессов",e.meta_reports_mgr="Менеджер отчетов",e.meta_charts_of_accounts_mgr="Менеджер планов счетов",e.meta_charts_of_characteristic_mgr="Менеджер планов видов характеристик",e.meta_extender="Модификаторы объектов и менеджеров",e.modified_close="Объект изменен<br/>Закрыть без сохранения?",e.mandatory_title="Обязательный реквизит",e.mandatory_field="Укажите значение реквизита '%1'",e.no_metadata="Не найдены метаданные объекта '%1'",e.no_selected_row="Не выбрана строка табличной части '%1'",e.no_dhtmlx="Библиотека dhtmlx не загружена",e.not_implemented="Не реализовано в текущей версии",e.offline_request="Запрос к серверу в автономном режиме",e.onbeforeunload="Окнософт: легкий клиент. Закрыть программу?",e.order_sent_title="Подтвердите отправку заказа",e.order_sent_message="Отправленный заказ нельзя изменить.<br/>После проверки менеджером<br/>он будет запущен в работу",e.report_error="<i class='fa fa-exclamation-circle fa-2x fa-fw'></i> Ошибка",e.report_prepare="<i class='fa fa-spinner fa-spin fa-2x fa-fw'></i> Подготовка отчета",e.report_need_prepare="<i class='fa fa-info fa-2x fa-fw'></i> Нажмите 'Сформировать' для получения отчета",e.report_need_online="<i class='fa fa-plug fa-2x fa-fw'></i> Нет подключения. Отчет недоступен в автономном режиме",e.request_title="Запрос регистрации",e.request_message="Заявка зарегистрирована. После обработки менеджером будет сформировано ответное письмо",e.select_from_list="Выбор из списка",e.select_grp="Укажите группу, а не элемент",e.select_elm="Укажите элемент, а не группу",e.select_file_import="Укажите файл для импорта",e.srv_overload="Сервер перегружен",e.sub_row_change_disabled="Текущая строка подчинена продукции.<br/>Строку нельзя изменить-удалить в документе<br/>только через построитель",e.sync_script="Обновление скриптов приложения:",e.sync_data="Синхронизация с сервером выполняется:<br />* при первом старте программы<br /> * при обновлении метаданных<br /> * при изменении цен или технологических справочников",e.sync_break="Прервать синхронизацию",e.sync_no_data="Файл не содержит подходящих элементов для загрузки",e.tabular_will_cleared="Табличная часть '%1' будет очищена. Продолжить?",e.unsupported_browser_title="Браузер не поддерживается",e.unsupported_browser="Несовместимая версия браузера<br/>Рекомендуется Google Chrome",e.supported_browsers="Рекомендуется Chrome, Safari или Opera",e.unsupported_mode_title="Режим не поддерживается",e.unsupported_mode="Программа не установлена<br/> в <a href='"+e.store_url_od+"'>приложениях Google Chrome</a>",e.unknown_error="Неизвестная ошибка в функции '%1'",e.value="Значение"}(K.msg),s.prototype.__define({family_name:{get:function(){return K.msg["meta_"+this.class_name.split(".")[0]+"_mgr"].replace(K.msg.meta_mgr+" ","")}},table_name:{get:function(){return this.class_name.replace(".","_")}},find_rows:{value:function(e,t){return K._find_rows.call(this,this.by_ref,e,t)}},extra_fields:{value:function(e){var t=K.cat.destinations||K.cch.destinations,n=_md.class_name_to_1c(this.class_name).replace(".","_"),r=[];return t&&t.find_rows({predefined_name:n},function(e){var t=e.extra_fields||e.ДополнительныеРеквизиты;return t&&t.each(function(e){e._deleted||e.ПометкаУдаления||r.push(e.property||e.Свойство)}),!1}),r}},extra_properties:{value:function(e){return[]}},obj_constructor:{value:function(e){var t=this.class_name.split("."),n=t[0].charAt(0).toUpperCase()+t[0].substr(1)+t[1].charAt(0).toUpperCase()+t[1].substr(1);return e?n+e.charAt(0).toUpperCase()+e.substr(1)+"Row":n}}}),s.prototype.sync_grid=function(e,t){function n(){if("function"==typeof e.custom_selection)return e.custom_selection(e);if("ram"==a.cachable){if("get_tree"==e.action)return K.wsql.promise(a.get_sql_struct(e),[]).then(K.iface.data_to_tree);if("get_selection"==e.action)return K.wsql.promise(a.get_sql_struct(e),[]).then(function(t){return K.iface.data_to_grid.call(a,t,e)})}else if(0==a.cachable.indexOf("doc")){if("get_tree"==e.action)return a.pouch_tree(e);if("get_selection"==e.action)return a.pouch_selection(e)}else{if("get_tree"==e.action)return a.rest_tree(e);if("get_selection"==e.action)return a.rest_selection(e)}}function r(e){return new Promise(function(n,r){"string"==typeof e?("{"==e.substr(0,1)&&(e=JSON.parse(e)),t&&t.parse?(t.xmlFileUrl="exec",t.parse(e,function(){n(e)},"xml")):n(e)):t instanceof dhtmlXTreeView&&t.loadStruct?t.loadStruct(e,function(){n(e)}):n(e)})}var a=this;return n().then(r).catch(K.record_log)},s.prototype.get_option_list=function(e,t){function n(t){return K.utils.is_equal(t.value,e)&&(t.selected=!0),t}var r,a,i,o=this,s=[];if(t.presentation&&(r=o.metadata().input_by_string)&&(a=t.presentation.like,delete t.presentation,t.or=[],r.forEach(function(e){i={},i[e]={like:a},t.or.push(i)})),"ram"==o.cachable||t&&t._local)return o.find_rows(t,function(e){s.push(n({text:e.presentation,value:e.ref}))}),Promise.resolve(s);if("e1cib"!=o.cachable)return o.pouch_find_rows(t).then(function(e){return e.forEach(function(e){s.push(n({text:e.presentation,value:e.ref}))}),s});var l={selection:t,top:t._top},_=o instanceof y||o instanceof b;return delete t._top,_?l.fields=["ref","date","number_doc"]:o.metadata().main_presentation_name?l.fields=["ref","name"]:l.fields=["ref","id"],Y.load_array(l,o).then(function(e){return e.forEach(function(e){s.push(n({text:_?e.number_doc+" от "+K.moment(e.date).format(K.moment._masks.ldt):e.name||e.id,value:e.ref}))}),s})},s.prototype.tabular_captions=function(e,t){},s.prototype.get_property_grid_xml=function(e,t,n){var r,a,i,o,s,l,_,u=this,c="<rows>",f=function(){if(!e)if(i=u.metadata(),i.form&&i.form.obj&&i.form.obj.head)e=i.form.obj.head;else{if(e={" ":[]},t instanceof q?(i.code_length&&e[" "].push("id"),i.main_presentation_name&&e[" "].push("name")):t instanceof A&&(e[" "].push("number_doc"),e[" "].push("date")),!t.is_folder)for(r in i.fields)"predefined_name"==r||i.fields[r].hide||e[" "].push(r);i.tabular_sections&&i.tabular_sections.extra_fields&&(e["Дополнительные реквизиты"]=[])}},d=function(e,t){l=K.utils.is_data_obj(e)?e.presentation:e,t.type.is_ref||(t.type.date_part?l=K.moment(l).format(K.moment._masks[t.type.date_part]):"boolean"==t.type.types[0]&&(l=l?"1":"0"))},p=function(e){s=_md.control_by_type(i.type,e),d(e,i)},h=function(e,r){if(r){var a=e.property||e.param||e.Параметр||e.Свойство,f=void 0!=e.value?e.value:e.Значение;a.empty()?(_=r+"|empty",s="ro",l="",i={synonym:"?"}):(i={synonym:a.presentation,type:a.type},_=r+"|"+a.ref,p(f),"edn"==s&&(s="calck"),a.mandatory&&(s+='" class="cell_mandatory'))}else if("object"==typeof e)_=e.id,i=n&&n.metadata&&n.metadata[_],i?e.synonym&&(i.synonym=e.synonym):i={synonym:e.synonym},s=e.type,l="",e.hasOwnProperty("txt")?l=e.txt:void 0!==(o=t[_])&&d(o,i.type?i:_md.get(u.class_name,_));else if(n&&n.metadata&&void 0!==(i=n.metadata[e]))_=e,p(o=t[e]);else{if(void 0===(o=t[e]))return;i=_md.get(u.class_name,_=e),p(o)}c+='<row id="'+_+'"><cell>'+(i.synonym||i.name)+'</cell><cell type="'+s+'">'+l+"</cell></row>"};f();for(r in e){" "!=r&&(c+='<row open="1"><cell>'+r+"</cell>");for(a in e[r])h(e[r][a]);if(n&&r==n.title&&t[n.ts]){var m,y=u.extra_fields(t),g="property,param,Свойство,Параметр".split(","),b=t[n.ts]._owner._metadata.tabular_sections[t[n.ts]._name].fields;g.some(function(e){if(b[e])return m=e,!0})&&(t[n.ts].forEach(function(e){var t=y.indexOf(e[m]);t!=-1&&y.splice(t,1)}),y.forEach(function(e){var r=t[n.ts].add();r[m]=e})),t[n.ts].find_rows(n.selection,function(e){h(e,n.ts)})}" "!=r&&(c+="</row>")}return c+="</rows>"},s.prototype.print=function(e,t,n){function r(e){n&&n.progressOff&&n.progressOff(),e&&e.focus()}if(n&&n.progressOn&&n.progressOn(),setTimeout(r,3e3),this._printing_plates[t]instanceof E&&(t=this._printing_plates[t]),t instanceof E&&t.execute)return e instanceof E?t.execute(e).then(r):this.get(e,!0,!0).then(t.execute.bind(t)).then(r);var a={};return K.ajax.default_attr(a,K.job_prm.irest_url()),a.url+=this.rest_name+"(guid'"+K.utils.fix_guid(e)+"')/Print(model="+t+", browser_uid="+K.wsql.get_user_param("browser_uid")+")",K.ajax.get_and_show_blob(a.url,a,"get").then(r)},s.prototype.printing_plates=function(){var e={},t=this;return t._printing_plates||(t.metadata().printing_plates?t._printing_plates=t.metadata().printing_plates:("ram"==t.metadata().cachable||t.metadata().cachable&&0==t.metadata().cachable.indexOf("doc"))&&(t._printing_plates={})),!t._printing_plates&&K.ajax.authorized?(K.ajax.default_attr(e,K.job_prm.irest_url()),e.url+=t.rest_name+"/Print()",K.ajax.get_ex(e.url,e).then(function(e){return t._printing_plates=JSON.parse(e.response),t._printing_plates}).catch(function(){}).then(function(e){return e||(t._printing_plates={})})):Promise.resolve(t._printing_plates)},l._extend(s),l.prototype.__define({push:{value:function(e,t){t&&t!=e.ref?(delete this.by_ref[e.ref],this.by_ref[t]=e):this.by_ref[e.ref]=e}},each:{value:function(e){for(var t in this.by_ref)if(t&&t!=K.utils.blank.guid&&1==e.call(this,this.by_ref[t]))break}},forEach:{value:function(e){return this.each.call(this,e)}},get:{value:function(e,t,n){var r=this.by_ref[e]||this.by_ref[e=K.utils.fix_guid(e)];if(!r){if(n&&!t)return;r=new(K[this.obj_constructor()])(e,this,(!0))}return t===!1?r:void 0===t&&e===K.utils.blank.guid?r:r.is_new()?r.load():t?Promise.resolve(r):r}},create:{value:function(e,t,n){e&&"object"==typeof e||(e={}),e.ref&&K.utils.is_guid(e.ref)&&!K.utils.is_empty_guid(e.ref)||(e.ref=K.utils.generate_guid());var r=this.by_ref[e.ref];if(!r)if(r=new(K[this.obj_constructor()])(e,this),!t&&e.ref&&e.presentation&&2==Object.keys(e).length);else{r instanceof A&&r.date==K.utils.blank.date&&(r.date=new Date);var a=this.handle_event(r,"after_create");if(this instanceof y||this instanceof g||this instanceof b?r.number_doc||r.new_number_doc():!r.id&&r._metadata.code_length&&r.new_number_doc(),a===!1)return Promise.resolve(r);if("object"==typeof a&&a.then)return a;if("e1cib"==this.cachable&&t){var i={};return K.ajax.default_attr(i,K.job_prm.irest_url()),i.url+=this.rest_name+"/Create()",K.ajax.get_ex(i.url,i).then(function(e){return r._mixin(JSON.parse(e.response),void 0,["ref"])})}}return n?r:Promise.resolve(r)}},unload_obj:{value:function(e){delete this.by_ref[e],this.alatable.some(function(t,n,r){if(t.ref==e)return r.splice(n,1),!0})}},find:{value:function(e,t){return K._find(this.by_ref,e,t)}},load_array:{value:function(e,t){for(var n,r,a=[],i=0;i<e.length;i++){if(n=K.utils.fix_guid(e[i]),r=this.by_ref[n])(r.is_new()||t)&&(r._mixin(e[i]),r._set_loaded());else{if("update_only"==t)continue;r=new(K[this.obj_constructor()])(e[i],this),t&&r._set_loaded()}a.push(r)}return a}},first_folder:{value:function(e){for(var t in this.by_ref){var n=this.by_ref[t];if(n.is_folder&&(!e||K.utils.is_equal(e,n.owner)))return n}return this.get()}},get_sql_struct:{value:function(e){function t(){function t(){var e=[],t="_t_.ref, _t_.`_deleted`";return s.form&&s.form.selection?s.form.selection.fields.forEach(function(t){e.push(t)}):o instanceof y?(e.push("posted"),e.push("date"),e.push("number_doc")):(s.hierarchical&&s.group_hierarchy?e.push("is_folder"):e.push("0 as is_folder"),o instanceof m?(e.push("id"),e.push("name as presentation")):s.main_presentation_name?e.push("name as presentation"):s.code_length?e.push("id as presentation"):e.push("'...' as presentation"),s.has_owners&&e.push("owner"),s.code_length&&e.push("id")),e.forEach(function(e){t+=e.indexOf(" as ")!=-1?", "+e:_md.sql_mask(e,!0)}),t}function n(){var e,t="";if(s.form&&s.form.selection)for(var n in s.form.selection.fields)s.form.selection.fields[n].indexOf(" as ")!=-1&&s.form.selection.fields[n].indexOf("_t_.")==-1&&(e=s.form.selection.fields[n].split(" as "),e[0]=e[0].split("."),e[0].length>1&&(t&&(t+="\n"),t+="left outer join "+e[0][0]+" on "+e[0][0]+".ref = _t_."+e[1]));return t}function r(){var t;return t=o instanceof m?" WHERE ("+(f?0:1):s.hierarchical?s.has_owners?" WHERE ("+(_||f?1:0)+" OR _t_.parent = '"+u+"') AND ("+(l==K.utils.blank.guid?1:0)+" OR _t_.owner = '"+l+"') AND ("+(f?0:1):" WHERE ("+(_||f?1:0)+" OR _t_.parent = '"+u+"') AND ("+(f?0:1):s.has_owners?" WHERE ("+(l==K.utils.blank.guid?1:0)+" OR _t_.owner = '"+l+"') AND ("+(f?0:1):" WHERE ("+(f?0:1),o.sql_selection_where_flds?t+=o.sql_selection_where_flds(f):o instanceof y?t+=" OR _t_.number_doc LIKE '"+f+"'":((s.main_presentation_name||o instanceof m)&&(t+=" OR _t_.name LIKE '"+f+"'"),s.code_length&&(t+=" OR _t_.id LIKE '"+f+"'")),t+=") AND (_t_.ref != '"+K.utils.blank.guid+"')",e.selection&&("function"==typeof e.selection||e.selection.forEach(function(e){for(var n in e)if("function"==typeof e[n])t+="\n AND "+e[n](o,n)+" ";else if(s.fields.hasOwnProperty(n)||"ref"===n)if(e[n]===!0)t+="\n AND _t_."+n+" ";else if(e[n]===!1)t+="\n AND (not _t_."+n+") ";else if("object"==typeof e[n])if(K.utils.is_data_obj(e[n])||K.utils.is_guid(e[n]))t+="\n AND (_t_."+n+" = '"+e[n]+"') ";else{var r,a=Object.keys(e[n]),i=e[n][a[0]],l=s.fields[n];l&&l.type.is_ref&&(r=_md.value_mgr({},n,l.type,!0,i)),t+="not"==a[0]?"\n AND (not _t_."+n+" = '"+i+"') ":"in"==a[0]?"\n AND (_t_."+n+" in ("+e[n].in.reduce(function(e,t){return e&&(e+=","),e+="number"==typeof t?t.toString():"'"+t+"'"},"")+")) ":"\n AND (_t_."+n+" = '"+i+"') "}else t+="string"==typeof e[n]?"\n AND (_t_."+n+" = '"+e[n]+"') ":"\n AND (_t_."+n+" = "+e[n]+") ";else"is_folder"==n&&s.hierarchical&&s.group_hierarchy})),t}function a(){return o instanceof m?"ORDER BY id":s.hierarchical?s.group_hierarchy?"ORDER BY _t_.is_folder desc, is_initial_value, presentation":"ORDER BY _t_.parent desc, is_initial_value, presentation":"ORDER BY is_initial_value, presentation"}function i(){function t(t){t&&(d=e.set_parent=t.parent.ref,u=d,_=!1),f&&f.indexOf("%")==-1&&(f="%"+f+"%")}s.has_owners&&(l=e.owner,e.selection&&"function"!=typeof e.selection&&e.selection.forEach(function(e){e.owner&&(l="object"==typeof e.owner?e.owner.valueOf():e.owner,delete e.owner)}),l||(l=K.utils.blank.guid)),c!=K.utils.blank.guid&&_&&s.hierarchical?t(o.get(c,!1)):t()}var l,_=!e.parent,u=e.parent||K.utils.blank.guid,c=e.initial_value||K.utils.blank.guid,f=e.filter||"",d=K.utils.blank.guid;i();var p;return p=o.sql_selection_list_flds?o.sql_selection_list_flds(c):("SELECT %2, case when _t_.ref = '"+c+"' then 0 else 1 end as is_initial_value FROM `"+o.table_name+"` AS _t_ %j %3 %4 LIMIT 300").replace("%2",t()).replace("%j",n()),p.replace("%3",r()).replace("%4",a())}function n(){var t="CREATE TABLE IF NOT EXISTS ";if(e&&e.postgres){t+=o.table_name+" (ref uuid PRIMARY KEY NOT NULL, _deleted boolean",o instanceof y?t+=", posted boolean, date timestamp with time zone, number_doc character(11)":(s.code_length&&(t+=", id character("+s.code_length+")"),t+=", name character varying(50), is_folder boolean");for(a in s.fields)a.length>30?s.fields[a].short_name?i=s.fields[a].short_name:(_++,i=a[0]+_+a.substr(a.length-27)):i=a,t+=", "+i+_md.sql_type(o,a,s.fields[a].type,!0)+_md.sql_composite(s.fields,a,i,!0);for(a in s.tabular_sections)t+=", ts_"+a+" JSON"}else{t+="`"+o.table_name+"` (ref CHAR PRIMARY KEY NOT NULL, `_deleted` BOOLEAN",t+=o instanceof y?", posted boolean, date Date, number_doc CHAR":", id CHAR, name CHAR, is_folder BOOLEAN";for(a in s.fields)t+=_md.sql_mask(a)+_md.sql_type(o,a,s.fields[a].type)+_md.sql_composite(s.fields,a);for(a in s.tabular_sections)t+=", `ts_"+a+"` JSON"}return t+=")"}function r(){var e=["ref","_deleted"],t="INSERT INTO `"+o.table_name+"` (ref, `_deleted`",n="(?";"cat"==o.class_name.substr(0,3)?(t+=", id, name, is_folder",e.push("id"),e.push("name"),e.push("is_folder")):"doc"==o.class_name.substr(0,3)&&(t+=", posted, date, number_doc",e.push("posted"),e.push("date"),e.push("number_doc"));for(a in s.fields)t+=_md.sql_mask(a),e.push(a);for(a in s.tabular_sections)t+=", `ts_"+a+"`",e.push("ts_"+a);for(t+=") VALUES ",a=1;a<e.length;a++)n+=", ?";return n+=")",t+=n,{sql:t,fields:e,values:n}}var a,i,o=this,s=o.metadata(),l={},_=0,u=e&&e.action?e.action:"create_table";return"create_table"==u?l=n():["insert","update","replace"].indexOf(u)!=-1?l[o.table_name]=r():"select"==u?l="SELECT * FROM `"+o.table_name+"` WHERE ref = ?":"select_all"==u?l="SELECT * FROM `"+o.table_name+"`":"delete"==u?l="DELETE FROM `"+o.table_name+"` WHERE ref = ?":"drop"==u?l="DROP TABLE IF EXISTS `"+o.table_name+"`":"get_tree"==u?l=!e.filter||e.filter.is_folder?"SELECT ref, parent, name as presentation FROM `"+o.table_name+"` WHERE is_folder order by parent, name":"SELECT ref, parent, name as presentation FROM `"+o.table_name+"` order by parent, name":"get_selection"==u&&(l=t()),l}},caption_flds:{value:function(e){var t=e.metadata||this.metadata(),n='<column id="%1" width="%2" type="%3" align="%4" sort="%5">%6</column>',r=[],a="";if(t.form&&t.form.selection?r=t.form.selection.cols:this instanceof y?(r.push(new Col_struct("date","160","ro","left","server","Дата")),r.push(new Col_struct("number_doc","140","ro","left","server","Номер")),t.fields.note&&r.push(new Col_struct("note","*","ro","left","server",t.fields.note.synonym)),t.fields.responsible&&r.push(new Col_struct("responsible","*","ro","left","server",t.fields.responsible.synonym))):this instanceof m?(r.push(new Col_struct("id","140","ro","left","server","Код")),r.push(new Col_struct("presentation","*","ro","left","server","Наименование"))):r.push(new Col_struct("presentation","*","ro","left","server","Наименование")),e.get_header&&r.length){a="<head>";for(var i in r)a+=n.replace("%1",r[i].id).replace("%2",r[i].width).replace("%3",r[i].type).replace("%4",r[i].align).replace("%5",r[i].sort).replace("%6",r[i].caption);a+="</head>"}return{head:a,acols:r}}},load_cached_server_array:{value:function(e,t){var n,r=[],a=this,i=t?{class_name:a.class_name,rest_name:t}:a,o=!t;if(e.forEach(function(e){n=a.get(e.ref||e,!1,!0),(!n||o&&n.is_new())&&r.push(e.ref||e)}),r.length){var s={url:"",selection:{ref:{in:r}}};return o&&(s.fields=["ref"]),K.rest.build_select(s,i),K.ajax.get_ex(s.url,s).then(function(t){var n=JSON.parse(t.response);if(o)n=n.value;else{n=n.data;for(var r in n)!n[r].ref&&n[r].id&&(n[r].ref=n[r].id),n[r].Код&&(n[r].id=n[r].Код,delete n[r].Код),n[r]._not_set_loaded=!0}return a.load_array(n),e})}return Promise.resolve(e)}},predefined:{value:function(e){return this._predefined||(this._predefined={}),this._predefined[e]||(this._predefined[e]=this.get(),this.find_rows({predefined_name:e},function(t){return this._predefined[e]=t,!1})),this._predefined[e]}}}),_._extend(s),_.prototype.__define({create:{value:function(){return new(K[this.obj_constructor()])({},this)}},unload_obj:{value:function(){}}}),u._extend(l),u.prototype.__define({get:{value:function(e){if(e instanceof N)return e;e&&e!=K.utils.blank.guid||(e="_");var t=this[e];return t||(t=new N({name:e},this)),t}},push:{value:function(e,t){this.__define(t,{value:e})}},each:{value:function(e){this.alatable.forEach(function(t){t.ref&&"_"!=t.ref&&t.ref!=K.utils.blank.guid&&e.call(this[t.ref])}.bind(this))}}}),u.prototype.get_sql_struct=function(e){var t="CREATE TABLE IF NOT EXISTS ",n=e&&e.action?e.action:"create_table";return e&&e.postgres?"create_table"==n?t+=this.table_name+" (ref character varying(255) PRIMARY KEY NOT NULL, sequence INT, synonym character varying(255))":["insert","update","replace"].indexOf(n)!=-1?(t={},t[this.table_name]={sql:"INSERT INTO "+this.table_name+" (ref, sequence, synonym) VALUES ($1, $2, $3)",fields:["ref","sequence","synonym"],values:"($1, $2, $3)"}):"delete"==n&&(t="DELETE FROM "+this.table_name+" WHERE ref = $1"):"create_table"==n?t+="`"+this.table_name+"` (ref CHAR PRIMARY KEY NOT NULL, sequence INT, synonym CHAR)":["insert","update","replace"].indexOf(n)!=-1?(t={},t[this.table_name]={sql:"INSERT INTO `"+this.table_name+"` (ref, sequence, synonym) VALUES (?, ?, ?)",fields:["ref","sequence","synonym"],values:"(?, ?, ?)"}):"delete"==n&&(t="DELETE FROM `"+this.table_name+"` WHERE ref = ?"),t},u.prototype.get_option_list=function(e,t){function n(t){return K.utils.is_equal(t.value,e)&&(t.selected=!0),t}var r,a=[],i="";if(t)for(var o in t)"_"!=o.substr(0,1)&&("ref"==o?r=t[o].hasOwnProperty("in")?t[o].in:t[o]:i=t[o]);return"object"==typeof i&&(i=i.like?i.like:""),i=i.toLowerCase(),this.alatable.forEach(function(e){if(!i||e.synonym&&e.synonym.toLowerCase().indexOf(i)!=-1){if(r)if(Array.isArray(r)){if(!r.some(function(t){return t.name==e.ref||t.ref==e.ref||t==e.ref}))return}else if(r.name!=e.ref&&r.ref!=e.ref&&r!=e.ref)return; +a.push(n({text:e.synonym||"",value:e.ref}))}}),Promise.resolve(a)},c._extend(s),c.prototype.__define({get_sql_struct:{value:function(e){function t(){function t(){var e=[],t="_t_.ref";if(s.form&&s.form.selection)s.form.selection.fields.forEach(function(t){e.push(t)});else for(var n in s.dimensions)e.push(n);return e.forEach(function(e){t+=e.indexOf(" as ")!=-1?", "+e:_md.sql_mask(e,!0)}),t}function n(){var e,t="";if(s.form&&s.form.selection)for(var n in s.form.selection.fields)s.form.selection.fields[n].indexOf(" as ")!=-1&&s.form.selection.fields[n].indexOf("_t_.")==-1&&(e=s.form.selection.fields[n].split(" as "),e[0]=e[0].split("."),e[0].length>1&&(t&&(t+="\n"),t+="left outer join "+e[0][0]+" on "+e[0][0]+".ref = _t_."+e[1]));return t}function r(){var t=" WHERE ("+(i?0:1);return o.sql_selection_where_flds&&(t+=o.sql_selection_where_flds(i)),t+=")",e.selection&&("function"==typeof e.selection||e.selection.forEach(function(e){for(var n in e)if("function"==typeof e[n])t+="\n AND "+e[n](o,n)+" ";else if(s.fields.hasOwnProperty(n))if(e[n]===!0)t+="\n AND _t_."+n+" ";else if(e[n]===!1)t+="\n AND (not _t_."+n+") ";else if("object"==typeof e[n])if(K.utils.is_data_obj(e[n]))t+="\n AND (_t_."+n+" = '"+e[n]+"') ";else{var r,a=Object.keys(e[n]),i=e[n][a[0]],l=s.fields[n];l&&l.type.is_ref&&(r=_md.value_mgr({},n,l.type,!0,i)),t+="not"==a[0]?"\n AND (not _t_."+n+" = '"+i+"') ":"\n AND (_t_."+n+" = '"+i+"') "}else t+="string"==typeof e[n]?"\n AND (_t_."+n+" = '"+e[n]+"') ":"\n AND (_t_."+n+" = "+e[n]+") ";else"is_folder"==n&&s.hierarchical&&s.group_hierarchy})),t}function a(){return""}var i=e.filter||"";i&&i.indexOf("%")==-1&&(i="%"+i+"%");var l;return l=o.sql_selection_list_flds?o.sql_selection_list_flds():("SELECT %2 FROM `"+o.table_name+"` AS _t_ %j %3 %4 LIMIT 300").replace("%2",t()).replace("%j",n()),l.replace("%3",r()).replace("%4",a())}function n(){var t="CREATE TABLE IF NOT EXISTS ",n=!0;if(e&&e.postgres){t+=o.table_name+" (",s.splitted&&(t+="zone integer",n=!1);for(i in s.dimensions)n?(t+=i,n=!1):t+=", "+i,t+=_md.sql_type(o,i,s.dimensions[i].type,!0)+_md.sql_composite(s.dimensions,i,"",!0);for(i in s.resources)t+=", "+i+_md.sql_type(o,i,s.resources[i].type,!0)+_md.sql_composite(s.resources,i,"",!0);for(i in s.attributes)t+=", "+i+_md.sql_type(o,i,s.attributes[i].type,!0)+_md.sql_composite(s.attributes,i,"",!0);t+=", PRIMARY KEY (",n=!0,s.splitted&&(t+="zone",n=!1);for(i in s.dimensions)n?(t+=i,n=!1):t+=", "+i}else{t+="`"+o.table_name+"` (ref CHAR PRIMARY KEY NOT NULL, `_deleted` BOOLEAN";for(i in s.dimensions)t+=_md.sql_mask(i)+_md.sql_type(o,i,s.dimensions[i].type);for(i in s.resources)t+=_md.sql_mask(i)+_md.sql_type(o,i,s.resources[i].type);for(i in s.attributes)t+=_md.sql_mask(i)+_md.sql_type(o,i,s.attributes[i].type)}return t+=")"}function r(){var e="INSERT OR REPLACE INTO `"+o.table_name+"` (",t=[],n=!0;for(i in s.dimensions)n?(e+=i,n=!1):e+=", "+i,t.push(i);for(i in s.resources)e+=", "+i,t.push(i);for(i in s.attributes)e+=", "+i,t.push(i);for(e+=") VALUES (?",i=1;i<t.length;i++)e+=", ?";return e+=")",{sql:e,fields:t}}function a(){var t="SELECT * FROM `"+o.table_name+"` WHERE ",n=!0;e._values=[];for(var r in s.dimensions)n?n=!1:t+=" and ",t+="`"+r+"`=?",e._values.push(e[r]);return n&&(t+="1"),t}var i,o=this,s=o.metadata(),l={},_=e&&e.action?e.action:"create_table";return"create_table"==_?l=n():_ in{insert:"",update:"",replace:""}?l[o.table_name]=r():"select"==_?l=a():"select_all"==_?l=a():"delete"==_?l="DELETE FROM `"+o.table_name+"` WHERE ref = ?":"drop"==_?l="DROP TABLE IF EXISTS `"+o.table_name+"`":"get_selection"==_&&(l=t()),l}},get_ref:{value:function(e){if(e instanceof C&&(e=e._obj),e.ref)return e.ref;var t="",n=this.metadata().dimensions;for(var r in n)t+=t?"¶":"",t+=n[r].type.is_ref?K.utils.fix_guid(e[r]):!e[r]&&n[r].type.digits?"0":n[r].date_part?K.moment(e[r]||K.utils.blank.date).format(K.moment.defaultFormatUtc):void 0!=e[r]?String(e[r]):"$";return t}},caption_flds:{value:function(e){var t=e.metadata||this.metadata(),n='<column id="%1" width="%2" type="%3" align="%4" sort="%5">%6</column>',r=[],a="";if(t.form&&t.form.selection)r=t.form.selection.cols;else for(var i in t.dimensions)r.push(new Col_struct(i,"*","ro","left","server",t.dimensions[i].synonym));if(e.get_header&&r.length){a="<head>";for(var o in r)a+=n.replace("%1",r[o].id).replace("%2",r[o].width).replace("%3",r[o].type).replace("%4",r[o].align).replace("%5",r[o].sort).replace("%6",r[o].caption);a+="</head>"}return{head:a,acols:r}}},create:{value:function(e){e&&"object"==typeof e||(e={});var t=this.by_ref[e.ref];if(!t){t=new(K[this.obj_constructor()])(e,this);var n=this.handle_event(t,"after_create");if(n===!1)return Promise.resolve(t);if("object"==typeof n&&n.then)return n}return Promise.resolve(t)}}}),f._extend(c),f.prototype.slice_first=function(e){},f.prototype.slice_last=function(e){},d._extend(c),p._extend(l),p.prototype.by_name=function(e){var t;return this.find_rows({name:e},function(e){return t=e,!1}),t||(t=this.get()),t},p.prototype.by_id=function(e){var t;return this.find_rows({id:e},function(e){return t=e,!1}),t||(t=this.get()),t},p.prototype.path=function(e){var t,n=[];if(t=e instanceof E?e:this.get(e,!1,!0),t&&n.push({ref:t.ref,presentation:t.presentation}),t&&this.metadata().hierarchical)for(;;){if(t=t.parent,t.empty())break;n.push({ref:t.ref,presentation:t.presentation})}return n},h._extend(p),m._extend(p),y._extend(l),g._extend(p),b._extend(p),v._extend(f),w._extend(p),x._extend(p),j._extend(p),O.prototype.toString=function(){return"Табличная часть "+this._owner._manager.class_name+"."+this._name},O.prototype.get=function(e){return this._obj[e]?this._obj[e]._row:null},O.prototype.count=function(){return this._obj.length},O.prototype.clear=function(e){for(var t in this._obj)delete this._obj[t];return this._obj.length=0,e||this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name}),this},O.prototype.del=function(e,t){var n,r=this._obj;if("undefined"!=typeof e){if("number"==typeof e)n=e;else if(r[e.row-1]._row===e)n=e.row-1;else for(var a in r)if(r[a]._row===e){n=Number(a),delete r[a]._row;break}void 0!=n&&(r.splice(n,1),r.forEach(function(e,t){e.row=t+1}),t||this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name}),this._owner._data._modified=!0)}},O.prototype.find=function(e,t){var n=K._find(this._obj,e,t);if(n)return n._row},O.prototype.find_rows=function(e,t){var n=this,r=t?function(e){return t.call(n,e._row)}:null;return K._find_rows.call(n,n._obj,e,r)},O.prototype.swap=function(e,t){var n=this._obj[e];this._obj[e]=this._obj[t],this._obj[t]=n,this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name})},O.prototype.add=function(e,t){var n=new(K[this._owner._manager.obj_constructor(this._name)])(this);e||(e={});for(var r in n._metadata.fields)n[r]=e[r]||"";return n._obj.row=this._obj.push(n._obj),n._obj.__define("_row",{value:n,enumerable:!1}),t||this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name}),e=null,this._owner._data._modified=!0,n},O.prototype.each=function(e){var t=this;t._obj.forEach(function(n){return e.call(t,n._row)})},O.prototype.forEach=O.prototype.each,O.prototype.group_by=function(e,t){try{var n=this.aggregate(e,t,"SUM",!0);return this.clear(!0).load(n)}catch(e){}},O.prototype.sort=function(e){"string"==typeof e&&(e=e.split(","));var t="select * from ? order by ",n=!0;e.forEach(function(e){e=e.trim().replace(/\s{1,}/g," ").split(" "),n?n=!1:t+=", ",t+="`"+e[0]+"`",e[1]&&(t+=" "+e[1])});try{return n=K.wsql.alasql(t,[this._obj]),this.clear(!0).load(n)}catch(e){K.record_log(e)}},O.prototype.aggregate=function(e,t,n,r){if("string"==typeof e&&(e=e.split(",")),"string"==typeof t&&(t=t.split(",")),n||(n="sum"),!e.length&&1==t.length&&"sum"==n)return this._obj.reduce(function(e,n,r,a){return e+n[t[0]]},0);var a,i=!0;t.forEach(function(e){a?a+=", "+n+"(`"+e+"`) `"+e+"`":a="select "+n+"(`"+e+"`) `"+e+"`"}),e.forEach(function(e){a?a+=", `"+e+"`":a="select `"+e+"`"}),a+=" from ? ",e.forEach(function(e){i?(a+="group by ",i=!1):a+=", ",a+="`"+e+"`"});try{return i=K.wsql.alasql(a,[this._obj]),r||(i=1==t.length?i.length?i[0][t[0]]:0:i.length?i[0]:{}),i}catch(e){K.record_log(e)}},O.prototype.load=function(e){var t,n=this;return n.clear(!0),e instanceof O?t=e._obj:Array.isArray(e)&&(t=e),t&&t.forEach(function(e){n.add(e,!0)}),this._owner._data._silent||Object.getNotifier(n._owner).notify({type:"rows",tabular:n._name}),n},O.prototype.sync_grid=function(e,t){for(var n={rows:[]},r=[],a=0;a<e.getColumnCount();a++)r.push(e.getColumnId(a));if(e.clearAll(),this.find_rows(t,function(e){var t=[];r.forEach(function(n){K.utils.is_data_obj(e[n])?t.push(e[n].presentation):t.push(e[n])}),n.rows.push({id:e.row,data:t})}),e.objBox)try{e.parse(n,"json"),e.callEvent("onGridReconstructed",[])}catch(e){}},O.prototype.toJSON=function(){return this._obj},k.prototype.__define("_metadata",{get:function(){return this._owner._owner._metadata.tabular_sections[this._owner._name]},enumerable:!1}),k.prototype.__define("row",{get:function(){return this._obj.row||0},enumerable:!0}),k.prototype.__define("_clone",{value:function(){return new(K[this._owner._owner._manager.obj_constructor(this._owner._name)])(this._owner)._mixin(this._obj)},enumerable:!1}),k.prototype._getter=E.prototype._getter,k.prototype._setter=function(e,t){if(this._obj[e]!=t&&(t||this._obj[e]!=K.utils.blank.guid)){if(this._owner._owner._data._silent||Object.getNotifier(this._owner._owner).notify({type:"row",row:this,tabular:this._owner._name,name:e,oldValue:this._obj[e]}),this._metadata.fields[e].choice_type){var n;n=2==this._metadata.fields[e].choice_type.path.length?this[this._metadata.fields[e].choice_type.path[1]]:this._owner._owner[this._metadata.fields[e].choice_type.path[0]],n&&n.type&&(t=K.utils.fetch_type(t,n.type))}E.prototype.__setter.call(this,e,t),this._owner._owner._data._modified=!0}},E.prototype._getter=function(e){var t,n=this._metadata.fields[e].type,r=this._obj?this._obj[e]:"";return"type"==e&&"object"==typeof r?r:"ref"==e?r:n.is_ref?n.digits&&"number"==typeof r?r:n.hasOwnProperty("str_len")&&!K.utils.is_guid(r)?r:(t=_md.value_mgr(this._obj,e,n))?K.utils.is_data_mgr(t)?t.get(r,!1):K.utils.fetch_type(r,t):r?(console.log([e,n,this._obj]),null):void 0:n.date_part?K.utils.fix_date(this._obj[e],!0):n.digits?K.utils.fix_number(this._obj[e],!n.hasOwnProperty("str_len")):"boolean"==n.types[0]?K.utils.fix_boolean(this._obj[e]):this._obj[e]||""},E.prototype.__setter=function(e,t){var n,r=this._metadata.fields[e].type;"type"==e&&t.types?this._obj[e]=t:"ref"==e?this._obj[e]=K.utils.fix_guid(t):r.is_ref?r.digits&&"number"==typeof t||r.hasOwnProperty("str_len")&&"string"==typeof t&&!K.utils.is_guid(t)?this._obj[e]=t:(this._obj[e]=K.utils.fix_guid(t),n=_md.value_mgr(this._obj,e,r,!1,t),n?n instanceof u?"string"==typeof t?this._obj[e]=t:t?"object"==typeof t&&(this._obj[e]=t.ref||t.name||""):this._obj[e]="":t&&t.presentation?(!t.type||t instanceof E||delete t.type,n.create(t)):K.utils.is_data_mgr(n)||(this._obj[e]=K.utils.fetch_type(t,n)):"object"!=typeof t&&(this._obj[e]=t)):r.date_part?this._obj[e]=K.utils.fix_date(t,!0):r.digits?this._obj[e]=K.utils.fix_number(t,!r.hasOwnProperty("str_len")):"boolean"==r.types[0]?this._obj[e]=K.utils.fix_boolean(t):this._obj[e]=t},E.prototype.__notify=function(e){this._data._silent||Object.getNotifier(this).notify({type:"update",name:e,oldValue:this._obj[e]})},E.prototype._setter=function(e,t){this._obj[e]!=t&&(this.__notify(e),this.__setter(e,t),this._data._modified=!0)},E.prototype._getter_ts=function(e){return this._ts_(e)},E.prototype._setter_ts=function(e,t){var n=this._ts_(e);n instanceof O&&Array.isArray(t)&&n.load(t)},E.prototype.__define({valueOf:{value:function(){return this.ref}},toJSON:{value:function(){return this._obj}},toString:{value:function(){return this.presentation}},_metadata:{get:function(){return this._manager.metadata()}},_deleted:{get:function(){return!!this._obj._deleted}},_modified:{get:function(){return!!this._data&&!!this._data._modified}},is_new:{value:function(){return this._data._is_new}},_set_loaded:{value:function(e){return this._manager.push(this,e),this._data._modified=!1,this._data._is_new=!1,this}},mark_deleted:{value:function(e){return this._obj._deleted=!!e,this.save(),this.__notify("_deleted"),this}},ref:{get:function(){return this._obj.ref},set:function(e){this._obj.ref=K.utils.fix_guid(e)},enumerable:!0,configurable:!0},empty:{value:function(){return K.utils.is_empty_guid(this._obj.ref)}},load:{value:function(){var e=function(){return e=null,this._data._modified=!1,this}.bind(this);return this.ref==K.utils.blank.guid?(this instanceof q?this.id="000000000":this.number_doc="000000000",Promise.resolve(this)):this._manager.cachable&&"e1cib"!=this._manager.cachable?K.wsql.pouch.load_obj(this).then(e):Y.load_obj(this).then(e)}},unload:{value:function(){var e,t=this._obj;this._manager.unload_obj(this.ref),this._observers&&(this._observers.length=0),this._notis&&(this._notis.length=0);for(e in this._metadata.tabular_sections)this[e].clear(!0);for(e in this)this.hasOwnProperty(e)&&delete this[e];for(e in t)delete t[e];["_ts_","_obj","_data"].forEach(function(e){delete this[e]}.bind(this)),e=t=null}},save:{value:function(e,t,n){if(this instanceof A&&"boolean"==typeof e){var r=this.posted;this.posted=e}var a,i=this._manager.handle_event(this,"before_save"),o=function(){return i===!1?this instanceof A&&"boolean"==typeof r&&this.posted!=r&&(this.posted=r):this._data._modified=!1,a=null,i=null,o=null,this}.bind(this);if(i===!1)return Promise.reject(o());if(i instanceof Promise||"object"==typeof i&&i.then)return i.then(o);if(this._metadata.hierarchical&&!this._obj.parent&&(this._obj.parent=K.utils.blank.guid),this instanceof A||this instanceof P||this instanceof S?(K.utils.blank.date==this.date&&(this.date=new Date),this.number_doc||this.new_number_doc()):this.id||this.new_number_doc(),K.msg&&K.msg.show_msg)for(var s in this._metadata.fields)if(this._metadata.fields[s].mandatory&&!this._obj[s])return K.msg.show_msg({title:K.msg.mandatory_title,type:"alert-error",text:K.msg.mandatory_field.replace("%1",this._metadata.fields[s].synonym)}),i=!1,Promise.reject(o());return a=this._manager.cachable&&"e1cib"!=this._manager.cachable?K.wsql.pouch.save_obj:Y.save_irest,a(this,{post:e,operational:t,attachments:n}).then(function(e){return e._manager.handle_event(e,"after_save")}).then(o)}},get_attachment:{value:function(e){return this._manager.get_attachment(this.ref,e)}},save_attachment:{value:function(e,t,n){return this._manager.save_attachment(this.ref,e,t,n).then(function(t){return this._attachments||(this._attachments={}),this._attachments[e]&&t.stub||(this._attachments[e]=t),t}.bind(this))}},delete_attachment:{value:function(e){return this._manager.delete_attachment(this.ref,e).then(function(t){return this._attachments&&delete this._attachments[e],t}.bind(this))}},_silent:{value:function(e){"boolean"==typeof e?this._data._silent=e:(this._data._silent=!0,setTimeout(function(){this._data._silent=!1}.bind(this)))}},print:{value:function(e,t){return this._manager.print(this,e,t)}}}),q._extend(E),q.prototype.__define("id",{get:function(){return this._obj.id||""},set:function(e){this.__notify("id"),this._obj.id=e},enumerable:!0}),q.prototype.__define("name",{get:function(){return this._obj.name||""},set:function(e){this.__notify("name"),this._obj.name=String(e)},enumerable:!0}),A._extend(E),A.prototype.__define({posted:{get:function(){return this._obj.posted||!1},set:function(e){this.__notify("posted"),this._obj.posted=K.utils.fix_boolean(e)},enumerable:!0}}),D(A.prototype),R._extend(E),P._extend(q),D(P.prototype),S._extend(q),D(S.prototype),N._extend(E),N.prototype.__define({order:{get:function(){return this._obj.sequence},set:function(e){this._obj.sequence=parseInt(e)},enumerable:!0},name:{get:function(){return this._obj.ref},set:function(e){this._obj.ref=String(e)},enumerable:!0},synonym:{get:function(){return this._obj.synonym||""},set:function(e){this._obj.synonym=String(e)},enumerable:!0},presentation:{get:function(){return this.synonym||this.name}},empty:{value:function(){return!this.ref||"_"==this.ref}}}),C._extend(E),C.prototype.__define({_metadata:{get:function(){var e=this._manager.metadata();return e.fields||(e.fields={}._mixin(e.dimensions)._mixin(e.resources)._mixin(e.attributes)),e}},ref:{get:function(){return this._manager.get_ref(this)},enumerable:!0},presentation:{get:function(){return this._metadata.obj_presentation||this._metadata.synonym}}});var Y=K.rest=new T;return s.prototype.__define("rest_name",{get:function(){var e=this.class_name.split("."),t={cat:"Catalog",doc:"Document",ireg:"InformationRegister",areg:"AccumulationRegister",cch:"ChartOfCharacteristicTypes",cacc:"ChartOfAccounts",tsk:"Task",bp:"BusinessProcess"};return t[e[0]]+"_"+_md.syns_1с(e[1])},enumerable:!1}),s.prototype.rest_tree=function(e){var t,n,r=this,a=r.metadata(),i=[];return K.ajax.default_attr(e,!a.irest&&K.job_prm.rest?K.job_prm.rest_url():K.job_prm.irest_url()),e.url+=this.rest_name+"?allowedOnly=true&$format=json&$top=1000&$select=Ref_Key,DeletionMark,Parent_Key,Description&$filter=IsFolder eq true",K.ajax.get_ex(e.url,e).then(function(e){return JSON.parse(e.response)}).then(function(e){for(var r=0;r<e.value.length;r++)n=e.value[r],t={ref:n.Ref_Key,_deleted:n.DeletionMark,parent:n.Parent_Key,presentation:n.Description},i.push(t);return K.iface.data_to_tree(i)})},s.prototype.rest_selection=function(e){if("get_tree"==e.action)return this.rest_tree(e);var t,n,r,a,i,o,s=this,l=s.metadata(),_=[],u=[];return i=function(){var e="$select=Ref_Key,DeletionMark";return l.form&&l.form.selection?l.form.selection.fields.forEach(function(e){_.push(e)}):s instanceof y?(_.push("posted"),_.push("date"),_.push("number_doc")):s instanceof g?(_.push("name as presentation"),_.push("date"),_.push("number_doc"),_.push("completed")):s instanceof b?(_.push("date"),_.push("number_doc"),_.push("started"),_.push("finished")):(l.hierarchical&&l.group_hierarchy?_.push("is_folder"):_.push("0 as is_folder"),l.main_presentation_name?_.push("name as presentation"):l.code_length?_.push("id as presentation"):_.push("'...' as presentation"),l.has_owners&&_.push("owner"),l.code_length&&_.push("id")),_.forEach(function(t){var n;if(t.indexOf(" as ")!=-1)if(n=t.split(" as ")[0].split("."),1==n.length)t=n[0];else{if("_t_"!=n[0])return;t=n[1]}"0"!=t&&(r=_md.syns_1с(t),_md.get(s.class_name,t).type.is_ref&&r.indexOf("_Key")==-1&&_md.get(s.class_name,t).type.types.length&&_md.get(s.class_name,t).type.types[0].indexOf("enm.")==-1&&(r+="_Key"),e+=","+r)}),_.push("ref"),_.push("_deleted"),e}(),K.ajax.default_attr(e,!l.irest&&K.job_prm.rest?K.job_prm.rest_url():K.job_prm.irest_url()),e.url+=(l.irest&&l.irest.selection?l.irest.selection:this.rest_name)+"?allowedOnly=true&$format=json&$top=1000&"+i,_md.get(s.class_name,"date")&&(e.date_from||e.date_till)&&(e.url+="&$filter="+Y.filter_date("Date",e.date_from,e.date_till),o=!0),l.hierarchical&&e.parent&&(e.url+=o?" and ":"&$filter=",e.url+="Parent_Key eq guid'"+e.parent+"'",o=!0),l.has_owners&&e.owner&&(e.url+=o?" and ":"&$filter=",e.url+="Owner_Key eq guid'"+e.owner+"'",o=!0),e.filter&&(e.url+=o?" and ":"&$filter=",e.url+="$filter eq '"+e.filter+"'",o=!0),K.ajax.get_ex(e.url,e).then(function(e){return JSON.parse(e.response)}).then(function(i){for(var o=0;o<i.value.length;o++)n=i.value[o],t={},_.forEach(function(e){var i;if("ref"==e)return void(t[e]=n.Ref_Key);if(e.indexOf(" as ")!=-1?(i=e.split(" as ")[1],e=e.split(" as ")[0].split("."),e=e[e.length-1]):i=e,r=_md.syns_1с(e),a=_md.get(s.class_name,e))if(r.indexOf("_Key")==-1&&a.type.is_ref&&a.type.types.length&&a.type.types[0].indexOf("enm.")==-1&&(r+="_Key"),a.type.date_part)t[i]=K.moment(n[r]).format(K.moment._masks[a.type.date_part]);else if(a.type.is_ref)if(n[r]&&n[r]!=K.utils.blank.guid){var o=_md.value_mgr(t,e,a.type,!1,n[r]);o?t[i]=o.get(n[r]).presentation:t[i]=""}else t[i]="";else t[i]=n[r]}),u.push(t);return K.iface.data_to_grid.call(s,u,e)})},f.prototype.rest_slice_last=function(e){e.period||(e.period=K.utils.date_add_day(new Date,1));var t=this,n=t.metadata(),r="Period=datetime'"+K.moment(e.period).format(K.moment._masks.iso)+"'",a="";for(var i in n.dimensions)if(void 0!==e[i]){var o=_md.syns_1с(i),s=n.dimensions[i];o.indexOf("_Key")==-1&&s.type.is_ref&&s.type.types.length&&s.type.types[0].indexOf("enm.")==-1?(o+="_Key",a&&(a+=" and "),a+=o+" eq guid'"+e[i].ref+"'"):(a&&(a+=" and "),a+=s.type.digits?o+" eq "+K.utils.fix_number(e[i]):s.type.date_part?o+" eq datetime'"+K.moment(e[i]).format(K.moment._masks.iso)+"'":o+" eq '"+e[i]+"'")}return a&&(r+=",Condition='"+a+"'"),K.ajax.default_attr(e,K.job_prm.rest_url()),e.url+=this.rest_name+"/SliceLast(%sl)?allowedOnly=true&$format=json&$top=1000".replace("%sl",r),Y.ajax_to_data(e,t).then(function(e){return t.load_array(e)})},E.prototype.to_atom=function(e){function t(e){var t=e._metadata.fields,a=e instanceof k?"\n\t<d:":"\n<d:";for(n in t){if(r=t[n],s=_md.syns_1с(n),l=e[n],l instanceof N)l=l.empty()?"":l.name;else if(l instanceof E)s.indexOf("_Key")==-1&&(s+="_Key"),l=l.ref;else if(r.type.date_part)l=l.getFullYear()<1e3?"0001-01-01T00:00:00Z":K.moment(l).format(K.moment.defaultFormatUtc);else if(void 0==l)continue;u+=a+s+">"+l+"</d:"+s+">"}}var n,r,a,i,o,s,l,_='<entry><category term="StandardODATA.%n" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"/>\t\t\t\t\n<title type="text"/><updated>%d</updated><author/><summary/><content type="application/xml">\t\t\t\t\n<m:properties xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">\t\t\t%p\t\t\t\n</m:properties></content></entry>'.replace("%n",this._manager.rest_name).replace("%d",K.moment().format(K.moment.defaultFormatUtc)),u="\n<d:Ref_Key>"+this.ref+"</d:Ref_Key>\n<d:DeletionMark>"+this._deleted+"</d:DeletionMark>";this instanceof A?(u+="\n<d:Date>"+K.moment(this.date).format(K.moment.defaultFormatUtc)+"</d:Date>",u+="\n<d:Number>"+this.number_doc+"</d:Number>"):(this._metadata.main_presentation_name&&(u+="\n<d:Description>"+this.name+"</d:Description>"),this._metadata.code_length&&(u+="\n<d:Code>"+this.id+"</d:Code>"),this._metadata.hierarchical&&this._metadata.group_hierarchy&&(u+="\n<d:IsFolder>"+this.is_folder+"</d:IsFolder>")),t(this);for(a in this._metadata.tabular_sections)o=this._metadata.tabular_sections[a],s="StandardODATA."+this._manager.rest_name+"_"+_md.syns_1с(a)+"_RowType",i=this[a],i.count()?(u+="\n<d:"+_md.syns_1с(a)+' m:type="Collection('+s+')">',i.each(function(e){u+='\n\t<d:element m:type="'+s+'">',u+="\n\t<d:LineNumber>"+e.row+"</d:LineNumber>",t(e),u+="\n\t</d:element>"}),u+="\n</d:"+_md.syns_1с(a)+">"):u+="\n<d:"+_md.syns_1с(a)+' m:type="Collection('+s+')" />';return _.replace("%p",u)},s.prototype.__define({pouch_load_array:{value:function(e,t){var n={limit:e.length+1,include_docs:!0,keys:e.map(function(e){return this.class_name+"|"+e}.bind(this))};return t&&(n.attachments=!0,n.binary=!0),this.pouch_db.allDocs(n).then(function(e){return K.wsql.pouch.load_changes(e,{})})}},pouch_load_view:{value:function(e){var t,n=this,r=[],a={limit:1e3,include_docs:!0,startkey:n.class_name+"|",endkey:n.class_name+"|￿"};return new Promise(function(i,o){function s(l,_){_?_.rows.length?(a.startkey=_.rows[_.rows.length-1].key,a.skip=1,_.rows.forEach(function(e){t=e.doc,key=t._id.split("|"),t.ref=key[1],r.push(t)}),n.load_array(r),r.length=0,n.pouch_db.query(e,a,s)):i():l&&o(l)}n.pouch_db.query(e,a,s)})}},pouch_db:{get:function(){return this.cachable.indexOf("_remote")!=-1?K.wsql.pouch.remote[this.cachable.replace("_remote","")]:K.wsql.pouch.local[this.cachable]||K.wsql.pouch.remote[this.cachable]}},pouch_find_rows:{value:function(e){var t,n,r,a,i,o,s=this,l=[],_=0,u=0,c=0,f={limit:100,include_docs:!0,startkey:s.class_name+"|",endkey:s.class_name+"|￿"};return e&&(e._top?(i=e._top,delete e._top):i=300,e._raw&&(n=e._raw,delete e._raw),e._total_count&&(a=e._total_count,delete e._total_count),e._view&&(r=e._view,delete e._view),e._key&&("des"==e._key._order_by?(f.startkey=e._key.endkey||e._key+"￿",f.endkey=e._key.startkey||e._key,f.descending=!0):(f.startkey=e._key.startkey||e._key,f.endkey=e._key.endkey||e._key+"￿")),"number"==typeof e._skip&&(u=e._skip,delete e._skip),e._attachments&&(f.attachments=!0,f.binary=!0,delete e._attachments)),a&&(o=!0,a=0,Object.keys(e).length<=1&&e._key&&e._key.hasOwnProperty("_search"))?(f.include_docs=!1,f.limit=1e5,s.pouch_db.query(r,f).then(function(t){return t.rows.forEach(function(t){if(!e._key._search||t.key[t.key.length-1].toLowerCase().indexOf(e._key._search)!=-1){if(a++,u&&(c++,c<u))return;if(i&&(_++,_>i))return;l.push(t.id)}}),delete f.startkey,delete f.endkey,f.descending&&delete f.descending,f.keys=l,f.include_docs=!0,s.pouch_db.allDocs(f)}).then(function(e){return{rows:e.rows.map(function(e){var t=e.doc;return t.ref=t._id.split("|")[1],n||(delete t._id,delete t._rev),t}),_total_count:a}})):new Promise(function(d,p){function h(r,h){h?h.rows.length?(f.startkey=h.rows[h.rows.length-1].key,f.skip=1,h.rows.forEach(function(r){t=r.doc,key=t._id.split("|"),t.ref=key[1],n||(delete t._id,delete t._rev),K._selection.call(s,t,e)&&(o&&a++,u&&(c++,c<u)||i&&(_++,_>i)||l.push(t))}),i&&_>i&&!o?d(n?l:s.load_array(l)):m()):d(o?{rows:n?l:s.load_array(l),_total_count:a}:n?l:s.load_array(l)):r&&p(r)}function m(){r?s.pouch_db.query(r,f,h):s.pouch_db.allDocs(f,h)}m()})}},pouch_selection:{value:function(e){var t,n,r,a=this,i=e.metadata||a.metadata(),o=["ref","_deleted"],s={_raw:!0,_total_count:!0,_top:e.count||30,_skip:e.start||0},l=[];if(i.form&&i.form.selection?i.form.selection.fields.forEach(function(e){o.push(e)}):a instanceof y?(o.push("posted"),o.push("date"),o.push("number_doc")):a instanceof g?(o.push("name as presentation"),o.push("date"),o.push("number_doc"),o.push("completed")):a instanceof b?(o.push("date"),o.push("number_doc"),o.push("started"),o.push("finished")):(i.hierarchical&&i.group_hierarchy?o.push("is_folder"):o.push("0 as is_folder"),i.main_presentation_name?o.push("name as presentation"):i.code_length?o.push("id as presentation"):o.push("'...' as presentation"),i.has_owners&&o.push("owner"),i.code_length&&o.push("id")),_md.get(a.class_name,"date")&&(e.date_from||e.date_till)&&(e.date_from||(e.date_from=new Date("2015-01-01")),e.date_till||(e.date_till=K.utils.date_add_day(new Date,1)),s.date={between:[e.date_from,e.date_till]}),i.hierarchical&&e.parent&&(s.parent=e.parent),e.selection)if(Array.isArray(e.selection))e.selection.forEach(function(e){for(r in e)"_"==r[0]&&"_view"!=r&&"_key"!=r||(s[r]=e[r])});else for(r in e.selection)"_"==r[0]&&"_view"!=r&&"_key"!=r||(s[r]=e.selection[r]);return s._key&&s._key._drop_date&&s.date&&delete s.date,!e.filter||s._key&&s._key._search||(1==i.input_by_string.length?s[i.input_by_string]={like:e.filter}:(s.or=[],i.input_by_string.forEach(function(t){var n={};n[t]={like:e.filter},s.or.push(n)}))),s._key&&s._key._order_by&&(s._key._order_by=e.direction),a.pouch_find_rows(s).then(function(i){return i.hasOwnProperty("_total_count")&&i.hasOwnProperty("rows")&&(e._total_count=i._total_count,i=i.rows),i.forEach(function(e){t={},o.forEach(function(i){if("ref"==i)return void(t[i]=e[i]);if(i.indexOf(" as ")!=-1?(r=i.split(" as ")[1],i=i.split(" as ")[0].split("."),i=i[i.length-1]):r=i,n=_md.get(a.class_name,i))if(n.type.date_part)t[r]=K.moment(e[i]).format(K.moment._masks[n.type.date_part]);else if(n.type.is_ref)if(e[i]&&e[i]!=K.utils.blank.guid){var o=_md.value_mgr(t,i,n.type,!1,e[i]);o?t[r]=o.get(e[i]).presentation:t[r]=""}else t[r]="";else"number"==typeof e[i]&&n.type.fraction_figits?t[r]=e[i].toFixed(n.type.fraction_figits):t[r]=e[i]}),l.push(t)}),K.iface.data_to_grid.call(a,l,e)}).catch(K.record_log)}},pouch_tree:{value:function(e){return this.pouch_find_rows({is_folder:!0,_raw:!0,_top:e.count||300,_skip:e.start||0}).then(function(e){return e.sort(function(e,t){return e.parent==K.utils.blank.guid&&t.parent!=K.utils.blank.guid?-1:t.parent==K.utils.blank.guid&&e.parent!=K.utils.blank.guid?1:e.name<t.name?-1:e.name>t.name?1:0}),e.map(function(e){return{ref:e.ref,parent:e.parent,presentation:e.name}})}).then(K.iface.data_to_tree)}},save_attachment:{value:function(e,t,n,r){r||(r={type:"text/plain"}),n instanceof Blob||r.indexOf("text")!=-1||(n=new Blob([n],{type:r}));var a,i=this.pouch_db;return e=this.class_name+"|"+K.utils.fix_guid(e),i.get(e).then(function(e){e&&(a=e._rev)}).catch(function(e){if(404!=e.status)throw e}).then(function(){return i.putAttachment(e,t,a,n,r)})}},get_attachment:{value:function(e,t){return this.pouch_db.getAttachment(this.class_name+"|"+K.utils.fix_guid(e),t)}},delete_attachment:{value:function(e,t){var n,r=this.pouch_db;return e=this.class_name+"|"+K.utils.fix_guid(e),r.get(e).then(function(e){e&&(n=e._rev)}).catch(function(e){if(404!=e.status)throw e}).then(function(){return r.removeAttachment(e,t,n)})}}}),E.prototype.__define({new_number_doc:{value:function(e){if(this._metadata.code_length){e||(e=(K.current_acl&&K.current_acl.prefix||"")+(this.organization&&this.organization.prefix?this.organization.prefix:K.wsql.get_user_param("zone")+"-"));var t=this,n="",r=this.date instanceof Date?this.date.getFullYear():0,a=this._metadata.code_length-e.length;return"ram"==this._manager.cachable?Promise.resolve(this.new_cat_id(e)):t._manager.pouch_db.query("doc/number_doc",{limit:1,include_docs:!1,startkey:[t._manager.class_name,r,e+"￿"],endkey:[t._manager.class_name,r,e],descending:!0}).then(function(r){if(r.rows.length){for(var i=r.rows[0].key[2],o=i.length-1;o>0&&!isNaN(parseInt(i[o]));o--)n=i[o]+n;n=(parseInt(n||0)+1).toFixed(0)}else n="1";for(;n.length<a;)n="0"+n;return t instanceof A||t instanceof P||t instanceof S?t.number_doc=e+n:t.id=e+n,t})}}},new_cat_id:{value:function(e){e||(e=(K.current_acl&&K.current_acl.prefix||"")+(this.organization&&this.organization.prefix?this.organization.prefix:K.wsql.get_user_param("zone")+"-"));var t=this._metadata.code_length-e.length,n=this instanceof A||this instanceof P||this instanceof S?"number_doc":"id",r="",a=K.wsql.alasql("select top 1 "+n+" as id from ? where "+n+" like '"+e+"%' order by "+n+" desc",[this._manager.alatable]);if(a.length){for(var i=a[0].id||"",o=i.length-1;o>0&&!isNaN(parseInt(i[o]));o--)r=i[o]+r;r=(parseInt(r||0)+1).toFixed(0)}else r="1";for(;r.length<t;)r="0"+r;return this[n]=e+r,this}}}),"undefined"!=typeof module&&module.exports&&(module.exports=I),K}); \ No newline at end of file diff --git a/dist/metadata.js b/dist/metadata.js index 001f97551..bf6f81a7b 100644 --- a/dist/metadata.js +++ b/dist/metadata.js @@ -1,5 +1,5 @@ /*! - metadata.js v0.11.223, built:2016-12-02 © Evgeniy Malyarov http://www.oknosoft.ru 2014-2016 + metadata.js v0.12.225, built:2016-12-03 © Evgeniy Malyarov http://www.oknosoft.ru 2014-2016 metadata.js may be freely distributed under the AGPL-3.0. To obtain _Oknosoft Commercial license_, contact info@oknosoft.ru */ (function(root, factory) { @@ -473,7 +473,7 @@ function MetaEngine() { this.__define({ version: { - value: "0.11.223", + value: "0.12.225", writable: false }, @@ -837,8 +837,8 @@ function MetaEngine() { */ record_log: { value: function (err) { - if($p.ireg && $p.ireg.$log) - $p.ireg.$log.record(err); + if($p.ireg && $p.ireg.log) + $p.ireg.log.record(err); console.log(err); } }, @@ -1138,6 +1138,18 @@ function MetaEngine() { value: LogManager }, + MetaObjManager: { + value: MetaObjManager + }, + + MetaFieldManager: { + value: MetaFieldManager + }, + + SchemeSettingsManager: { + value: SchemeSettingsManager + }, + AccumRegManager: { value: AccumRegManager }, @@ -1207,6 +1219,7 @@ function MetaEngine() { } }); + } /** @@ -1550,16 +1563,16 @@ function Ajax() { if(typeof auth == "object" && auth.username && auth.hasOwnProperty("password")){ username = auth.username; password = auth.password; - + }else{ if($p.ajax.username && $p.ajax.authorized){ username = $p.ajax.username; password = $p.aes.Ctr.decrypt($p.ajax.password); - + }else{ username = $p.wsql.get_user_param("user_name"); password = $p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd")); - + if(!username && $p.job_prm && $p.job_prm.guest_name){ username = $p.job_prm.guest_name; password = $p.aes.Ctr.decrypt($p.job_prm.guest_pwd); @@ -2889,7 +2902,7 @@ $p.__define({ get_acl: { value: function(class_name) { var acn = class_name.split("."); - return this._acl && this._acl[acn[0]] ? this._acl[acn[0]][acn[1]] : "e"; + return this._acl && this._acl[acn[0]] && this._acl[acn[0]][acn[1]] ? this._acl[acn[0]][acn[1]] : "e"; } } @@ -3932,11 +3945,419 @@ $p.fias = function FIAS(){}; */ function Meta() { - var _m; + var _m = { + enm: { + accumulation_record_type: [ + { + order: 0, + name: "debit", + synonym: "Приход" + }, + { + order: 1, + name: "credit", + synonym: "Расход" + } + ], + comparison_types: [ + { + order: 0, + name: "gt", + synonym: "Больше" + }, + { + order: 1, + name: "gte", + synonym: "Больше или равно" + }, + { + order: 2, + name: "lt", + synonym: "Меньше" + }, + { + order: 3, + name: "lte", + synonym: "Меньше или равно " + }, + { + order: 4, + name: "eq", + synonym: "Равно" + }, + { + order: 5, + name: "ne", + synonym: "Не равно" + }, + { + "order": 6, + "name": "in", + "synonym": "В списке" + }, + { + order: 7, + name: "nin", + synonym: "Не в списке" + }, + { + order: 8, + name: "lke", + synonym: "Подобно " + }, + { + order: 9, + name: "nlk", + synonym: "Не подобно" + } + ] + }, + cat: { + meta_objs: {}, + meta_fields: {}, + scheme_settings: { + name: "scheme_settings", + splitted: true, + synonym: "Настройки отчетов и списков", + illustration: "", + obj_presentation: "", + list_presentation: "", + input_by_string: [ + "name" + ], + hierarchical: false, + has_owners: false, + group_hierarchy: true, + main_presentation_name: true, + code_length: 0, + fields: { + obj: { + "synonym": "Объект", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 250 + } + }, + user: { + "synonym": "Пользователь", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 50 + } + }, + predefined_name: { + "synonym": "", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 256 + } + } + }, + tabular_sections: { + available_fields: { + "name": "available_fields", + "synonym": "Доступные поля", + "tooltip": "Состав, порядок и ширина колонок", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "Для плоского списка, родитель пустой", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "use": { + "synonym": "Использование", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "boolean" + ] + } + }, + "field": { + "synonym": "Поле", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "width": { + "synonym": "Ширина", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "number" + ], + "digits": 6, + "fraction_figits": 0 + } + }, + "caption": { + "synonym": "Заголовок", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + sort_fields: { + "name": "sort_fields", + "synonym": "Поля сортировки", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "field": { + "synonym": "Поле", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + grouping_fields: { + "name": "grouping_fields", + "synonym": "Поля группировки", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "field": { + "synonym": "Поле", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + selection: { + "name": "selection", + "synonym": "Отбор", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "use": { + "synonym": "Использование", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "boolean" + ] + } + }, + "left_value": { + "synonym": "Левое значение", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "comparison_type": { + "synonym": "Вид сравнения", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "right_value": { + "synonym": "Правое значение", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + scheme: { + "name": "scheme", + "synonym": "Структура", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 10 + } + }, + "kind": { + "synonym": "Вид раздела отчета", + "multiline_mode": false, + "tooltip": "список, таблица, группировка строк, группировка колонок", + "type": { + "types": [ + "string" + ], + "str_len": 10 + } + } + } + } + }, + cachable: "doc" + } + }, + doc: {}, + ireg: { + "log": { + name: "log", + note: "", + synonym: "Журнал событий", + dimensions: { + date: { + synonym: "Дата", + multiline_mode: false, + tooltip: "Время события", + type: { + types: [ + "number" + ], + digits: 15, + fraction_figits: 0 + } + }, + sequence: { + synonym: "Порядок", + multiline_mode: false, + tooltip: "Порядок следования", + type: { + types: [ + "number" + ], + digits: 6, + fraction_figits: 0 + } + } + }, + resources: { + "class": { + synonym: "Класс", + multiline_mode: false, + tooltip: "Класс события", + type: { + types: [ + "string" + ], + str_len: 100 + } + }, + note: { + synonym: "Комментарий", + multiline_mode: true, + tooltip: "Текст события", + type: { + types: [ + "string" + ], + str_len: 0 + } + }, + obj: { + synonym: "Объект", + multiline_mode: true, + tooltip: "Объект, к которому относится событие", + type: { + types: [ + "string" + ], + str_len: 0 + } + } + } + } + }, + areg: {}, + dp: {}, + rep: {}, + cch: {}, + cacc: {} + }; _md = this; - // загружает метаданные из pouchdb function meta_from_pouch(meta_db){ @@ -3946,7 +4367,7 @@ function Meta() { }) .then(function (doc) { - _m = doc; + $p._patch(_m, doc); doc = null; return meta_db.get('meta_patch'); @@ -3983,7 +4404,7 @@ function Meta() { function do_init(){ if(meta_db && !is_local && !is_remote){ - _m = meta_db; + $p._patch(_m, meta_db); meta_db = null; _md.create_managers(); @@ -4014,7 +4435,7 @@ function Meta() { if(!_m) do_init(); - else{ + else if($p.iface && $p.iface.do_reload){ // если изменились метаданные, запланировать перезагрузку setTimeout(function () { @@ -4659,7 +5080,7 @@ function DataManager(class_name){ * ### После чтения объекта с сервера * Имеет смысл для объектов с типом кеширования ("doc", "doc_remote", "meta", "e1cib"). * т.к. структура _DataObj_ может отличаться от прототипа в базе-источнике, в обработчике можно дозаполнить или пересчитать реквизиты прочитанного объекта - * + * * @event after_load * @for DataManager */ @@ -5027,7 +5448,7 @@ DataManager.prototype.sync_grid = function(attr, grid){ if(typeof attr.custom_selection == "function"){ return attr.custom_selection(attr); - + }else if(mgr.cachable == "ram"){ // запрос к alasql @@ -5091,7 +5512,7 @@ DataManager.prototype.sync_grid = function(attr, grid){ }); } - + // TODO: переделать обработку catch() return request() .then(to_grid) @@ -5384,8 +5805,8 @@ DataManager.prototype.print = function(ref, model, wnd){ // если _printing_plates содержит ссылку на обрабочтик печати, используем его if(this._printing_plates[model] instanceof DataObj) - model = this._printing_plates[model]; - + model = this._printing_plates[model]; + // если существует локальный обработчик, используем его if(model instanceof DataObj && model.execute){ @@ -5398,7 +5819,7 @@ DataManager.prototype.print = function(ref, model, wnd){ .then(tune_wnd_print); }else{ - + // иначе - печатаем средствами 1С или иного сервера var rattr = {}; $p.ajax.default_attr(rattr, $p.job_prm.irest_url()); @@ -5458,9 +5879,9 @@ DataManager.prototype.printing_plates = function(){ * @param class_name {string} - имя типа менеджера объекта */ function RefDataManager(class_name) { - + RefDataManager.superclass.constructor.call(this, class_name); - + } RefDataManager._extend(DataManager); @@ -5695,7 +6116,7 @@ RefDataManager.prototype.__define({ return this.get(); } }, - + /** * Возаращает массив запросов для создания таблиц объекта и его табличных частей * @method get_sql_struct @@ -6490,10 +6911,10 @@ function RegisterManager(class_name){ attr = {}; else if(typeof attr == "string") attr = {ref: attr}; - + if(attr.ref && return_row) return force_promise ? Promise.resolve(this.by_ref[attr.ref]) : this.by_ref[attr.ref]; - + attr.action = "select"; var arr = $p.wsql.alasql(this.get_sql_struct(attr), attr._values), @@ -6511,7 +6932,7 @@ function RegisterManager(class_name){ res.push(this.by_ref[this.get_ref(arr[i])]); } } - + return force_promise ? Promise.resolve(res) : res; }; @@ -7009,74 +7430,286 @@ InfoRegManager.prototype.slice_last = function(filter){ }; + /** - * ### Журнал событий - * Хранит и накапливает события сеанса<br /> - * Является наследником регистра сведений - * @extends InfoRegManager - * @class LogManager - * @static + * ### Абстрактный менеджер регистра накопления + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "AccumRegs"}}{{/crossLink}} + * + * @class AccumRegManager + * @extends RegisterManager + * @constructor + * @param class_name {string} - имя типа менеджера объекта. например, "areg.goods_on_stores" */ -function LogManager(){ +function AccumRegManager(class_name){ - LogManager.superclass.constructor.call(this, "ireg.$log"); + AccumRegManager.superclass.constructor.call(this, class_name); +} +AccumRegManager._extend(RegisterManager); - var smax; - this.__define({ + +/** + * ### Абстрактный менеджер справочника + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Catalogs"}}{{/crossLink}} + * + * @class CatManager + * @extends RefDataManager + * @constructor + * @param class_name {string} + */ +function CatManager(class_name) { + + CatManager.superclass.constructor.call(this, class_name); + + // реквизиты по метаданным + if(this.metadata().hierarchical && this.metadata().group_hierarchy){ /** - * Добавляет запись в журнал - * @param msg {String|Object|Error} - текст + класс события - * @param [msg.obj] {Object} - дополнительный json объект + * ### Признак "это группа" + * @property is_folder + * @for CatObj + * @type {Boolean} */ - record: { - value: function(msg){ + $p[this.obj_constructor()].prototype.__define("is_folder", { + get : function(){ return this._obj.is_folder || false}, + set : function(v){ this._obj.is_folder = $p.utils.fix_boolean(v)}, + enumerable: true, + configurable: true + }); + } - if(msg instanceof Error){ - if(console) - console.log(msg); - msg = { - class: "error", - note: msg.toString() - } - }else if(typeof msg == "object" && !msg.class && !msg.obj){ - msg = { - class: "obj", - obj: msg, - note: msg.note - }; - }else if(typeof msg != "object") - msg = {note: msg}; +} +CatManager._extend(RefDataManager); - msg.date = Date.now() + $p.wsql.time_diff; +/** + * Возвращает объект по наименованию + * @method by_name + * @param name {String|Object} - искомое наименование + * @return {DataObj} + */ +CatManager.prototype.by_name = function(name){ - // уникальность ключа - if(!smax) - smax = alasql.compile("select MAX(`sequence`) as `sequence` from `ireg_$log` where `date` = ?"); - var res = smax([msg.date]); - if(!res.length || res[0].sequence === undefined) - msg.sequence = 0; - else - msg.sequence = parseInt(res[0].sequence) + 1; + var o; - // класс сообщения - if(!msg.class) - msg.class = "note"; + this.find_rows({name: name}, function (obj) { + o = obj; + return false; + }); - $p.wsql.alasql("insert into `ireg_$log` (`ref`, `date`, `sequence`, `class`, `note`, `obj`) values (?,?,?,?,?,?)", - [msg.date + "¶" + msg.sequence, msg.date, msg.sequence, msg.class, msg.note, msg.obj ? JSON.stringify(msg.obj) : ""]); + if(!o) + o = this.get(); - } - }, + return o; +}; - /** - * Сбрасывает события на сервер - * @method backup - * @param [dfrom] {Date} - * @param [dtill] {Date} - */ - backup: { +/** + * Возвращает объект по коду + * @method by_id + * @param id {String|Object} - искомый код + * @return {DataObj} + */ +CatManager.prototype.by_id = function(id){ + + var o; + + this.find_rows({id: id}, function (obj) { + o = obj; + return false; + }); + + if(!o) + o = this.get(); + + return o; +}; + +/** + * Для иерархических кешируемых справочников возвращает путь элемента + * @param ref {String|CatObj} - ссылка или объект данных + * @return {string} - строка пути элемента + */ +CatManager.prototype.path = function(ref){ + var res = [], tobj; + + if(ref instanceof DataObj) + tobj = ref; + else + tobj = this.get(ref, false, true); + if(tobj) + res.push({ref: tobj.ref, presentation: tobj.presentation}); + + if(tobj && this.metadata().hierarchical){ + while(true){ + tobj = tobj.parent; + if(tobj.empty()) + break; + res.push({ref: tobj.ref, presentation: tobj.presentation}); + } + } + return res; +}; + + + +/** + * ### Абстрактный менеджер плана видов характеристик + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "ChartsOfCharacteristics"}}{{/crossLink}} + * + * @class ChartOfCharacteristicManager + * @extends CatManager + * @constructor + * @param class_name {string} + */ +function ChartOfCharacteristicManager(class_name){ + + ChartOfCharacteristicManager.superclass.constructor.call(this, class_name); + +} +ChartOfCharacteristicManager._extend(CatManager); + + +/** + * ### Абстрактный менеджер плана счетов + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "ChartsOfAccounts"}}{{/crossLink}} + * + * @class ChartOfAccountManager + * @extends CatManager + * @constructor + * @param class_name {string} + */ +function ChartOfAccountManager(class_name){ + + ChartOfAccountManager.superclass.constructor.call(this, class_name); + +} +ChartOfAccountManager._extend(CatManager); + + +/** + * ### Абстрактный менеджер документов + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Documents"}}{{/crossLink}} + * + * @class DocManager + * @extends RefDataManager + * @constructor + * @param class_name {string} + */ +function DocManager(class_name) { + + + DocManager.superclass.constructor.call(this, class_name); + +} +DocManager._extend(RefDataManager); + +/** + * ### Абстрактный менеджер задач + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Tasks"}}{{/crossLink}} + * + * @class TaskManager + * @extends CatManager + * @constructor + * @param class_name {string} + */ +function TaskManager(class_name){ + + TaskManager.superclass.constructor.call(this, class_name); + +} +TaskManager._extend(CatManager); + +/** + * ### Абстрактный менеджер бизнес-процессов + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "BusinessProcesses"}}{{/crossLink}} + * + * @class BusinessProcessManager + * @extends CatManager + * @constructor + * @param class_name {string} + */ +function BusinessProcessManager(class_name){ + + BusinessProcessManager.superclass.constructor.call(this, class_name); + +} +BusinessProcessManager._extend(CatManager); + + +/** + * ### Журнал событий + * Хранит и накапливает события сеанса<br /> + * Является наследником регистра сведений + * @extends InfoRegManager + * @class LogManager + * @static + */ +function LogManager(){ + + LogManager.superclass.constructor.call(this, "ireg.log"); + + var smax; + + this.__define({ + + /** + * Добавляет запись в журнал + * @param msg {String|Object|Error} - текст + класс события + * @param [msg.obj] {Object} - дополнительный json объект + */ + record: { + value: function(msg){ + + if(msg instanceof Error){ + if(console) + console.log(msg); + msg = { + class: "error", + note: msg.toString() + } + }else if(typeof msg == "object" && !msg.class && !msg.obj){ + msg = { + class: "obj", + obj: msg, + note: msg.note + }; + }else if(typeof msg != "object") + msg = {note: msg}; + + msg.date = Date.now() + $p.wsql.time_diff; + + // уникальность ключа + if(!smax) + smax = alasql.compile("select MAX(`sequence`) as `sequence` from `ireg_log` where `date` = ?"); + var res = smax([msg.date]); + if(!res.length || res[0].sequence === undefined) + msg.sequence = 0; + else + msg.sequence = parseInt(res[0].sequence) + 1; + + // класс сообщения + if(!msg.class) + msg.class = "note"; + + $p.wsql.alasql("insert into `ireg_log` (`ref`, `date`, `sequence`, `class`, `note`, `obj`) values (?,?,?,?,?,?)", + [msg.date + "¶" + msg.sequence, msg.date, msg.sequence, msg.class, msg.note, msg.obj ? JSON.stringify(msg.obj) : ""]); + + } + }, + + /** + * Сбрасывает события на сервер + * @method backup + * @param [dfrom] {Date} + * @param [dtill] {Date} + */ + backup: { value: function(dfrom, dtill){ } @@ -7124,7 +7757,7 @@ function LogManager(){ return undefined; var parts = ref.split("¶"); - $p.wsql.alasql("select * from `ireg_$log` where date=" + parts[0] + " and sequence=" + parts[1]).forEach(function (row) { + $p.wsql.alasql("select * from `ireg_log` where date=" + parts[0] + " and sequence=" + parts[1]).forEach(function (row) { new RegisterRow(row, this); }.bind(this)); } @@ -7137,7 +7770,7 @@ function LogManager(){ value: function(attr){ if(attr && attr.action == "get_selection"){ - var sql = "select * from `ireg_$log`"; + var sql = "select * from `ireg_log`"; if(attr.date_from){ if (attr.date_till) sql += " where `date` >= ? and `date` <= ?"; @@ -7196,224 +7829,46 @@ function LogManager(){ return xml + "</rows>"; } } + }); } LogManager._extend(InfoRegManager); - /** - * ### Абстрактный менеджер регистра накопления - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "AccumRegs"}}{{/crossLink}} - * - * @class AccumRegManager - * @extends RegisterManager - * @constructor - * @param class_name {string} - имя типа менеджера объекта. например, "areg.goods_on_stores" + * ### Менеджер объектов метаданных + * Используется для формирования списков типов документов, справочников и т.д. + * Например, при работе в интерфейсе с составными типами */ -function AccumRegManager(class_name){ +function MetaObjManager() { - AccumRegManager.superclass.constructor.call(this, class_name); + MetaObjManager.superclass.constructor.call(this, "cat.meta_objs"); } -AccumRegManager._extend(RegisterManager); - - +MetaObjManager._extend(CatManager); /** - * ### Абстрактный менеджер справочника - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Catalogs"}}{{/crossLink}} - * - * @class CatManager - * @extends RefDataManager - * @constructor - * @param class_name {string} + * ### Менеджер доступных полей + * Используется при настройке отчетов и динамических списков */ -function CatManager(class_name) { - - CatManager.superclass.constructor.call(this, class_name); - - // реквизиты по метаданным - if(this.metadata().hierarchical && this.metadata().group_hierarchy){ - - /** - * ### Признак "это группа" - * @property is_folder - * @for CatObj - * @type {Boolean} - */ - $p[this.obj_constructor()].prototype.__define("is_folder", { - get : function(){ return this._obj.is_folder || false}, - set : function(v){ this._obj.is_folder = $p.utils.fix_boolean(v)}, - enumerable: true, - configurable: true - }); - } +function MetaFieldManager() { + MetaFieldManager.superclass.constructor.call(this, "cat.meta_fields"); } -CatManager._extend(RefDataManager); - -/** - * Возвращает объект по наименованию - * @method by_name - * @param name {String|Object} - искомое наименование - * @return {DataObj} - */ -CatManager.prototype.by_name = function(name){ - - var o; - - this.find_rows({name: name}, function (obj) { - o = obj; - return false; - }); - - if(!o) - o = this.get(); - - return o; -}; - -/** - * Возвращает объект по коду - * @method by_id - * @param id {String|Object} - искомый код - * @return {DataObj} - */ -CatManager.prototype.by_id = function(id){ +MetaFieldManager._extend(CatManager); - var o; - - this.find_rows({id: id}, function (obj) { - o = obj; - return false; - }); - - if(!o) - o = this.get(); - - return o; -}; /** - * Для иерархических кешируемых справочников возвращает путь элемента - * @param ref {String|CatObj} - ссылка или объект данных - * @return {string} - строка пути элемента + * ### Менеджер настроек отчетов и динсписков */ -CatManager.prototype.path = function(ref){ - var res = [], tobj; - - if(ref instanceof DataObj) - tobj = ref; - else - tobj = this.get(ref, false, true); - if(tobj) - res.push({ref: tobj.ref, presentation: tobj.presentation}); - - if(tobj && this.metadata().hierarchical){ - while(true){ - tobj = tobj.parent; - if(tobj.empty()) - break; - res.push({ref: tobj.ref, presentation: tobj.presentation}); - } - } - return res; -}; - - - -/** - * ### Абстрактный менеджер плана видов характеристик - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "ChartsOfCharacteristics"}}{{/crossLink}} - * - * @class ChartOfCharacteristicManager - * @extends CatManager - * @constructor - * @param class_name {string} - */ -function ChartOfCharacteristicManager(class_name){ - - ChartOfCharacteristicManager.superclass.constructor.call(this, class_name); +function SchemeSettingsManager() { + SchemeSettingsManager.superclass.constructor.call(this, "cat.scheme_settings"); } -ChartOfCharacteristicManager._extend(CatManager); +SchemeSettingsManager._extend(CatManager); -/** - * ### Абстрактный менеджер плана счетов - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "ChartsOfAccounts"}}{{/crossLink}} - * - * @class ChartOfAccountManager - * @extends CatManager - * @constructor - * @param class_name {string} - */ -function ChartOfAccountManager(class_name){ - - ChartOfAccountManager.superclass.constructor.call(this, class_name); - -} -ChartOfAccountManager._extend(CatManager); - - -/** - * ### Абстрактный менеджер документов - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Documents"}}{{/crossLink}} - * - * @class DocManager - * @extends RefDataManager - * @constructor - * @param class_name {string} - */ -function DocManager(class_name) { - - - DocManager.superclass.constructor.call(this, class_name); - -} -DocManager._extend(RefDataManager); - -/** - * ### Абстрактный менеджер задач - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Tasks"}}{{/crossLink}} - * - * @class TaskManager - * @extends CatManager - * @constructor - * @param class_name {string} - */ -function TaskManager(class_name){ - - TaskManager.superclass.constructor.call(this, class_name); - -} -TaskManager._extend(CatManager); - -/** - * ### Абстрактный менеджер бизнес-процессов - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "BusinessProcesses"}}{{/crossLink}} - * - * @class BusinessProcessManager - * @extends CatManager - * @constructor - * @param class_name {string} - */ -function BusinessProcessManager(class_name){ - - BusinessProcessManager.superclass.constructor.call(this, class_name); - -} -BusinessProcessManager._extend(CatManager); - /** * Конструкторы объектов данных diff --git a/dist/metadata.min.js b/dist/metadata.min.js index 506b4fc3f..42d544ff5 100644 --- a/dist/metadata.min.js +++ b/dist/metadata.min.js @@ -1,15 +1,16 @@ /*! - metadata.js v0.11.223, built:2016-12-02 © Evgeniy Malyarov http://www.oknosoft.ru 2014-2016 + metadata.js v0.12.225, built:2016-12-03 © Evgeniy Malyarov http://www.oknosoft.ru 2014-2016 metadata.js may be freely distributed under the AGPL-3.0. To obtain _Oknosoft Commercial license_, contact info@oknosoft.ru */ -!function(e,t){"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?module.exports=t():e.$p=t()}(this,function(){function MetaEngine(){this.__define({version:{value:"0.11.223",writable:!1},toString:{value:function(){return"Oknosoft data engine. v:"+this.version},writable:!1},utils:{value:new Utils},injected_data:{value:{},writable:!1},ajax:{value:new Ajax,writable:!1},msg:{value:new Messages,writable:!1},wsql:{value:new WSQL,writable:!1},eve:{value:new AppEvents,writable:!1},aes:{value:new Aes("metadata.js"),writable:!1},moment:{get:function(){return this.utils.moment}},_patch:{value:function(e,t){for(var n in t)"object"==typeof t[n]&&e[n]&&"object"==typeof e[n]?$p._patch(e[n],t[n]):e[n]=t[n];return e}},_find:{value:function(e,t,n){var a,i,s;if("object"!=typeof t)for(i in e){a=e[i];for(var o in a)if("function"!=typeof a[o]&&$p.utils.is_equal(a[o],t))return a}else for(i in e){a=e[i],s=!0;for(var o in t)if("function"!=typeof a[o]&&!$p.utils.is_equal(a[o],t[o])){s=!1;break}if(s)return a}}},_selection:{value:function(e,t){var n,a,i,s=!0;if(t)if("function"==typeof t)s=t.call(this,e);else for(n in t)if(a=t[n],i="object"==typeof a,"_"!=n.substr(0,1))if("function"==typeof a){if(s=a.call(this,e,n),!s)break}else if("or"==n&&Array.isArray(a)){if(s=a.some(function(t){var n=Object.keys(t)[0];return t[n].hasOwnProperty("like")?e[n]&&e[n].toLowerCase().indexOf(t[n].like.toLowerCase())!=-1:$p.utils.is_equal(e[n],t[n])}),!s)break}else if(i&&a.hasOwnProperty("like")){if(!e[n]||e[n].toLowerCase().indexOf(a.like.toLowerCase())==-1){s=!1;break}}else if(i&&a.hasOwnProperty("not")){if($p.utils.is_equal(e[n],a.not)){s=!1;break}}else if(i&&a.hasOwnProperty("in")){if(s=a.in.some(function(t){return $p.utils.is_equal(t,e[n])}),!s)break}else if(i&&a.hasOwnProperty("lt")){if(s=e[n]<a.lt,!s)break}else if(i&&a.hasOwnProperty("gt")){if(s=e[n]>a.gt,!s)break}else if(i&&a.hasOwnProperty("between")){var o=e[n];if("number"!=typeof o&&(o=$p.utils.fix_date(e[n])),s=o>=a.between[0]&&o<=a.between[1],!s)break}else if(!$p.utils.is_equal(e[n],a)){s=!1;break}return s}},_find_rows:{value:function(e,t,n){var a,i,s=[],o=0;t&&(t._top?(i=t._top,delete t._top):i=300);for(var r in e)if(a=e[r],$p._selection.call(this,a,t)){if(n){if(n.call(this,a)===!1)break}else s.push(a);if(i&&(o++,o>=i))break}return s}},on:{value:function(e,t){if("object"!=typeof e)return this.eve.attachEvent(e,t);for(var n in e)e[n]._evnts||(e[n]._evnts=[]),e[n]._evnts.push(this.eve.attachEvent(n,e[n]))}},off:{value:function(e){"function"==typeof e&&e._evnts?e._evnts.forEach(function(e){$p.eve.detachEvent(e)}):e?$p.eve.detachEvent(e):$p.eve.detachAllEvents()}},record_log:{value:function(e){$p.ireg&&$p.ireg.$log&&$p.ireg.$log.record(e),console.log(e)}},md:{value:new Meta},enm:{value:new function(){this.toString=function(){return $p.msg.meta_enn_mgr}}},cat:{value:new function(){this.toString=function(){return $p.msg.meta_cat_mgr}}},doc:{value:new function(){this.toString=function(){return $p.msg.meta_doc_mgr}}},ireg:{value:new function(){this.toString=function(){return $p.msg.meta_ireg_mgr}}},areg:{value:new function(){this.toString=function(){return $p.msg.meta_areg_mgr}}},accreg:{value:new function(){this.toString=function(){return $p.msg.meta_accreg_mgr}}},dp:{value:new function(){this.toString=function(){return $p.msg.meta_dp_mgr}}},rep:{value:new function(){this.toString=function(){return $p.msg.meta_reports_mgr}}},cacc:{value:new function(){this.toString=function(){return $p.msg.meta_charts_of_accounts_mgr}}},cch:{value:new function(){this.toString=function(){return $p.msg.meta_charts_of_characteristic_mgr}}},tsk:{value:new function(){this.toString=function(){return $p.msg.meta_task_mgr}}},bp:{value:new function(){this.toString=function(){return $p.msg.meta_bp_mgr}}},DataManager:{value:DataManager},RefDataManager:{value:RefDataManager},DataProcessorsManager:{value:DataProcessorsManager},EnumManager:{value:EnumManager},RegisterManager:{value:RegisterManager},InfoRegManager:{value:InfoRegManager},LogManager:{value:LogManager},AccumRegManager:{value:AccumRegManager},CatManager:{value:CatManager},ChartOfCharacteristicManager:{value:ChartOfCharacteristicManager},ChartOfAccountManager:{value:ChartOfAccountManager},DocManager:{value:DocManager},TaskManager:{value:TaskManager},BusinessProcessManager:{value:BusinessProcessManager},DataObj:{value:DataObj},CatObj:{value:CatObj},DocObj:{value:DocObj},DataProcessorObj:{value:DataProcessorObj},TaskObj:{value:TaskObj},BusinessProcessObj:{value:BusinessProcessObj},EnumObj:{value:EnumObj},RegisterRow:{value:RegisterRow},TabularSection:{value:TabularSection},TabularSectionRow:{value:TabularSectionRow}})}function Utils(){this.moment="function"==typeof moment?moment:require("moment"),this.moment._masks={date:"DD.MM.YY",date_time:"DD.MM.YYYY HH:mm",ldt:"DD MMMM YYYY, HH:mm",iso:"YYYY-MM-DDTHH:mm:ss"},this.fix_date=function(e,t){if(e instanceof Date)return e;var n=this.moment(e,["DD-MM-YYYY","DD-MM-YYYY HH:mm","DD-MM-YYYY HH:mm:ss","DD-MM-YY HH:mm","YYYYDDMMHHmmss",this.moment.ISO_8601]);return n.isValid()?n.toDate():t?this.blank.date:e},this.fix_guid=function(e,t){if(e&&"string"==typeof e);else{if(e instanceof DataObj)return e.ref;if(e&&"object"==typeof e)if(e.presentation){if(e.ref)return e.ref;if(e.name)return e.name}else e="object"==typeof e.ref&&e.ref.hasOwnProperty("ref")?e.ref.ref:e.ref}return this.is_guid(e)||t===!1?e:t?this.generate_guid():this.blank.guid},this.fix_number=function(e,t){var n=parseFloat(e);return isNaN(n)?t?0:e:n},this.fix_boolean=function(e){return"string"==typeof e?!(!e||"false"==e.toLowerCase()):!!e},this.blank={date:this.fix_date("0001-01-01T00:00:00"),guid:"00000000-0000-0000-0000-000000000000",by_type:function(e){var t;return t=e.is_ref?this.guid:e.date_part?this.date:e.digits?0:(!e.types||"boolean"!=e.types[0])&&""}},this.fetch_type=function(e,t){var n=e;return t.is_ref?n=this.fix_guid(e):t.date_part?n=this.fix_date(e,!0):t.digits?n=this.fix_number(e,!0):"boolean"==t.types[0]&&(n=this.fix_boolean(e)),n},this.date_add_day=function(e,t,n){var a=new Date(e);return a.setDate(e.getDate()+t),n&&a.setHours(0,-a.getTimezoneOffset(),0,0),a},this.generate_guid=function(){var e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var n=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?n:7&n|8).toString(16)})},this.is_guid=function(e){return!("string"!=typeof e||e.length<36)&&(e.length>36&&(e=e.substr(0,36)),/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(e))},this.is_empty_guid=function(e){return!e||e===this.blank.guid},this.is_data_obj=function(e){return e&&e instanceof DataObj},this.is_data_mgr=function(e){return e&&e instanceof DataManager},this.is_equal=function(e,t){return e==t||typeof e!=typeof t&&this.fix_guid(e,!1)==this.fix_guid(t,!1)},this.blob_as_text=function(e,t){return new Promise(function(n,a){var i=new FileReader;i.onload=function(e){n(i.result)},i.onerror=function(e){a(e)},"data_url"==t?i.readAsDataURL(e):i.readAsText(e)})}}function Ajax(){function e(e,t,n,a,i){return new Promise(function(s,o){if("undefined"==typeof window&&a&&a.request)a.request({url:encodeURI(t),headers:{Authorization:a.auth}},function(e,t,n){e?o(e):200!=t.statusCode?o({message:t.statusMessage,description:n,status:t.statusCode}):s({response:n})});else{var r=new XMLHttpRequest;if(window.dhx4&&window.dhx4.isIE&&(t=encodeURI(t)),a){var l,c;"object"==typeof a&&a.username&&a.hasOwnProperty("password")?(l=a.username,c=a.password):$p.ajax.username&&$p.ajax.authorized?(l=$p.ajax.username,c=$p.aes.Ctr.decrypt($p.ajax.password)):(l=$p.wsql.get_user_param("user_name"),c=$p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd")),!l&&$p.job_prm&&$p.job_prm.guest_name&&(l=$p.job_prm.guest_name,c=$p.aes.Ctr.decrypt($p.job_prm.guest_pwd))),r.open(e,t,!0,l,c),r.withCredentials=!0,r.setRequestHeader("Authorization","Basic "+btoa(unescape(encodeURIComponent(l+":"+c))))}else r.open(e,t,!0);i&&i.call(this,r),"GET"!=e?this.hide_headers||a.hide_headers||(r.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),r.setRequestHeader("X-Requested-With","XMLHttpRequest")):n=null,r.onload=function(){200==r.status&&(r.response instanceof Blob||"<!DOCTYPE"!==r.response.substr(0,9))?(void 0==r.responseURL&&(r.responseURL=t),s(r)):o(r.response?{message:r.statusText,description:r.response,status:r.status}:Error(r.statusText))},r.onerror=function(){o(Error("Network Error"))},r.send(n)}})}this.username="",this.password="",this.root=!0,this.authorized=!1,this.get=function(t){return e.call(this,"GET",t)},this.post=function(t,n){return 1==arguments.length?n="":2==arguments.length&&"function"==typeof n?(onLoad=n,n=""):n=String(n),e.call(this,"POST",t,n)},this.get_ex=function(t,n,a){return e.call(this,"GET",t,null,n,a)},this.post_ex=function(t,n,a,i){return e.call(this,"POST",t,n,a,i)},this.put_ex=function(t,n,a,i){return e.call(this,"PUT",t,n,a,i)},this.patch_ex=function(t,n,a,i){return e.call(this,"PATCH",t,n,a,i)},this.delete_ex=function(t,n,a){return e.call(this,"DELETE",t,null,n,a)},this.get_and_show_blob=function(e,t,n){function a(t){return e=window.URL.createObjectURL(t.response),i=window.open(e,"wnd_print",s),i.onload=function(t){window.URL.revokeObjectURL(e)},i}var i,s="menubar=no,toolbar=no,location=no,status=no,directories=no,resizable=yes,scrollbars=yes";return!n||"string"==typeof n&&n.toLowerCase().indexOf("post")!=-1?this.post_ex(e,"object"==typeof t?JSON.stringify(t):t,!0,function(e){e.responseType="blob"}).then(a):this.get_ex(e,!0,function(e){e.responseType="blob"}).then(a)},this.get_and_save_blob=function(e,t,n){return this.post_ex(e,"object"==typeof t?JSON.stringify(t):t,!0,function(e){e.responseType="blob"}).then(function(e){saveAs(e.response,n)})},this.default_attr=function(e,t){e.url||(e.url=t),e.username||(e.username=this.username),e.password||(e.password=this.password),e.hide_headers=!0,$p.job_prm["1c"]&&(e.auth=$p.job_prm["1c"].auth,e.request=$p.job_prm["1c"].request)}}function WSQL(){var e,t=this,n={};this.__define({js_time_diff:{value:-new Date("0001-01-01").valueOf()},time_diff:{get:function(){var e=this.get_user_param("time_diff","number");return!e||isNaN(e)||e<621355716e5||e>62135622e6?this.js_time_diff:e}},set_user_param:{value:function(t,a){var i=a;"object"==typeof a?i=JSON.stringify(a):a===!1&&(i=""),e.setItem($p.job_prm.local_storage_prefix+t,i),n[t]=a}},get_user_param:{value:function(t,a){return!n.hasOwnProperty(t)&&e&&(n[t]=this.fetch_type(e.getItem($p.job_prm.local_storage_prefix+t),a)),n[t]}},promise:{value:function(e,n){return new Promise(function(a,i){t.alasql(e,n||[],function(e,t){t?i(t):a(e)})})}},save_options:{value:function(e,n){return t.set_user_param(e+"_"+n.name,n)}},restore_options:{value:function(e,n){var a=t.get_user_param(e+"_"+n.name,"object");for(var i in a)if("object"!=typeof a[i])n[i]=a[i];else{n[i]||(n[i]={});for(var s in a[i])n[i][s]=a[i][s]}return n}},fetch_type:{value:function(e,t){if("object"==t){try{e=JSON.parse(e)}catch(t){e={}}return e}return"number"==t?$p.utils.fix_number(e,!0):"date"==t?$p.utils.fix_date(e,!0):"boolean"==t?$p.utils.fix_boolean(e):e}},alasql:{value:"undefined"!=typeof alasql?alasql:require("alasql")},init_params:{value:function(){if(!$p.job_prm.local_storage_prefix&&!$p.job_prm.create_tables)return Promise.resolve();e="undefined"==typeof localStorage?"undefined"==typeof WorkerGlobalScope?new require("node-localstorage").LocalStorage("./localstorage"):{setItem:function(e,t){},getItem:function(e){}}:localStorage;var n,a=[{p:"user_name",v:"",t:"string"},{p:"user_pwd",v:"",t:"string"},{p:"browser_uid",v:$p.utils.generate_guid(),t:"string"},{p:"zone",v:$p.job_prm.hasOwnProperty("zone")?$p.job_prm.zone:1,t:$p.job_prm.zone_is_string?"string":"number"},{p:"enable_save_pwd",v:$p.job_prm.enable_save_pwd,t:"boolean"},{p:"autologin",v:"",t:"boolean"},{p:"skin",v:"dhx_web",t:"string"},{p:"rest_path",v:"",t:"string"}];$p.job_prm.additional_params&&(a=a.concat($p.job_prm.additional_params)),e.getItem($p.job_prm.local_storage_prefix+"zone")||(n=$p.job_prm.hasOwnProperty("zone")?$p.job_prm.zone:1),$p.job_prm.url_prm.hasOwnProperty("zone")&&(n=$p.job_prm.zone_is_string?$p.job_prm.url_prm.zone:$p.utils.fix_number($p.job_prm.url_prm.zone,!0)),void 0!==n&&t.set_user_param("zone",n),a.forEach(function(e){(void 0==t.get_user_param(e.p,e.t)||!t.get_user_param(e.p,e.t)&&e.p.indexOf("url")!=-1)&&t.set_user_param(e.p,$p.job_prm.hasOwnProperty(e.p)?$p.job_prm[e.p]:e.v)});var i={path:t.get_user_param("couch_path","string")||$p.job_prm.couch_path||"",zone:t.get_user_param("zone","number"),prefix:$p.job_prm.local_storage_prefix,suffix:t.get_user_param("couch_suffix","string")||"",user_node:$p.job_prm.user_node,noreplicate:$p.job_prm.noreplicate};i.path&&(t.__define("pouch",{value:new Pouch}),t.pouch.init(i)),this.create_tables&&(this.alasq(this.create_tables,[]),this.create_tables="")}},drop_tables:{value:function(e){function n(){s--,s<=0?setTimeout(e,10):a()}function a(){var e=o[s-1].tableid;"_"==e.substr(0,1)?n():t.alasql("drop table IF EXISTS "+e,[],n)}function i(e){o=e,(s=e.length)?a():n()}var s=0,o=[];t.alasql("SHOW TABLES",[],i)}}}),this.__define({aladb:{value:new this.alasql.Database("md")}})}function Col_struct(e,t,n,a,i,s){this.id=e,this.width=t,this.type=n,this.align=a,this.sort=i,this.caption=s}function InterfaceObjs(){function e(e,t,n){if(this.layout=e.attachLayout({pattern:"2U",cells:[{id:"a",text:"Разделы",collapsed_text:"Разделы",width:220},{id:"b",text:"Раздел",header:!1}],offsets:{top:0,right:0,bottom:0,left:0}}),this.tree=this.layout.cells("a").attachTreeView(),this.tree.attachEvent("onSelect",function(e,t){if(t){var a=$p.md.mgr_by_class_name(e);a instanceof DataProcessorsManager?a.form_rep(this.layout.cells("b"),n||{hide_header:!0}):a&&a.form_list(this.layout.cells("b"),n||{hide_header:!0})}}.bind(this)),!t){var a=$p.md.get_classes();t=[];for(var i in a)a[i].length&&t.push(i)}1==t.length?$p.md.get_classes()[t[0]].forEach(function(e){var n=t[0]+"."+e,a=$p.md.get(n);a.hide||(this.tree.addItem(n,a.list_presentation||a.synonym),this.tree.setItemIcons(n,{file:"icon_1c_"+t[0]}))}.bind(this)):t.forEach(function(e){this.tree.addItem(e,$p.msg["meta_"+e]),this.tree.setItemIcons(e,{file:"icon_1c_"+e,folder_opened:"icon_1c_"+e,folder_closed:"icon_1c_"+e}),$p.md.get_classes()[e].forEach(function(t){var n=e+"."+t,a=$p.md.get(n);a.hide||(this.tree.addItem(n,a.list_presentation||a.synonym,e),this.tree.setItemIcons(n,{file:"icon_1c_"+e}))}.bind(this))}.bind(this))}function t(e){e.attachHTMLString($p.injected_data["view_settings.html"]),this.cont=e.cell.querySelector(".dhx_cell_cont_tabbar"),this.cont.style.overflow="auto",this.form2=function(e){var t=new dhtmlXForm(e,[{type:"settings",labelWidth:80,position:"label-left"},{type:"label",labelWidth:320,label:"Адрес CouchDB",className:"label_options"},{type:"input",inputWidth:220,name:"couch_path",label:"Путь:",validate:"NotEmpty"},{type:"template",label:"",value:"",note:{text:"Можно указать как относительный, так и абсолютный URL публикации CouchDB",width:320}},{type:"label",labelWidth:320,label:"Адрес http сервиса 1С",className:"label_options"},{type:"input",inputWidth:220,name:"rest_path",label:"Путь",validate:"NotEmpty"},{type:"template",label:"",value:"",note:{text:"Можно указать как относительный, так и абсолютный URL публикации 1С OData",width:320}},{type:"label",labelWidth:320,label:"Значение разделителя данных",className:"label_options"},{type:"input",inputWidth:220,name:"zone",label:"Зона:",numberFormat:["0","",""],validate:"NotEmpty,ValidInteger"},{type:"template",label:"",value:"",note:{text:"Для неразделенной публикации, зона = 0",width:320}},{type:"label",labelWidth:320,label:"Суффикс базы пользователя",className:"label_options"},{type:"input",inputWidth:220,name:"couch_suffix",label:"Суффикс:"},{type:"template",label:"",value:"",note:{text:"Назначается абоненту при регистрации",width:320}},{type:"block",blockOffset:0,name:"block_buttons",list:[{type:"button",name:"save",value:"<i class='fa fa-floppy-o fa-lg'></i>",tooltip:"Применить настройки и перезагрузить программу"},{type:"newcolumn"},{type:"button",offsetLeft:20,name:"reset",value:"<i class='fa fa-refresh fa-lg'></i>",tooltip:"Стереть справочники и перезаполнить данными сервера"}]}]);return t.cont.style.fontSize="100%",["zone","couch_path","couch_suffix","rest_path"].forEach(function(e){"zone"==e?t.setItemValue(e,$p.wsql.get_user_param(e)):t.setItemValue(e,$p.wsql.get_user_param(e)||$p.job_prm[e])}),t.attachEvent("onChange",function(e,t,n){$p.wsql.set_user_param(e,"enable_save_pwd"==e?n||"":t)}),t.disableItem("couch_suffix"),$p.job_prm.rest_path||t.disableItem("rest_path"),t.attachEvent("onButtonClick",function(e){"save"==e?($p.wsql.pouch.log_out(),setTimeout(function(){$p.eve.redirect=!0,location.reload(!0)},1e3)):"reset"==e&&dhtmlx.confirm({title:"Сброс данных",text:"Стереть справочники и перезаполнить данными сервера?",cancel:$p.msg.cancel,callback:function(e){e&&$p.wsql.pouch.reset_local_data()}})}),t}(this.cont.querySelector("[name=form2]").firstChild),this.form1=function(e){var t=new dhtmlXForm(e,[{type:"settings",labelWidth:320,position:"label-left"},{type:"label",label:"Тип устройства",className:"label_options"},{type:"block",blockOffset:0,name:"block_device_type",list:[{type:"settings",labelAlign:"left",position:"label-right"},{type:"radio",name:"device_type",labelWidth:120,label:'<i class="fa fa-desktop"></i> Компьютер',value:"desktop"},{type:"newcolumn"},{type:"radio",name:"device_type",labelWidth:150,label:'<i class="fa fa-mobile fa-lg"></i> Телефон, планшет',value:"phone"}]},{type:"template",label:"",value:"",note:{text:"Класс устройства определяется автоматически, но пользователь может задать его явно",width:320}},{type:"label",label:"Сохранять пароль пользователя",className:"label_options"},{type:"checkbox",name:"enable_save_pwd",label:"Разрешить:",labelWidth:90,checked:$p.wsql.get_user_param("enable_save_pwd","boolean")},{type:"template",label:"",value:"",note:{text:"Не рекомендуется, если к компьютеру имеют доступ посторонние лица",width:320}},{type:"template",label:"",value:"",note:{text:"",width:320}},{type:"label",label:"Подключаемые модули",className:"label_options"},{type:"input",position:"label-top",inputWidth:320,name:"modifiers",label:"Модификаторы:",value:$p.wsql.get_user_param("modifiers"),rows:3,style:"height:80px;"},{type:"template",label:"",value:"",note:{text:"Список дополнительных модулей",width:320}}]);return t.cont.style.fontSize="100%",t.checkItem("device_type",$p.job_prm.device_type),t.attachEvent("onChange",function(e,t,n){$p.wsql.set_user_param(e,"enable_save_pwd"==e?n||"":t)}),t.disableItem("modifiers"),t.getInput("modifiers").onchange=function(){$p.wsql.set_user_param("modifiers",this.value)},t}(this.cont.querySelector("[name=form1]").firstChild)}var n=this;this.clear_svgs=function(e){for("string"==typeof e&&(e=document.getElementById(e));e.firstChild;)e.removeChild(e.firstChild)},this.get_offset=function(e){var t={left:0,top:0};if(e.offsetParent)do t.left+=e.offsetLeft,t.top+=e.offsetTop;while(e=e.offsetParent);return t},this.normalize_xml=function(e){if(!e)return"";var t={"&":"&",'"':""","'":"'","<":"<",">":">"};return e.replace(/[&"'<>]/g,function(e){return t[e]})},this.scale_svg=function(e,t,n){var a,i,s,o,r,l,c,p,d,u={},f="number"==typeof t?t:t.height,m="number"==typeof t?(1.5*t).round(0):t.width,h="number"==typeof t?1/0:t.zoom||1/0;r=e.indexOf(">"),c=e.substring(5,r),s=c.split(" "),o=e.substr(r+1),o=o.substr(0,o.length-6);for(a in s)e=s[a].split("="),"width,height,x,y".indexOf(e[0])!=-1&&(e[1]=Number(e[1].replace(/"/g,"")),u[e[0]]=e[1]);(l=c.indexOf("viewBox="))!=-1?(p=c.substring(l+9),d='viewBox="'+p.substring(0,p.indexOf('"'))+'"'):d='viewBox="'+(u.x||0)+" "+(u.y||0)+" "+(u.width-n)+" "+(u.height-n)+'"';var _=u.height,g=u.width;return i=(f-n)/_,u.height=f,u.width=(g*i).round(0),u.width>m&&(i=(m-n)/g,u.height=(_*i).round(0),u.width=m),i>h&&(i=h,u.height=(_*i).round(0),u.width=(g*i).round(0)),u.x=(u.x*i).round(0),u.y=(u.y*i).round(0),'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="'+u.width+'" height="'+u.height+'" x="'+u.x+'" y="'+u.y+'" xml:space="preserve" '+d+">"+o+"</svg>"},this.bind_help=function(e,t){function n(e){if(!e.help_path)return void $p.msg.show_msg({title:"Справка",type:"alert-info",text:$p.msg.not_implemented})}e instanceof dhtmlXCellObject||(!e.help_path&&t&&(e.help_path=t),e.button("help").show(),e.button("help").enable(),e.attachEvent("onHelp",n))},this.set_hash=function(e,t,a,i){var s={},o=$p.job_prm.parse_url();1==arguments.length&&"object"==typeof e&&(s=e,s.hasOwnProperty("obj")&&(e=s.obj,delete s.obj),s.hasOwnProperty("ref")&&(t=s.ref,delete s.ref),s.hasOwnProperty("frm")&&(a=s.frm,delete s.frm),s.hasOwnProperty("view")&&(i=s.view,delete s.view)),void 0===e&&(e=o.obj||""),void 0===t&&(t=o.ref||""),void 0===a&&(a=o.frm||""),void 0===i&&(i=o.view||"");var r="obj="+e+"&ref="+t+"&frm="+a+"&view="+i;for(var l in s)r+="&"+l+"="+s[l];location.hash.substr(1)==r?n.hash_route():location.hash=r},this.hash_route=function(e){var t,a=$p.job_prm.parse_url(),i=$p.eve.callEvent("hash_route",[a]);if(i===!1||n.before_route&&n.before_route(e)===!1||$p.ajax.authorized&&(a.ref&&"undefined"!=typeof _md?(t=_md.mgr_by_class_name(a.obj),t&&t[a.frm||"form_obj"](n.docs,a.ref)):a.view&&n.swith_view&&n.swith_view(a.view)),e)return n.cancel_bubble(e)},this.cancel_bubble=function(e){var t=e||event;return t&&t.stopPropagation&&t.stopPropagation(),t&&!t.cancelBubble&&(t.cancelBubble=!0),!1},this.Col_struct=Col_struct,this.init_sidebar=function(e,t,a){n.btn_auth_sync=new n.OBtnAuthSync,n.btns_nav=function(e){return n.btn_auth_sync.bind(new n.OTooolBar({wrapper:e,class_name:"md_otbnav",width:"260px",height:"28px",top:"3px",right:"3px",name:"right",buttons:t,onclick:function(e){return n.main.cells(e).setActive(!0),!1}}))},n.main=new dhtmlXSideBar({parent:document.body,icons_path:a||"dist/imgs/",width:180,header:!0,template:"tiles",autohide:!0,items:e,offsets:{top:0,right:0,bottom:0,left:0}}),n.main.attachEvent("onSelect",function(e){var t=$p.job_prm.parse_url();t.view!=e&&n.set_hash(t.obj,t.ref,t.frm,e),n["view_"+e](n.main.cells(e))}),n.main.progressOn();var i=$p.job_prm.parse_url();i.view&&n.main.getAllItems().indexOf(i.view)!=-1?setTimeout(n.hash_route):n.set_hash(i.obj,i.ref,i.frm,"doc")},this.All_meta_objs=e,this.Setting2col=t,this.do_reload=function(){function e(){dhtmlx.confirm({title:$p.msg.file_new_date_title,text:$p.msg.file_new_date,ok:"Перезагрузка",cancel:"Продолжить",callback:function(n){n?($p.wsql.pouch.log_out(),setTimeout(function(){$p.eve.redirect=!0,location.reload(!0)},1e3)):(t++,setTimeout(e,3e4*t))}})}var t=0;e()}}function Pouch(){var e,t,n,a,i=this,s={};i.__define({DB:{value:"undefined"==typeof PouchDB?require("pouchdb-core").plugin(require("pouchdb-adapter-memory")).plugin(require("pouchdb-adapter-http")).plugin(require("pouchdb-replication")).plugin(require("pouchdb-mapreduce")):PouchDB},init:{value:function(e){s._mixin(e),s.path&&0!=s.path.indexOf("http")&&"undefined"!=typeof location&&(s.path=location.protocol+"//"+location.host+s.path)}},local:{get:function(){if(!e){var t={auto_compaction:!0,revs_limit:2};e={ram:new i.DB(s.prefix+s.zone+"_ram",t),doc:new i.DB(s.prefix+s.zone+"_doc",t),meta:new i.DB(s.prefix+"meta",t),sync:{}}}return s.path&&!e._meta&&(e._meta=new i.DB(s.path+"meta",{auth:{username:"guest",password:"meta"},skip_setup:!0}),i.run_sync(e.meta,e._meta,"meta")),e}},remote:{get:function(){return!t&&n&&(t={ram:new i.DB(s.path+s.zone+"_ram",{auth:{username:n.username,password:n.password},skip_setup:!0}),doc:new i.DB(s.path+s.zone+"_doc"+s.suffix,{auth:{username:n.username,password:n.password},skip_setup:!0})}),t}},log_in:{value:function(e,t){return void 0==e&&void 0==t&&(e=$p.job_prm.guest_name,t=$p.aes.Ctr.decrypt($p.job_prm.guest_pwd)),n?n.username==e?Promise.resolve():Promise.reject():$p.ajax.get_ex(s.path+s.zone+"_ram",{username:e,password:t}).then(function(a){return n={username:e,password:t},setTimeout(function(){dhx4.callEvent("log_in",[e])}),{ram:i.run_sync(i.local.ram,i.remote.ram,"ram"),doc:i.run_sync(i.local.doc,i.remote.doc,"doc")}})}},log_out:{value:function(){if(n){if(e.sync.doc)try{e.sync.doc.cancel()}catch(e){}if(e.sync.ram)try{e.sync.ram.cancel()}catch(e){}n=null}t&&t.ram&&delete t.ram,t&&t.doc&&delete t.doc,t=null,dhx4.callEvent("log_out")}},reset_local_data:{value:function(){var e=i.local.ram.destroy.bind(i.local.ram),t=i.local.doc.destroy.bind(i.local.doc),n=function(){setTimeout(function(){$p.eve.redirect=!0,location.reload(!0)},1e3)};i.log_out(),setTimeout(function(){e().then(t).catch(t).then(n).catch(n)},1e3)}},load_data:{value:function(){var e={limit:800,include_docs:!0},t={total_rows:0,limit:e.limit,page:0,start:Date.now()};return new Promise(function(n,s){function o(){i.local.ram.allDocs(e,function(r,l){l?(t.page++,t.total_rows=l.total_rows,t.duration=Date.now()-t.start,$p.eve.callEvent("pouch_load_data_page",[t]),i.load_changes(l,e)?o():(n(),a=!0,$p.eve.callEvent("pouch_load_data_loaded",[t]),t.note="pouch_load_data_loaded",$p.record_log(t))):r&&(s(r),$p.eve.callEvent("pouch_load_data_error",[r]))})}i.local.ram.info().then(function(e){e.doc_count>=($p.job_prm.pouch_ram_doc_count||10)?($p.eve.callEvent("pouch_load_data_start",[t]),o()):($p.eve.callEvent("pouch_load_data_error",[e]),s(e))})})}},authorized:{get:function(){return n&&n.username}},data_loaded:{get:function(){return!!a}},run_sync:{value:function(t,n,s){var o,r;return t.info().then(function(e){return o=e,n.info()}).then(function(e){return"ram"!=s?e:n.get("data_version").then(function(t){return t.version!=$p.wsql.get_user_param("couch_ram_data_version")&&($p.wsql.get_user_param("couch_ram_data_version")&&(e=i.reset_local_data()),$p.wsql.set_user_param("couch_ram_data_version",t.version)),e}).catch(function(e){$p.record_log(e)}).then(function(){return e})}).then(function(l){if(l){"ram"==s&&o.doc_count<($p.job_prm.pouch_ram_doc_count||10)?(r={total_rows:l.doc_count,local_rows:o.doc_count,docs_written:0,limit:200,page:0,start:Date.now()},$p.eve.callEvent("pouch_load_data_start",[r])):"doc"==s&&setTimeout(function(){$p.eve.callEvent("pouch_doc_sync_start")});var c={live:!0,retry:!0,batch_size:300,batches_limit:8};return"meta"==s?c.filter="auth/meta":$p.job_prm.pouch_filter&&$p.job_prm.pouch_filter[s]&&(c.filter=$p.job_prm.pouch_filter[s]),"ram"==s||"meta"==s||$p.wsql.get_user_param("zone")==$p.job_prm.zone_demo?e.sync[s]=t.replicate.from(n,c):e.sync[s]=t.sync(n,c),e.sync[s].on("change",function(e){"ram"==s?(i.load_changes(e),o.doc_count<($p.job_prm.pouch_ram_doc_count||10)&&(r.page++,r.docs_written=e.docs_written,r.duration=Date.now()-r.start,$p.eve.callEvent("pouch_load_data_page",[r]),r.docs_written>=r.total_rows&&(a=!0,$p.eve.callEvent("pouch_load_data_loaded",[r]),r.note="pouch_load_data_loaded",$p.record_log(r)))):(e.update_only=!0,i.load_changes(e)),$p.eve.callEvent("pouch_change",[s,e])}).on("paused",function(e){e&&$p.eve.callEvent("pouch_paused",[s,e])}).on("active",function(e){$p.eve.callEvent("pouch_active",[s,e])}).on("denied",function(e){$p.eve.callEvent("pouch_denied",[s,e])}).on("complete",function(e){$p.eve.callEvent("pouch_complete",[s,e])}).on("error",function(e){$p.eve.callEvent("pouch_error",[s,e])}),e.sync[s]}})}},load_obj:{value:function(e){return e._manager.pouch_db.get(e._manager.class_name+"|"+e.ref).then(function(t){delete t._id,delete t._rev,e._mixin(t)._set_loaded()}).catch(function(e){if(404!=e.status)throw e}).then(function(t){return e})}},save_obj:{value:function(e,t){var n=e._obj._clone(),a=t.db||e._manager.pouch_db;return n._id=e._manager.class_name+"|"+e.ref,delete n.ref,t.attachments&&(n._attachments=t.attachments),(e.is_new()?Promise.resolve():a.get(n._id)).then(function(e){if(e){n._rev=e._rev;for(var t in e._attachments)n._attachments||(n._attachments={}),n._attachments[t]||(n._attachments[t]=e._attachments[t])}}).catch(function(e){if(404!=e.status)throw e}).then(function(){return a.put(n)}).then(function(){if(e.is_new()&&e._set_loaded(e.ref),n._attachments){e._attachments||(e._attachments={});for(var a in n._attachments)e._attachments[a]&&n._attachments[a].stub||(e._attachments[a]=n._attachments[a])}return n=null,t=null,e})}},load_changes:{value:function(e,t){var n,a,i,s,o={};if(t)n=e.rows;else if(e.direction){if("pull"!=e.direction)return;n=e.change.docs}else n=e.docs;if(n.length>0){t&&(t.startkey=n[n.length-1].key,t.skip=1),n.forEach(function(e){if(a=t?e.doc:e,!a)if(e.value&&e.value.deleted)a={_id:e.id,_deleted:!0};else if(e.error)return;s=a._id.split("|"),i=s[0].split("."),a.ref=s[1],delete a._id,delete a._rev,o[i[0]]||(o[i[0]]={}),o[i[0]][i[1]]||(o[i[0]][i[1]]=[]),o[i[0]][i[1]].push(a)});for(var r in o)for(i in o[r])$p[r]&&$p[r][i]&&$p[r][i].load_array(o[r][i],!e.update_only||"update_only");return o=e=n=a=null,!0}return!1}},backup_database:{value:function(e){}},restore_database:{value:function(e){}}})}function Messages(){this.toString=function(){return"Интернационализация сообщений"},"undefined"!=typeof window&&"dhtmlx"in window&&(this.show_msg=function(e,t){if(e){if("string"==typeof e){if($p.iface.synctxt)return void $p.iface.synctxt.show_message(e);e={type:"info",text:e}}t&&"function"==typeof t.setText&&t.setText(e.text),dhtmlx.message(e)}},this.check_soap_result=function(e){return e?"limit_query"==e.error?($p.iface.docs.progressOff(),$p.msg.show_msg({type:"alert-warning",text:$p.msg.limit_query.replace("%1",e.queries).replace("%2",e.queries_avalable),title:$p.msg.srv_overload}),!0):"network"==e.error||"empty"==e.error?($p.iface.docs.progressOff(),$p.msg.show_msg({type:"alert-warning",text:$p.msg.error_network,title:$p.msg.error_critical}),!0):e.error&&e.error_description?($p.iface.docs.progressOff(),e.error_description.indexOf("Недостаточно прав")!=-1&&(e.error_type="alert-warning",e.error_title=$p.msg.error_rights),$p.msg.show_msg({type:e.error_type||"alert-error",text:e.error_description,title:e.error_title||$p.msg.error_critical}),!0):e.error&&!e.messages?($p.iface.docs.progressOff(),$p.msg.show_msg({type:"alert-error",title:$p.msg.error_critical,text:$p.msg.unknown_error.replace("%1","unknown_error")}),!0):void 0:($p.msg.show_msg({type:"alert-error",text:$p.msg.empty_response,title:$p.msg.error_critical}),!0)},this.show_not_implemented=function(){$p.msg.show_msg({type:"alert-warning",text:$p.msg.not_implemented,title:$p.msg.main_title})})}function Meta(){function e(e){return e.info().then(function(){return e.get("meta")}).then(function(n){return t=n,n=null,e.get("meta_patch")}).then(function(e){return $p._patch(t,e),e=null,delete t._id,delete t._rev,t})}var t;_md=this,_md.create_managers=function(){},_md.init=function(n){function a(){return!n||i||s?e(n||$p.wsql.pouch.local.meta).then(function(){return i?void _md.create_managers():t}).catch($p.record_log):(t=n,n=null,_md.create_managers(),void 0)}var i=!n||$p.wsql.pouch&&n==$p.wsql.pouch.local.meta,s=n&&$p.wsql.pouch&&n==$p.wsql.pouch.local._meta;return $p.on("pouch_change",function(e,n){"meta"==e&&(t?setTimeout(function(){$p.iface.do_reload()},3e3):a())}),a()},_md.get=function(e,n){var a=e.split(".");if(!n)return t[a[0]][a[1]];var i={multiline_mode:!1,note:"",synonym:"",tooltip:"",type:{is_ref:!1,types:["string"]}},s="doc,tsk,bp".indexOf(a[0])!=-1,o="cat,cch,cacc,tsk".indexOf(a[0])!=-1;return s&&"number_doc"==n?(i.synonym="Номер",i.tooltip="Номер документа",i.type.str_len=11):s&&"date"==n?(i.synonym="Дата",i.tooltip="Дата документа",i.type.date_part="date_time",i.type.types[0]="date"):s&&"posted"==n?(i.synonym="Проведен",i.type.types[0]="boolean"):o&&"id"==n?i.synonym="Код":o&&"name"==n?i.synonym="Наименование":"_deleted"==n?(i.synonym="Пометка удаления",i.type.types[0]="boolean"):"is_folder"==n?(i.synonym="Это группа",i.type.types[0]="boolean"):"ref"==n?(i.synonym="Ссылка",i.type.is_ref=!0,i.type.types[0]=e):i=n?t[a[0]][a[1]].fields[n]:t[a[0]][a[1]],i},_md.get_classes=function(){ -var e={};for(var n in t){e[n]=[];for(var a in t[n])e[n].push(a)}return e},_md.sql_type=function(e,t,n,a){var i;return i="type"==t&&"cch_properties"==e.table_name||"svg"==t&&"cat_production_params"==e.table_name?" JSON":n.is_ref||n.types.indexOf("guid")!=-1?a?n.types.every(function(e){return 0==e.indexOf("enm.")})?" character varying(100)":n.hasOwnProperty("str_len")?" character varying("+Math.max(36,n.str_len)+")":" uuid":" CHAR":n.hasOwnProperty("str_len")?a?n.str_len?" character varying("+n.str_len+")":" text":" CHAR":n.date_part?a&&"date"!=n.date_part?"date_time"==n.date_part?" timestamp with time zone":" time without time zone":" Date":n.hasOwnProperty("digits")?0==n.fraction_figits?a?n.digits<7?" integer":" bigint":" INT":a?" numeric("+n.digits+","+n.fraction_figits+")":" FLOAT":n.types.indexOf("boolean")!=-1?" BOOLEAN":n.types.indexOf("json")!=-1?" JSON":a?" character varying(255)":" CHAR"},_md.sql_composite=function(e,t,n,a){var i="";return e[t].type.types.length>1&&"type"!=t&&(n=n?n.substr(0,29)+"_T":t.substr(0,29)+"_T",i=a?', "'+n+'" character varying(255)':_md.sql_mask(n)+" CHAR"),i},_md.sql_mask=function(e,t){return", "+(t?"_t_.":"")+("`"+e+"`")},_md.mgr_by_class_name=function(e){if(e){var t=e.split(".");if(t[1]&&$p[t[0]])return $p[t[0]][t[1]]}},_md.value_mgr=function(e,t,n,a,i){function s(e){return e&&1==n.types.length&&(n._mgr=e),e}var o,r,l,c,p;if(n._mgr)return n._mgr;if(1==n.types.length){if(l=n.types[0].split("."),l.length>1&&$p[l[0]])return s($p[l[0]][l[1]])}else if(i&&i.type&&(l=i.type.split("."),l.length>1&&$p[l[0]]))return s($p[l[0]][l[1]]);if(o=e.property||e.param,"value"==t&&o){if($p.utils.is_data_obj(o))r=o;else{if(!$p.utils.is_guid(o))return;r=$p.cch.properties.get(o,!1)}if($p.utils.is_data_obj(r)){if(r.is_new())return $p.cat.property_values;if(c=[],r.type.types.forEach(function(e){l=e.split("."),l.length>1&&$p[l[0]][l[1]]&&c.push($p[l[0]][l[1]])}),1==c.length||e[t]==$p.utils.blank.guid)return s(c[0]);if(a)return c;if((o=e[t])instanceof DataObj)return o._manager;if($p.utils.is_guid(o)&&o!=$p.utils.blank.guid)for(var d in c)if(p=c[d],p.get(o,!1,!0))return p}}else{if(c=[],n.types.forEach(function(e){l=e.split("."),l.length>1&&$p[l[0]][l[1]]&&c.push($p[l[0]][l[1]])}),1==c.length||e[t]==$p.utils.blank.guid)return s(c[0]);if(a)return c;if((o=e[t])instanceof DataObj)return o._manager;if($p.utils.is_guid(o)&&o!=$p.utils.blank.guid)for(var d in c)if(p=c[d],p.get(o,!1,!0))return p}},_md.control_by_type=function(e,t){var n;return n="boolean"==typeof t&&e.types.indexOf("boolean")!=-1?"ch":"number"==typeof t&&e.digits?e.fraction_figits<5?"calck":"edn":t instanceof Date&&e.date_part?"dhxCalendar":e.is_ref?"ocombo":e.date_part?"dhxCalendar":e.digits?e.fraction_figits<5?"calck":"edn":"boolean"==e.types[0]?"ch":e.hasOwnProperty("str_len")&&(e.str_len>=100||0==e.str_len)?"txt":"ed"},_md.ts_captions=function(e,t,n){n||(n={});var a,i=_md.get(e).tabular_sections[t],s=_md.get(e).form,o=i.fields;if(s&&s.obj){if(!s.obj.tabular_sections[t])return;n._mixin(s.obj.tabular_sections[t])}else{"contact_information"===t&&(o={type:"",kind:"",presentation:""}),n.fields=["row"],n.headers="№",n.widths="40",n.min_widths="",n.aligns="",n.sortings="na",n.types="cntr";for(var r in o)a=i.fields[r],a.hide||(n.fields.push(r),n.headers+=","+(a.synonym?a.synonym.replace(/,/g," "):r),n.types+=","+_md.control_by_type(a.type),n.sortings+=",na")}return!0},_md.syns_js=function(e){var n={DeletionMark:"_deleted",Description:"name",DataVersion:"data_version",IsFolder:"is_folder",Number:"number_doc",Date:"date","Дата":"date",Posted:"posted",Code:"id",Parent_Key:"parent",Owner_Key:"owner",Owner:"owner",Ref_Key:"ref","Ссылка":"ref",LineNumber:"row"};return n[e]?n[e]:t.syns_js[t.syns_1с.indexOf(e)]||e},_md.syns_1с=function(e){var n={_deleted:"DeletionMark",name:"Description",is_folder:"IsFolder",number_doc:"Number",date:"Date",posted:"Posted",id:"Code",ref:"Ref_Key",parent:"Parent_Key",owner:"Owner_Key",row:"LineNumber"};return n[e]?n[e]:t.syns_1с[t.syns_js.indexOf(e)]||e},_md.printing_plates=function(e){if(e)for(var n in e.doc)t.doc[n].printing_plates=e.doc[n]},_md.class_name_from_1c=function(e){var t=e.split(".");return 1==t.length?"enm."+e:("Перечисление"==t[0]?e="enm.":"Справочник"==t[0]?e="cat.":"Документ"==t[0]?e="doc.":"РегистрСведений"==t[0]?e="ireg.":"РегистрНакопления"==t[0]?e="areg.":"РегистрБухгалтерии"==t[0]?e="accreg.":"ПланВидовХарактеристик"==t[0]?e="cch.":"ПланСчетов"==t[0]?e="cacc.":"Обработка"==t[0]?e="dp.":"Отчет"==t[0]&&(e="rep."),e+_md.syns_js(t[1]))},_md.class_name_to_1c=function(e){var t=e.split(".");return 1==t.length?"Перечисление."+e:("enm"==t[0]?e="Перечисление.":"cat"==t[0]?e="Справочник.":"doc"==t[0]?e="Документ.":"ireg"==t[0]?e="РегистрСведений.":"areg"==t[0]?e="РегистрНакопления.":"accreg"==t[0]?e="РегистрБухгалтерии.":"cch"==t[0]?e="ПланВидовХарактеристик.":"cacc"==t[0]?e="ПланСчетов.":"dp"==t[0]?e="Обработка.":"rep"==t[0]&&(e="Отчет."),e+_md.syns_1с(t[1]))},_md.create_tables=function(e,t){function n(){s--,0==s?e?e(l):alasql.utils.saveFile("create_tables.sql",l):a()}function a(){var e=o[s-1];l+=e.class[e.name].get_sql_struct(t)+"; ",n()}var i,s=0,o=[],r=_md.get_classes(),l=t&&t.postgres?"":"USE md; ";"enm,cch,cacc,cat,bp,tsk,doc,ireg,areg".split(",").forEach(function(e){for(i in r[e])o.push({class:$p[e],name:r[e][i]})}),s=o.length,a()}}function DataManager(e){var t=_md.get(e),n={after_create:[],after_load:[],before_save:[],after_save:[],value_change:[],add_row:[],del_row:[]};this.__define({cachable:{get:function(){return e.indexOf("enm.")!=-1?"ram":t.cachable?t.cachable:e.indexOf("doc.")!=-1||e.indexOf("dp.")!=-1||e.indexOf("rep.")!=-1?"doc":"ram"}},class_name:{value:e,writable:!1},alatable:{get:function(){return $p.wsql.aladb.tables[this.table_name]?$p.wsql.aladb.tables[this.table_name].data:[]}},metadata:{value:function(e){return e?t.fields[e]||t.tabular_sections[e]:t}},on:{value:function(e,t){if("object"==typeof e)for(var a in e)e.hasOwnProperty(a)&&n[a].push(e[a]);else n[e].push(t)}},off:{value:function(e,t){}},handle_event:{value:function(e,t,a){var i,s=[];return n[t].forEach(function(t){s!==!1&&(i=t.call(e,a),i===!1?s=i:i&&s.push(i))}),s===!1?s:s.length?1==s.length?s[0]:s.some(function(e){return"object"==typeof e&&e.then})?Promise.all(s):s:void 0}},by_ref:{value:{}}})}function RefDataManager(e){RefDataManager.superclass.constructor.call(this,e)}function DataProcessorsManager(e){DataProcessorsManager.superclass.constructor.call(this,e)}function EnumManager(e){EnumManager.superclass.constructor.call(this,e);var t=$p.md.get(e);for(var n in t)new EnumObj(t[n],this)}function RegisterManager(e){RegisterManager.superclass.constructor.call(this,e),this.push=function(e,t){t&&t!=e.ref?(delete this.by_ref[e.ref],this.by_ref[t]=e):this.by_ref[e.ref]=e},this.get=function(e,t,n){if(e?"string"==typeof e&&(e={ref:e}):e={},e.ref&&n)return t?Promise.resolve(this.by_ref[e.ref]):this.by_ref[e.ref];e.action="select";var a,i=$p.wsql.alasql(this.get_sql_struct(e),e._values);if(delete e.action,delete e._values,i.length)if(n)a=this.by_ref[this.get_ref(i[0])];else{a=[];for(var s in i)a.push(this.by_ref[this.get_ref(i[s])])}return t?Promise.resolve(a):a},this.unload_obj=function(e){delete this.by_ref[e],this.alatable.some(function(t,n,a){if(t.ref==e)return a.splice(n,1),!0})},this.load_array=function(e,t){for(var n,a,i=[],s=0;s<e.length;s++){if(n=this.get_ref(e[s]),a=this.by_ref[n],a||e[s]._deleted){if(a&&e[s]._deleted){a.unload();continue}(a.is_new()||t)&&(a._mixin(e[s]),a._set_loaded())}else a=new($p[this.obj_constructor()])(e[s],this),t&&a._set_loaded();i.push(a)}return i}}function InfoRegManager(e){InfoRegManager.superclass.constructor.call(this,e)}function LogManager(){LogManager.superclass.constructor.call(this,"ireg.$log");var e;this.__define({record:{value:function(t){t instanceof Error?(console&&console.log(t),t={class:"error",note:t.toString()}):"object"!=typeof t||t.class||t.obj?"object"!=typeof t&&(t={note:t}):t={class:"obj",obj:t,note:t.note},t.date=Date.now()+$p.wsql.time_diff,e||(e=alasql.compile("select MAX(`sequence`) as `sequence` from `ireg_$log` where `date` = ?"));var n=e([t.date]);n.length&&void 0!==n[0].sequence?t.sequence=parseInt(n[0].sequence)+1:t.sequence=0,t.class||(t.class="note"),$p.wsql.alasql("insert into `ireg_$log` (`ref`, `date`, `sequence`, `class`, `note`, `obj`) values (?,?,?,?,?,?)",[t.date+"¶"+t.sequence,t.date,t.sequence,t.class,t.note,t.obj?JSON.stringify(t.obj):""])}},backup:{value:function(e,t){}},restore:{value:function(e,t){}},clear:{value:function(e,t){}},show:{value:function(e){}},get:{value:function(e,t,n){if("object"==typeof e&&(e=e.ref||""),!this.by_ref[e]){if(t===!1)return;var a=e.split("¶");$p.wsql.alasql("select * from `ireg_$log` where date="+a[0]+" and sequence="+a[1]).forEach(function(e){new RegisterRow(e,this)}.bind(this))}return t?Promise.resolve(this.by_ref[e]):this.by_ref[e]}},get_sql_struct:{value:function(e){if(e&&"get_selection"==e.action){var t="select * from `ireg_$log`";return e.date_from?t+=e.date_till?" where `date` >= ? and `date` <= ?":" where `date` >= ?":e.date_till&&(t+=" where `date` <= ?"),t}return LogManager.superclass.get_sql_struct.call(this,e)}},caption_flds:{value:function(e){var t='<column id="%1" width="%2" type="%3" align="%4" sort="%5">%6</column>',n=[],a="";if(n.push(new Col_struct("date","200","ro","left","server","Дата")),n.push(new Col_struct("class","100","ro","left","server","Класс")),n.push(new Col_struct("note","*","ro","left","server","Событие")),e.get_header){a="<head>";for(var i in n)a+=t.replace("%1",n[i].id).replace("%2",n[i].width).replace("%3",n[i].type).replace("%4",n[i].align).replace("%5",n[i].sort).replace("%6",n[i].caption);a+="</head>"}return{head:a,acols:n}}},data_to_grid:{value:function(e,t){var n="<?xml version='1.0' encoding='UTF-8'?><rows total_count='%1' pos='%2' set_parent='%3'>".replace("%1",e.length).replace("%2",t.start).replace("%3",t.set_parent||""),a=this.caption_flds(t);return n+=a.head,e.forEach(function(e){n+='<row id="'+e.ref+'"><cell>'+$p.moment(e.date-$p.wsql.time_diff).format("DD.MM.YYYY HH:mm:ss")+"."+e.sequence+"</cell><cell>"+(e.class||"")+"</cell><cell>"+(e.note||"")+"</cell></row>"}),n+"</rows>"}}})}function AccumRegManager(e){AccumRegManager.superclass.constructor.call(this,e)}function CatManager(e){CatManager.superclass.constructor.call(this,e),this.metadata().hierarchical&&this.metadata().group_hierarchy&&$p[this.obj_constructor()].prototype.__define("is_folder",{get:function(){return this._obj.is_folder||!1},set:function(e){this._obj.is_folder=$p.utils.fix_boolean(e)},enumerable:!0,configurable:!0})}function ChartOfCharacteristicManager(e){ChartOfCharacteristicManager.superclass.constructor.call(this,e)}function ChartOfAccountManager(e){ChartOfAccountManager.superclass.constructor.call(this,e)}function DocManager(e){DocManager.superclass.constructor.call(this,e)}function TaskManager(e){TaskManager.superclass.constructor.call(this,e)}function BusinessProcessManager(e){BusinessProcessManager.superclass.constructor.call(this,e)}function DataObj(e,t){var n,a={},i={},s={_is_new:!(this instanceof EnumObj)};return t instanceof DataProcessorsManager||t instanceof EnumManager||(n=t.get(e,!1,!0)),n?(e=null,n):(t instanceof EnumManager?i.ref=e.name:t instanceof RegisterManager?i.ref=t.get_ref(e):i.ref=$p.utils.fix_guid(e),this.__define({_obj:{value:i,configurable:!0},_ts_:{value:function(e){return a[e]||(a[e]=new TabularSection(e,this)),a[e]},configurable:!0},_manager:{value:t},_data:{value:s,configurable:!0}}),t.alatable&&t.push&&(t.alatable.push(i),t.push(this,i.ref)),void(e=null))}function CatObj(e,t){var n="";CatObj.superclass.constructor.call(this,e,t),this.__define("presentation",{get:function(){return this.name||this.id?this.name||this.id||this._metadata.obj_presentation||this._metadata.synonym:n},set:function(e){e&&(n=String(e))}}),e&&"object"==typeof e&&(e._not_set_loaded?(delete e._not_set_loaded,this._mixin(e)):(this._mixin(e),$p.utils.is_empty_guid(this.ref)||!e.id&&!e.name||this._set_loaded(this.ref))),e=null}function DocObj(e,t){var n="";DocObj.superclass.constructor.call(this,e,t),this.__define("presentation",{get:function(){return this.number_doc?(this._metadata.obj_presentation||this._metadata.synonym)+" №"+this.number_doc+" от "+$p.moment(this.date).format($p.moment._masks.ldt):n},set:function(e){e&&(n=String(e))}}),e&&"object"==typeof e&&this._mixin(e),!$p.utils.is_empty_guid(this.ref)&&e.number_doc&&this._set_loaded(this.ref),e=null}function doc_props_date_number(e){e.__define({number_doc:{get:function(){return this._obj.number_doc||""},set:function(e){this.__notify("number_doc"),this._obj.number_doc=e},enumerable:!0},date:{get:function(){return this._obj.date||$p.utils.blank.date},set:function(e){this.__notify("date"),this._obj.date=$p.utils.fix_date(e,!0)},enumerable:!0}})}function DataProcessorObj(e,t){DataProcessorObj.superclass.constructor.call(this,e,t);var n,a=t.metadata();for(n in a.fields)e[n]=$p.utils.fetch_type("",a.fields[n].type);for(n in a.tabular_sections)e[n]=[];this._mixin(e)}function TaskObj(e,t){TaskObj.superclass.constructor.call(this,e,t)}function BusinessProcessObj(e,t){BusinessProcessObj.superclass.constructor.call(this,e,t)}function EnumObj(e,t){EnumObj.superclass.constructor.call(this,e,t),e&&"object"==typeof e&&this._mixin(e)}function RegisterRow(e,t){RegisterRow.superclass.constructor.call(this,e,t),e&&"object"==typeof e&&this._mixin(e);for(var n in t.metadata().dimensions)if(!e.hasOwnProperty(n)&&e.ref){var a=e.ref.split("¶");Object.keys(t.metadata().dimensions).forEach(function(e,t){this[e]=a[t]}.bind(this));break}}function TabularSection(e,t){t._obj[e]||(t._obj[e]=[]),this.__define("_name",{value:e,enumerable:!1}),this.__define("_owner",{value:t,enumerable:!1}),this.__define("_obj",{value:t._obj[e],writable:!1,enumerable:!1})}function TabularSectionRow(e){var t={};this.__define("_owner",{value:e,enumerable:!1}),this.__define("_obj",{value:t,writable:!1,enumerable:!1})}function Rest(){this.filter_date=function(e,t,n){t||(t=new Date("2015-01-01"));var a=e+" gt datetime'"+$p.moment(t).format($p.moment._masks.iso)+"'";return n&&(a+=" and "+e+" lt datetime'"+$p.moment(n).format($p.moment._masks.iso)+"'"),a},this.to_data=function(e,t){var n,a,i,s,o,r,l={},c=t.metadata(),p=c.fields,d=c.tabular_sections;t instanceof RefDataManager?(e.hasOwnProperty("DeletionMark")&&(l._deleted=e.DeletionMark),e.hasOwnProperty("DataVersion"),e.hasOwnProperty("Ref_Key")&&(l.ref=e.Ref_Key)):p={}._mixin(c.dimensions)._mixin(c.resources)._mixin(c.attributes),t instanceof DocManager?(e.hasOwnProperty("Number")?l.number_doc=e.Number||e.number_doc:e.hasOwnProperty("number_doc")&&(l.number_doc=e.number_doc),e.hasOwnProperty("Date")?l.date=e.Date:e.hasOwnProperty("date")&&(l.date=e.date),e.hasOwnProperty("Posted")?l.posted=e.Posted:e.hasOwnProperty("posted")&&(l.posted=e.posted)):(c.main_presentation_name&&(e.hasOwnProperty("Description")?l.name=e.Description:e.hasOwnProperty("name")&&(l.name=e.name)),c.code_length&&(e.hasOwnProperty("Code")?l.id=e.Code:e.hasOwnProperty("id")&&(l.id=e.id)));for(a in p)if(e.hasOwnProperty(a))l[a]=e[a];else{if(o=_md.syns_1с(a),o.indexOf("_Key")==-1&&p[a].type.is_ref&&e[o+"_Key"]&&(o+="_Key"),!e.hasOwnProperty(o))continue;l[a]=e[o]}for(n in d)r="extra_fields"==n||e.hasOwnProperty(n)?n:_md.syns_1с(n),e.hasOwnProperty(r)&&(l[n]=[],e[r]&&(e[r].sort(function(e,t){return(e.LineNumber||e.row)>(t.LineNumber||t.row)}),e[r].forEach(function(e){s={};for(i in d[n].fields)o=e.hasOwnProperty(i)||"extra_fields"==n&&("property"==i||"value"==i)?i:_md.syns_1с(i),o.indexOf("_Key")==-1&&d[n].fields[i].type.is_ref&&e[o+"_Key"]&&(o+="_Key"),s[i]=e[o];l[n].push(s)})));return l},this.ajax_to_data=function(e,t){return $p.ajax.get_ex(e.url,e).then(function(e){return JSON.parse(e.response)}).then(function(e){var n=[];return e.value.forEach(function(e){n.push(_rest.to_data(e,t))}),n})},this.build_select=function(e,t){function n(e,a){"function"==typeof a?s+=a(t,e):(o=_md.syns_1с(e),r=_md.get(t.class_name,e),r&&(r=r.type,r.is_ref&&o.indexOf("_Key")==-1&&r.types.length&&r.types[0].indexOf("enm.")==-1&&(o+="_Key"),r.types.length&&(["boolean","number"].indexOf(typeof a)!=-1?s+=o+" eq "+a:r.is_ref&&"object"!=typeof a||a instanceof DataObj?s+=o+" eq guid'"+a+"'":"string"==typeof a?s+=o+" eq '"+a+"'":"object"==typeof a&&(a.hasOwnProperty("like")?s+=o+" like '%"+a.like+"%'":a.hasOwnProperty("not")?s+=" not ("+n(e,a.not)+") ":a.hasOwnProperty("in")&&(s+=o+" in ("+(r.is_ref?a.in.map(function(e){return"guid'"+e+"'"}).join(","):a.in.join(","))+") ")))))}function a(e){for(var t in e)if(s?s+=" and ":s="&$filter=","or"==t&&Array.isArray(e[t])){var a=!0;e[t].forEach(function(e){a?(s+=" ( ",a=!1):s+=" or ";var t=Object.keys(e)[0];n(t,e[t])}),s+=" ) "}else n(t,e[t])}var i,s,o,r,l="";e||(e={}),e.fields&&(e.fields.forEach(function(e){"ref"==e?o="Ref_Key":(o=_md.syns_1с(e),r=_md.get(t.class_name,e).type,r.is_ref&&o.indexOf("_Key")==-1&&r.types.length&&r.types[0].indexOf("enm.")==-1&&(o+="_Key")),i?i+=",":i="&$select=",i+=o}),l+=i),e.selection&&("function"==typeof e.selection||(Array.isArray(e.selection)?e.selection.forEach(a):a(e.selection)),s&&(l+=s)),$p.job_prm.rest&&t.rest_name.indexOf("Module_")==-1&&t.rest_name.indexOf("DataProcessor_")==-1&&t.rest_name.indexOf("Report_")==-1&&l.indexOf(" like ")==-1&&l.indexOf(" in ")==-1&&!t.metadata().irest?$p.ajax.default_attr(e,$p.job_prm.rest_url()):$p.ajax.default_attr(e,$p.job_prm.irest_url()),e.url+=t.rest_name+"?allowedOnly=true&$format=json&$top="+(e.top||300)+l},this.load_array=function(e,t){return _rest.build_select(e,t),_rest.ajax_to_data(e,t)},this.load_obj=function(e){var t={};return $p.ajax.default_attr(t,!e._metadata.irest&&$p.job_prm.rest?$p.job_prm.rest_url():$p.job_prm.irest_url()),t.url+=e._manager.rest_name+"(guid'"+e.ref+"')?$format=json",$p.ajax.get_ex(t.url,t).then(function(e){return JSON.parse(e.response)}).then(function(t){return e._mixin(_rest.to_data(t,e._manager))._set_loaded(),e}).catch(function(t){return 404==t.status?e:void $p.record_log(t)})},this.save_irest=function(e,t){var n=JSON.stringify(e),a=(void 0!=t.post?",post="+t.post:"")+(void 0!=t.operational?",operational="+t.operational:"");return $p.ajax.default_attr(t,$p.job_prm.irest_url()),t.url+=e._manager.rest_name+"(guid'"+e.ref+"'"+a+")",$p.ajax.post_ex(t.url,n,t).then(function(e){return JSON.parse(e.response)}).then(function(t){return e._mixin(t)})},this.save_rest=function(e,t){var n,a=e.to_atom();return $p.ajax.default_attr(t,$p.job_prm.rest_url()),n=t.url+e._manager.rest_name,t.url=n+"(guid'"+e.ref+"')?$format=json&$select=Ref_Key,DeletionMark",$p.ajax.get_ex(t.url,t).catch(function(e){return 404==e.status?{response:JSON.stringify({is_new:!0})}:Promise.reject(e)}).then(function(e){return JSON.parse(e.response)}).then(function(i){return i.is_new?$p.ajax.post_ex(n,a,t):$p.ajax.patch_ex(n+"(guid'"+e.ref+"')",a,t)}).then(function(t){var n=xmlToJSON.parseString(t.response,{mergeCDATA:!1,grokAttr:!0,grokText:!1,normalize:!0,xmlns:!1,namespaceKey:"_ns",textKey:"_text",valueKey:"_value",attrKey:"_attr",cdataKey:"_cdata",attrsAsObject:!1,stripAttrPrefix:!0,stripElemPrefix:!0,childrenAsArray:!1});if(n.entry&&n.entry.content&&n.entry.updated){var a,i=n.entry.content.properties,s={};for(var o in i)if(0!=o.indexOf("_"))if(a=i[o].element)if(s[o]=[],Array.isArray(a))for(var r in a){s[o][r]={};for(var l in a[r])0!=l.indexOf("_")&&(s[o][r][l]="false"!==a[r][l]._text&&a[r][l]._text)}else{s[o][0]={};for(var l in a)0!=l.indexOf("_")&&(s[o][0][l]="false"!==a[l]._text&&a[l]._text)}else s[o]="false"!==i[o]._text&&i[o]._text;return _rest.to_data(s,e._manager)}}).then(function(t){return e._mixin(t)})}}function eXcell_ocombo(e){if(e){var t=this;t.cell=e,t.grid=e.parentNode.grid,t.setValue=function(e){t.setCValue(e instanceof DataObj?e.presentation:e||"")},t.getValue=function(){return t.grid.get_cell_value()},t.shiftNext=function(){t.grid.editStop()},t.edit=function(){t.combo||(t.val=t.getValue(),t.cell.innerHTML="",t.combo=new OCombo({parent:t.cell}._mixin(t.grid.get_cell_field())),t.combo.getInput().focus())},t.detach=function(){if(t.combo){if(t.combo.getComboText){t.setValue(t.combo.getComboText()),t.combo.getSelectedValue()||t.combo.callEvent("onChange");var e=!$p.utils.is_equal(t.val,t.getValue());return t.combo.unload(),e}t.combo.unload&&t.combo.unload()}return!0}}}function eXcell_pwd(e){var t;e&&(this.cell=e,this.grid=e.parentNode.grid,eXcell_ed.call(this),t=this.edit,this.edit=function(){t.call(this),this.obj.type="password"},this.setValue=function(){this.setCValue("*********")},this.getValue=function(){return this.grid.get_cell_value()},this.detach=function(){if(this.grid.get_cell_field){var e=this.grid.get_cell_field();e.obj[e.field]=this.obj.value}return this.setValue(),t=null,this.val!=this.getValue()})}function ODropdownList(e){function t(t){s.innerHTML=e.values[s.getAttribute("current")],e.event_name&&!t&&dhx4.callEvent(e.event_name,[s.getAttribute("current")])}function n(){i.classList.remove("open")}var a,i,s,o=document.createElement("ul");e.container.innerHTML='<div class="dropdown_list">'+e.title+'<a href="#" class="dropdown_list"></a></div>',i=e.container.firstChild,s=i.querySelector("a"),s.setAttribute("current",Array.isArray(e.values)?"0":Object.keys(e.values)[0]),i.onclick=function(e){if(i.classList.contains("open")){if("LI"==e.target.tagName)for(var a in o.childNodes)if(o.childNodes[a]==e.target){s.setAttribute("current",e.target.getAttribute("current")),t();break}n()}else i.classList.add("open");return $p.iface.cancel_bubble(e)},i.appendChild(o),o.className="dropdown_menu",e.class_name&&(i.classList.add(e.class_name),o.classList.add(e.class_name));for(var r in e.values){a=document.createElement("li");var l=e.values[r].indexOf("<i");a.innerHTML=e.values[r].substr(l)+" "+e.values[r].substr(0,l),a.setAttribute("current",r),o.appendChild(a)}document.body.addEventListener("keydown",function(e){27==e.keyCode&&i.classList.remove("open")}),document.body.addEventListener("click",n),this.unload=function(){for(var t;t=i.lastChild;)i.removeChild(t);e.container.removeChild(i),a=o=i=s=e=null},t(!0)}function OCombo(e){function t(e){var t={_top:30};return f&&f.metadata().hierarchical&&f.metadata().group_hierarchy&&("elm"==u.choice_groups_elm?t.is_folder=!1:"grp"!=u.choice_groups_elm&&"parent"!=d||(t.is_folder=!0)),u.choice_links&&u.choice_links.forEach(function(e){e.name&&"selection"==e.name[0]&&(p instanceof TabularSectionRow?e.path.length<2?t[e.name[1]]="function"==typeof e.path[0]?e.path[0]:p._owner._owner[e.path[0]]:t[e.name[1]]=p[e.path[1]]:t[e.name[1]]="function"==typeof e.path[0]?e.path[0]:p[e.path[0]])}),u.choice_params&&u.choice_params.forEach(function(e){var n=Array.isArray(e.path)?{in:e.path}:e.path;t[e.name]?Array.isArray(t[e.name])?t[e.name].push(n):(t[e.name]=[t[e.name]],t[e.name].push(n)):t[e.name]=n}),u._option_list_local&&(t._local=!0),e&&(t.presentation={like:e}),t}function n(a){if("select"==this.name)f?f.form_selection(g,{initial_value:p[d].ref,selection:[t()]}):n.call({name:"type"});else if("add"==this.name)f&&f.create({},!0).then(function(t){t._set_loaded(t.ref),t.form_obj(e.pwnd)});else if("open"==this.name)p&&p[d]&&!p[d].empty()&&p[d].form_obj(e.pwnd);else if("type"==this.name){var i,s,o=[],r=p,l=d;u.type.types.forEach(function(e){i=_md.mgr_by_class_name(e),s=i.metadata(),o.push({presentation:s.synonym||s.name,mgr:i,selected:f===i})}),$p.iface.select_from_list(o).then(function(e){r[l]&&(r[l].empty&&r[l].empty()||r[l]._manager!=e.mgr)&&(f=e.mgr,p=r,d=l,u=p._metadata.fields[d],f.form_selection({on_select:function(e){p[d]=e,p=null,d=null,u=null}},{selection:[t()]})),f=null,i=null,s=null,r=null,l=null})}if(a)return $p.iface.cancel_bubble(a)}function a(){h=!1,setTimeout(function(){h||($p.iface.popup.p&&$p.iface.popup.p.onmouseover&&($p.iface.popup.p.onmouseover=null),$p.iface.popup.p&&$p.iface.popup.p.onmouseout&&($p.iface.popup.p.onmouseout=null),$p.iface.popup.clear(),$p.iface.popup.hide())},300)}function i(){if(!(f instanceof EnumManager)){h=!0;var t=document.createElement("div"),i=e.hide_frm?"":"<a href='#' name='select' title='Форма выбора {F4}'>Показать все</a><a href='#' name='open' style='margin-left: 9px;' title='Открыть форму элемента {Ctrl+Shift+F4}'><i class='fa fa-external-link fa-fw'></i></a>";if(!e.hide_frm){var s=$p.current_acl.get_acl(f.class_name);s.indexOf("i")!=-1&&(i+=" <a href='#' name='add' title='Создать новый элемент {F8}'><i class='fa fa-plus fa-fwfa-fw'></i></a>")}if(u.type.types.length>1&&(i+=" <a href='#' name='type' title='Выбрать тип значения {Alt+T}'><i class='fa fa-level-up fa-fw'></i></a>"),i){t.innerHTML=i;for(var o=0;o<t.children.length;o++)t.children[o].onclick=n;$p.iface.popup.clear(),$p.iface.popup.attachObject(t),$p.iface.popup.show(dhx4.absLeft(_.getButton())-77,dhx4.absTop(_.getButton()),_.getButton().offsetWidth,_.getButton().offsetHeight),$p.iface.popup.p.onmouseover=function(){h=!0},$p.iface.popup.p.onmouseout=a}}}function s(e){return setTimeout(i,10),e.preventDefault(),!1}function o(n){if(!(f instanceof EnumManager))return 115==n.keyCode?(n.ctrlKey&&n.shiftKey?p[d].empty()||p[d].form_obj(e.pwnd):n.ctrlKey||n.shiftKey||f&&f.form_selection(g,{initial_value:p[d].ref,selection:[t()]}),$p.iface.cancel_bubble(n)):void 0}function r(e){setTimeout(function(){_&&_.getInput&&_.getInput().select()},50)}function l(e){_&&_.getBase&&(_.getBase().parentElement?p instanceof TabularSectionRow||e.forEach(function(e){e.name==d&&c(p[d])}):setTimeout(_.unload))}function c(e){if(e&&e instanceof DataObj&&!e.empty()){if(_.getOption(e.ref)||_.addOption(e.ref,e.presentation),_.getSelectedValue()==e.ref)return;_.setComboValue(e.ref)}else _.getSelectedValue()||(_.setComboValue(""),_.setComboText(""))}var p,d,u,f,m,h,_=this,g={on_select:e.on_select||function(e){p[d]=e}};e.pwnd&&e.pwnd.setModal&&(g.setModal=e.pwnd.setModal.bind(e.pwnd)),OCombo.superclass.constructor.call(_,e),e.on_select?(_.getBase().style.border="none",_.getInput().style.left="-3px",e.is_tabular||(_.getButton().style.right="9px")):_.getBase().style.marginBottom="4px",e.left&&(_.getBase().style.left=left+"px"),this.attachEvent("onChange",function(){p&&d&&(p[d]=this.getSelectedValue())}),this.attachEvent("onBlur",function(){!this.getSelectedValue()&&this.getComboText()&&this.setComboText("")}),this.attachEvent("onDynXLS",function(n){f||(f=_md.value_mgr(p,d,u.type)),f&&(_.clearAll(),(e.get_option_list||f.get_option_list).call(f,null,t(n)).then(function(e){_.addOption&&(_.addOption(e),_.openSelect())}))}),_.getButton().addEventListener("mouseover",i),_.getButton().addEventListener("mouseout",a),_.getBase().addEventListener("click",$p.iface.cancel_bubble),_.getBase().addEventListener("contextmenu",s),_.getInput().addEventListener("keyup",o),_.getInput().addEventListener("focus",r),this.attach=function(e){p&&(p instanceof TabularSectionRow?Object.unobserve(p._owner._owner,l):Object.unobserve(p,l)),p=e.obj,d=e.field,m=e.property,e.metadata?u=e.metadata:m?(u=p._metadata.fields[d]._clone(),u.type=m.type):u=p._metadata.fields[d],_.clearAll(),f=_md.value_mgr(p,d,u.type),(f||e.get_option_list)&&(e.get_option_list||f.get_option_list).call(f,p[d],t()).then(function(e){_.addOption&&(_.addOption(e),c(p[d]))}),p instanceof TabularSectionRow?Object.observe(p._owner._owner,l,["row"]):Object.observe(p,l,["update"])};var b=this.unload;this.unload=function(){a(),_.getButton().removeEventListener("mouseover",i),_.getButton().removeEventListener("mouseout",a),_.getBase().removeEventListener("click",$p.iface.cancel_bubble),_.getBase().removeEventListener("contextmenu",s),_.getInput().removeEventListener("keyup",o),_.getInput().removeEventListener("focus",r),p&&(p instanceof TabularSectionRow?Object.unobserve(p._owner._owner,l):Object.unobserve(p,l)),_.conf&&_.conf.tm_confirm_blur&&clearTimeout(_.conf.tm_confirm_blur),p=null,d=null,u=null,f=null,g=null;try{b.call(_)}catch(e){}},e.obj&&e.field&&this.attach(e),this.enableFilteringMode("between","dummy",!1,!1),this.__define({value:{get:function(){if(p)return p[d]}}})}function ODateRangePicker(e,t){var n=this._cont=document.createElement("div");e instanceof dhtmlXCellObject?e.appendObject(this._cont):e.appendChild(this._cont),this._cont.className="odaterangepicker",this._cont.innerHTML='<i class="fa fa-calendar"></i>  <span></span>  <i class="fa fa-caret-down"></i>',this.__define({set_text:{value:function(){$("span",n).html(this.date_from.format("DD MMM YY")+" - "+this.date_till.format("DD MMM YY"))}},on:{value:function(e,t){return $(n).on(e,t)}},date_from:{get:function(){return $(n).data("daterangepicker").startDate},set:function(e){$(n).data("daterangepicker").setStartDate(e),this.set_text()}},date_till:{get:function(){return $(n).data("daterangepicker").endDate},set:function(e){$(n).data("daterangepicker").setEndDate(e),this.set_text()}}}),$(n).daterangepicker({startDate:t.date_from?moment(t.date_from):moment().subtract(29,"days"),endDate:moment(t.date_till),showDropdowns:!0,alwaysShowCalendars:!0,opens:"left",ranges:{"Сегодня":[moment(),moment()],"Вчера":[moment().subtract(1,"days"),moment().subtract(1,"days")],"Последние 7 дней":[moment().subtract(6,"days"),moment()],"Последние 30 дней":[moment().subtract(29,"days"),moment()],"Этот месяц":[moment().startOf("month"),moment().endOf("month")],"Прошлый месяц":[moment().subtract(1,"month").startOf("month"),moment().subtract(1,"month").endOf("month")]}},this.set_text.bind(this)),this.set_text()}function _clear_all(){$p.iface.docs.__define({clear_all:{value:function(){this.detachToolbar(),this.detachStatusBar(),this.detachObject(!0)},enumerable:!1},"Очистить":{get:function(){return this.clear_all},enumerable:!1},"Контейнер":{get:function(){return this.cell.querySelector(".dhx_cell_cont_layout")},enumerable:!1}})}function OTooolBar(e){function t(e){for(var t=0;t<c.children.length;t++)c.children[t].classList.remove("selected");e&&!this.classList.contains("selected")&&this.classList.add("selected")}function n(){s=!1,setTimeout(function(){s||$p.iface.popup.hide()},300)}function a(){e.onclick&&e.onclick.call(l,this.name.replace(e.name+"_",""),e.name)}var i,s,o,r,l=this,c=document.createElement("div");e.image_path||(e.image_path=dhtmlx.image_path),e.hasOwnProperty("class_name")?c.className=e.class_name:c.className="md_otooolbar",l.cell=c,l.buttons={},this.add=function(t){function p(e){if(e||(e=d),e.subdiv&&!o&&!r){for(;e.subdiv.firstChild;)e.subdiv.removeChild(e.subdiv.firstChild);e.subdiv.parentNode.removeChild(e.subdiv),e.subdiv=null}}var d=$p.iface.add_button(c,e,t);d.onclick=a,d.onmouseover=function(){t.title&&!t.sub&&(s=!0,$p.iface.popup.clear(),$p.iface.popup.attachHTML(t.title),$p.iface.popup.show(dhx4.absLeft(d),dhx4.absTop(d),d.offsetWidth,d.offsetHeight),$p.iface.popup.p.onmouseover=function(){s=!0},$p.iface.popup.p.onmouseout=n,e.on_popup&&e.on_popup($p.iface.popup,d))},d.onmouseout=n,l.buttons[t.name]=d,t.sub&&(d.onmouseover=function(){for(var n=0;n<d.parentNode.children.length;n++)if(d.parentNode.children[n]!=d&&d.parentNode.children[n].subdiv){p(d.parentNode.children[n]);break}if(r=!0,!this.subdiv){this.subdiv=document.createElement("div"),this.subdiv.className="md_otooolbar",i=$p.iface.get_offset(d),"right"==t.sub.align?this.subdiv.style.left=i.left+d.offsetWidth-(parseInt(t.sub.width.replace(/\D+/g,""))||56)+"px":this.subdiv.style.left=i.left+"px",this.subdiv.style.top=i.top+c.offsetHeight+"px",this.subdiv.style.height=t.sub.height||"198px",this.subdiv.style.width=t.sub.width||"56px";for(var n in t.sub.buttons){var s=$p.iface.add_button(this.subdiv,e,t.sub.buttons[n]);s.onclick=a}e.wrapper.appendChild(this.subdiv),this.subdiv.onmouseover=function(){o=!0},this.subdiv.onmouseout=function(){o=!1,setTimeout(p,500)},t.title&&$p.iface.popup.show(dhx4.absLeft(this.subdiv),dhx4.absTop(this.subdiv),this.subdiv.offsetWidth,this.subdiv.offsetHeight)}},d.onmouseout=function(){r=!1,setTimeout(p,500)})},this.select=function(n){for(var a=0;a<c.children.length;a++){var i=c.children[a];if(i.name==e.name+"_"+n)return void t.call(i,!0); -}},this.get_selected=function(){for(var e=0;e<c.children.length;e++){var t=c.children[e];if(t.classList.contains("selected"))return t.name}},this.unload=function(){for(;c.firstChild;)c.removeChild(c.firstChild);e.wrapper.removeChild(c)},e.wrapper.appendChild(c),c.style.width=e.width||"28px",c.style.height=e.height||"150px",c.style.position="absolute",e.top&&(c.style.top=e.top),e.left&&(c.style.left=e.left),e.bottom&&(c.style.bottom=e.bottom),e.right&&(c.style.right=e.right),e.paddingRight&&(c.style.paddingRight=e.paddingRight),e.paddingLeft&&(c.style.paddingLeft=e.paddingLeft),e.buttons&&e.buttons.forEach(function(e){l.add(e)})}function eXcell_addr(e){if(e){var t,n=this,a=function(e){return eXcell_proto.input_keydown(e,n)},i=function(e){var t={grid:n.grid}._mixin(n.grid.get_cell_field());return wnd_address(t),$p.iface.cancel_bubble(e)};n.cell=e,n.grid=n.cell.parentNode.grid,n.open_selection=i,n.setValue=function(e){n.setCValue(e)},n.getValue=function(){return n.grid.get_cell_value()},n.edit=function(){var e;n.val=n.getValue(),n.cell.innerHTML='<div class="ref_div21"><input type="text" class="dhx_combo_edit" style="height: 20px;"><div class="ref_field21"> </div></div>',t=n.cell.firstChild,e=t.childNodes[0],e.value=n.val,e.onclick=$p.iface.cancel_bubble,e.readOnly=!0,e.focus(),e.onkeydown=a,t.childNodes[1].onclick=i},n.detach=function(){return n.setValue(n.getValue()),!$p.utils.is_equal(n.val,n.getValue())}}}function wnd_address(e){function t(){var e={name:"wnd_addr",wnd:{id:"wnd_addr",top:130,left:200,width:800,height:560,modal:!0,center:!0,pwnd:g,allow_close:!0,allow_minmax:!0,on_close:m,caption:_.shipping_address}};g&&g.getHeight&&e.wnd.height>g.getHeight()&&(e.wnd.height=g.getHeight()),h=$p.iface.dat_blank(null,e.wnd),h.elmnts.layout=h.attachLayout("2E"),h.elmnts.cell_frm=h.elmnts.layout.cells("a"),h.elmnts.cell_frm.setHeight("110"),h.elmnts.cell_frm.hideHeader(),h.elmnts.cell_frm.fixSize(0,1),h.elmnts.pgrid=h.elmnts.cell_frm.attachPropertyGrid(),h.elmnts.pgrid.setDateFormat("%d.%m.%Y %H:%i"),h.elmnts.pgrid.init(),h.elmnts.pgrid.parse(_._manager.get_property_grid_xml({" ":[{id:"delivery_area",path:"o.delivery_area",synonym:"Район доставки",type:"ref",txt:v.delivery_area.presentation},{id:"region",path:"o.region",synonym:"Регион",type:"ro",txt:v.region},{id:"city",path:"o.city",synonym:"Населенный пункт",type:"ed",txt:v.city},{id:"street",path:"o.street",synonym:"Улица, дом, корпус, литера, квартира",type:"ed",txt:v.street}]},v),function(){h.elmnts.pgrid.enableAutoHeight(!0),h.elmnts.pgrid.setInitWidthsP("40,60"),h.elmnts.pgrid.setSizes(),h.elmnts.pgrid.attachEvent("onPropertyChanged",f)},"xml"),h.elmnts.pgrid.get_cell_field=function(){return{obj:v,field:"delivery_area",on_select:a,pwnd:h,metadata:{synonym:"Район",tooltip:"Район (зона, направление) доставки для группировки при планировании и оптимизации маршрута геокодером",choice_groups_elm:"elm",type:{types:["cat.delivery_areas"],is_ref:!0}}}},h.elmnts.toolbar=h.attachToolbar({icons_path:dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()}),h.elmnts.toolbar.loadStruct('<toolbar><item id="btn_select" type="button" title="Установить адрес" text="<b>Выбрать</b>" /></toolbar>',function(){this.attachEvent("onclick",n)}),h.elmnts.cell_map=h.elmnts.layout.cells("b"),h.elmnts.cell_map.hideHeader();var t={center:new google.maps.LatLng(v.latitude,v.longitude),zoom:v.street?15:12,mapTypeId:google.maps.MapTypeId.ROADMAP};h.elmnts.map=h.elmnts.cell_map.attachMap(t),v.marker=new google.maps.Marker({map:h.elmnts.map,draggable:!0,animation:google.maps.Animation.DROP,position:t.center}),google.maps.event.addListener(v.marker,"click",d),google.maps.event.addListener(v.marker,"dragend",u),s()}function n(e){"btn_select"==e&&(_.delivery_area=v.delivery_area,l(),_.coordinates=JSON.stringify([v.latitude,v.longitude])),h.close()}function a(e){if(void 0!==e){var t,n=b;b=$p.utils.is_data_obj(e)?e:$p.cat.delivery_areas.get(e,!1),t=n!=b,$p.utils.is_data_obj(b)||(b=$p.cat.delivery_areas.get()),h.elmnts.pgrid.cells().setValue(e.presentation),i(t)}}function i(e){if(!v.delivery_area.empty()&&e&&(v.street=""),v.delivery_area.region?(v.region=v.delivery_area.region,h.elmnts.pgrid.cells("region",1).setValue(v.region)):e&&(v.region=""),v.delivery_area.city?(v.city=v.delivery_area.city,h.elmnts.pgrid.cells("city",1).setValue(v.city)):e&&(v.city=""),v.delivery_area.latitude&&v.delivery_area.longitude){var t=new google.maps.LatLng(v.delivery_area.latitude,v.delivery_area.longitude);h.elmnts.map.setCenter(t),v.marker.setPosition(t)}s()}function s(){h.elmnts.pgrid.cells("region",1).setValue(v.region),h.elmnts.pgrid.cells("city",1).setValue(v.city),h.elmnts.pgrid.cells("street",1).setValue(v.street)}function o(){var e=v.street?15:12;h.elmnts.map.getZoom()!=e&&h.elmnts.map.setZoom(e),p(function(e,t){if(t==google.maps.GeocoderStatus.OK){var n=e[0].geometry.location;h.elmnts.map.setCenter(n),v.marker.setPosition(n),v.latitude=n.lat(),v.longitude=n.lng(),v.postal_code=$p.ipinfo.components({},e[0].address_components).postal_code||""}})}function r(){return(v.street?v.street.replace(/,/g," ")+", ":"")+(v.city?v.city+", ":"")+(v.region?v.region+", ":"")+v.country+(v.postal_code?", "+v.postal_code:"")}function l(){_.shipping_address=r();var e='<КонтактнаяИнформация \t\t\t\txmlns="http://www.v8.1c.ru/ssl/contactinfo" \t\t\t\txmlns:xs="http://www.w3.org/2001/XMLSchema" \t\t\t\txmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" \t\t\t\tПредставление="%1"> \t\t\t\t\t<Комментарий/> \t\t\t\t\t<Состав xsi:type="Адрес" Страна="РОССИЯ"> \t\t\t\t\t\t<Состав xsi:type="АдресРФ">'.replace("%1",_.shipping_address);if(v.region&&(e+="\n<СубъектРФ>"+v.region+"</СубъектРФ>"),v.city&&(e+=v.city.indexOf("г.")!=-1||v.city.indexOf("г ")!=-1||v.city.indexOf(" г")!=-1?"\n<Город>"+v.city+"</Город>":"\n<НаселПункт>"+v.city+"</НаселПункт>"),v.street){var t,n,a,i,s,o=v.street.replace(/,/g," ");for(var l in $p.fias){if(1==$p.fias[l].type)for(var c in $p.fias[l].syn)if((n=o.indexOf($p.fias[l].syn[c]))!=-1){i=l,t=o.substr(n+$p.fias[l].syn[c].length).trim(),o=o.substr(0,n).trim();break}if(i)break}if(i||(i="1010",(n=o.indexOf(" "))!=-1&&(t=o.substr(n),o=o.substr(0,n))),e+="\n<Улица>"+o.trim()+"</Улица>",t){a=t.toLowerCase(),t="";for(var l in $p.fias){if(3==$p.fias[l].type)for(var c in $p.fias[l].syn)if((n=a.indexOf($p.fias[l].syn[c]))!=-1){s=l,t=a.substr(n+$p.fias[l].syn[c].length),a=a.substr(0,n);break}if(s)break}s||(s="2010",(n=a.indexOf(" "))!=-1&&(t=a.substr(n),a=a.substr(0,n))),e+='\n<ДопАдрЭл><Номер Тип="'+i+'" Значение="'+a.trim()+'"/></ДопАдрЭл>'}t&&(e+='\n<ДопАдрЭл><Номер Тип="'+s+'" Значение="'+t.trim()+'"/></ДопАдрЭл>')}v.postal_code&&(e+='<ДопАдрЭл ТипАдрЭл="10100000" Значение="'+v.postal_code+'"/>'),e+="</Состав> \t\t\t\t\t</Состав></КонтактнаяИнформация>",_.address_fields=e}function c(){function e(e){if(e.attributes&&2==e.attributes.length){var t={};return t[e.attributes[0].value]=e.attributes[1].value,t}}if(_.address_fields){v.xml=(new DOMParser).parseFromString(_.address_fields,"text/xml");var t,n={},a={building_room:""},i=[],s="СубъектРФ,Округ,СвРайМО,СвРайМО,ВнутригРайон,НаселПункт,Улица,Город,ДопАдрЭл,Адрес_по_документу,Местоположение".split(",");for(var o in s)n[s[o]]=v.xml.getElementsByTagName(s[o]);for(var o in n)for(var r in n[o])if("length"!=r&&n[o].hasOwnProperty(r))if(t=e(n[o][r]))a[o]||(a[o]=[]),a[o].push(t);else if(n[o][r].childNodes.length)for(var l in n[o][r].childNodes)"length"!=l&&n[o][r].childNodes.hasOwnProperty(l)&&((t=e(n[o][r].childNodes[l]))?(a[o]||(a[o]=[]),a[o].push(t)):n[o][r].childNodes[l].nodeValue&&(a[o]?a[o]+=" "+n[o][r].childNodes[l].nodeValue:a[o]=n[o][r].childNodes[l].nodeValue));for(var o in a["ДопАдрЭл"]){for(var r in $p.fias)4==r.length&&a["ДопАдрЭл"][o][r]&&(i[$p.fias[r].type]=$p.fias[r].name+" "+a["ДопАдрЭл"][o][r]);a["ДопАдрЭл"][o][101e5]&&(v.postal_code=a["ДопАдрЭл"][o][101e5])}v.address_fields=a,v.region=a["СубъектРФ"]||a["Округ"]||"",v.city=a["Город"]||a["НаселПункт"]||"",v.street=a["Улица"]||"";for(var o in i)v.street+=" "+i[o]}return new Promise(function(e,t){if($p.ipinfo||($p.ipinfo=new IPInfo),window.google&&window.google.maps)e();else{$p.load_script("//maps.google.com/maps/api/js?callback=$p.ipinfo.location_callback","script",function(){});var n=$p.eve.attachEvent("geo_google_ready",function(){a&&clearTimeout(a),n&&($p.eve.detachEvent(n),n=null,e())}),a=setTimeout(function(){n&&($p.eve.detachEvent(n),n=null),$p.msg.show_msg({type:"alert-warning",text:$p.msg.error_geocoding+" Google",title:$p.msg.main_title}),e()},1e4)}}).then(function(){v.coordinates.length?(v.latitude=v.coordinates[0],v.longitude=v.coordinates[1]):_.shipping_address?p(function(e,t){t==google.maps.GeocoderStatus.OK&&(v.latitude=e[0].geometry.location.lat(),v.longitude=e[0].geometry.location.lng())}):$p.ipinfo.latitude&&$p.ipinfo.longitude?(v.latitude=$p.ipinfo.latitude,v.longitude=$p.ipinfo.longitude):(v.latitude=55.635924,v.longitude=37.6066379,$p.msg.show_msg($p.msg.empty_geocoding))})}function p(e){var t=r();$p.ipinfo.ggeocoder.geocode({address:t},e)}function d(){null!=v.marker.getAnimation()?v.marker.setAnimation(null):(v.marker.setAnimation(google.maps.Animation.BOUNCE),setTimeout(function(){v.marker.setAnimation(null)},1500))}function u(e){$p.ipinfo.ggeocoder.geocode({latLng:e.latLng},function(t,n){if(n==google.maps.GeocoderStatus.OK&&t[0]){var a=t[0];h.setText(a.formatted_address),$p.ipinfo.components(v,a.address_components),s();var i=v.street?15:12;h.elmnts.map.getZoom()!=i&&(h.elmnts.map.setZoom(i),h.elmnts.map.setCenter(e.latLng)),v.latitude=e.latLng.lat(),v.longitude=e.latLng.lng()}})}function f(e,t,n){e&&(v.delivery_area.empty()?(t=n,$p.msg.show_msg({type:"alert",text:$p.msg.delivery_area_empty,title:$p.msg.addr_title}),setTimeout(function(){h.elmnts.pgrid.selectRowById("delivery_area")},50)):"delivery_area"==e?a(t):(v[h.elmnts.pgrid.getSelectedRowId()]=t,o()))}function m(t){return e.grid.editStop(),!t.error}var h,_=e.obj,g=e.pwnd,b=_.delivery_area,v={coordinates:_.coordinates?JSON.parse(_.coordinates):[],country:"Россия",region:"",city:"",street:"",postal_code:"",marker:{}};return v.__define("delivery_area",{get:function(){return b},set:function(e){a(e)}}),c().then(t),h}function AppEvents(){if(this.__define({init:{value:function(){$p.__define("job_prm",{value:new JobPrm,writable:!1}),$p.wsql.init_params()}},do_eventable:{value:function(e){function t(e,t){e=String(e).toLowerCase(),this._evnts.data[e]||(this._evnts.data[e]={});var n=$p.utils.generate_guid();return this._evnts.data[e][n]=t,n}function n(e){if(!e)return a.call(this);for(var t in this._evnts.data){var n=0;for(var i in this._evnts.data[t])i==e?(this._evnts.data[t][i]=null,delete this._evnts.data[t][i]):n++;0==n&&(this._evnts.data[t]=null,delete this._evnts.data[t])}}function a(){for(var e in this._evnts.data){for(var t in this._evnts.data[e])this._evnts.data[e][t]=null,delete this._evnts.data[e][t];this._evnts.data[e]=null,delete this._evnts.data[e]}}function i(e,t){if(e=String(e).toLowerCase(),null==this._evnts.data[e])return!0;var n=!0;for(var a in this._evnts.data[e])n=this._evnts.data[e][a].apply(this,t)&&n;return n}function s(){for(var e in this._evnts.evnts){var t=this._evnts.evnts[e].length;if(t){for(var n=0;n<t;n++)this.emit(e,this._evnts.evnts[e][n]);this._evnts.evnts[e].length=0}}this._evnts.timer=0}e.__define({_evnts:{value:{data:{},timer:0,evnts:{}}},on:{value:t},attachEvent:{value:t},off:{value:n},detachEvent:{value:n},detachAllEvents:{value:a},checkEvent:{value:function(e){return e=String(e).toLowerCase(),null!=this._evnts.data[e]}},callEvent:{value:i},emit:{value:i},emit_async:{value:function(e,t){this._evnts.evnts[e]||(this._evnts.evnts[e]=[]),this._evnts.evnts[e].push(t),this._evnts.timer&&clearTimeout(this._evnts.timer),this._evnts.timer=setTimeout(s.bind(this),4)}}})}}}),"undefined"!=typeof window&&window.dhx4){for(var e in dhx4)this[e]=dhx4[e],delete dhx4[e];window.dhx4=this}else"undefined"==typeof WorkerGlobalScope&&this.do_eventable(this)}function JobPrm(){function e(){return $p.wsql.get_user_param("rest_path")||$p.job_prm.rest_path||"/a/zd/%1/odata/standard.odata/"}function t(){function e(e){var t,n={},a=[];if("#"!==e.substr(0,1)&&"?"!==e.substr(0,1)||(e=e.substr(1)),e.length>2){t=decodeURI(e).split("&");for(var i in t)if(a=t[i].split("="),"m"==a[0])try{n[a[0]]=JSON.parse(a[1])}catch(e){n[a[0]]={}}else n[a[0]]=a[1]||""}return n}return e(location.search)._mixin(e(location.hash))}this.__define({parse_url:{value:t},offline:{value:!1,writable:!0},local_storage_prefix:{value:"",writable:!0},create_tables:{value:!0,writable:!0},url_prm:{value:"undefined"!=typeof window?t():{}},rest_url:{value:function(){var t=e(),n=$p.wsql.get_user_param("zone",$p.job_prm.zone_is_string?"string":"number");return n?t.replace("%1",n):t.replace("%1/","")}},irest_url:{value:function(){var t=e(),n=$p.wsql.get_user_param("zone",$p.job_prm.zone_is_string?"string":"number");return t=t.replace("odata/standard.odata","hs/rest"),n?t.replace("%1",n):t.replace("%1/","")}}}),$p.eve.callEvent("settings",[this]);for(var n in this)"url_prm"!==n&&"function"!=typeof this[n]&&this.url_prm.hasOwnProperty[n]&&(this[n]=this.url_prm[n])}function Modifiers(){var e=[];this.push=function(t){e.push(t)},this.detache=function(t){var n=e.indexOf(t);n!=-1&&e.splice(n,1)},this.clear=function(){e.length=0},this.execute=function(t){var n,a;return e.forEach(function(e){a="function"==typeof e?e(t):$p.injected_data[e](t),n!==!1&&(n=a)}),n},this.execute_external=function(e){var t=$p.wsql.get_user_param("modifiers");return t=t?t.split("\n").map(function(e){return e?new Promise(function(t,n){$p.load_script(e,"script",t)}):Promise.resolve()}):[],Promise.all(t).then(function(){this.execute(e)}.bind(this))}}function IPInfo(){function e(){this.geocode=function(e){return Promise.resolve(!1)}}var t,n,a,i="";this.__define({ipgeo:{value:function(){return $p.ajax.get("//api.sypexgeo.net/").then(function(e){return JSON.parse(e.response)}).catch($p.record_log)}},yageocoder:{get:function(){return t||(t=new e),t},enumerable:!1,configurable:!1},ggeocoder:{get:function(){return n},enumerable:!1,configurable:!1},addr:{get:function(){return i}},parts:{get:function(){return a}},components:{value:function(e,t){var n,a,i,s="",o="",r="";for(n in t){a=t[n];for(i in a.types)switch(a.types[i]){case"route":a.short_name.indexOf("Unnamed")==-1&&(s=a.short_name+(s?" "+s:""),o=a.long_name.replace("улица","").trim());break;case"administrative_area_level_1":e.region=a.long_name;break;case"administrative_area_level_2":e.city=a.short_name,e.city_long=a.long_name;break;case"locality":r=(r?r+" ":"")+a.short_name;break;case"street_number":s=(s?s+" ":"")+a.short_name;break;case"postal_code":e.postal_code=a.short_name}}return e.region&&e.region==e.city_long?e.city.indexOf(r)==-1?e.city=r:e.city="":r&&e.city.indexOf(r)==-1&&e.region.indexOf(r)==-1&&(s=r+", "+s),e.street&&e.street.indexOf(o)!=-1||(e.street=s),e}},location_callback:{value:function(){n=new google.maps.Geocoder,$p.eve.callEvent("geo_google_ready"),navigator.geolocation&&navigator.geolocation.getCurrentPosition(function(e){$p.ipinfo.latitude=e.coords.latitude,$p.ipinfo.longitude=e.coords.longitude;var t=new google.maps.LatLng($p.ipinfo.latitude,$p.ipinfo.longitude);n.geocode({latLng:t},function(e,t){t==google.maps.GeocoderStatus.OK&&(a=!e[1]||e[0].address_components.length>=e[1].address_components.length?e[0]:e[1],i=a.formatted_address,$p.eve.callEvent("geo_current_position",[$p.ipinfo.components({},a.address_components)]))})},$p.record_log,{timeout:3e4})}}})}function SpreadsheetDocument(e){this._attr={orientation:"portrait",title:"",content:document.createElement("DIV")},e&&"string"==typeof e?this.content=e:"object"==typeof e&&this._mixin(e),e=null}function HandsontableDocument(e,t){var n=function(){this._then&&this._then(this)}.bind(this);this._online=t&&t.allow_offline||navigator.onLine&&$p.wsql.pouch.authorized,e instanceof dhtmlXCellObject?(this._cont=document.createElement("div"),e.detachObject(!0),e.attachObject(this._cont)):this._cont=e,this._cont.classList.add("handsontable_wrapper"),this._online?this._cont.innerHTML=t.autorun?$p.msg.report_prepare:$p.msg.report_need_prepare:this._cont.innerHTML=$p.msg.report_need_online,this.then=function(e){return this._then=e,this},this.requery=function(e){this.hot&&this.hot.destroy(),e instanceof Error?this._cont.innerHTML=$p.msg.report_error+(e.name?" <b>"+e.name+"</b>":"")+(e.message?" "+e.message:""):(this._cont.innerHTML="",this.hot=new Handsontable(this._cont,e))},"function"!=typeof Handsontable&&this._online?$p.load_script("https://cdnjs.cloudflare.com/ajax/libs/pikaday/1.4.0/pikaday.min.js","script").then(function(){return $p.load_script("https://cdnjs.cloudflare.com/ajax/libs/numbro/1.9.2/numbro.min.js","script")}).then(function(){return $p.load_script("https://cdn.jsdelivr.net/g/zeroclipboard,handsontable@0.26(handsontable.min.js)","script")}).then(function(){return Promise.all([$p.load_script("https://cdn.jsdelivr.net/handsontable/0.26/handsontable.min.css","link"),$p.load_script("https://cdnjs.cloudflare.com/ajax/libs/numbro/1.9.2/languages/ru-RU.min.js","script")])}).then(n):setTimeout(n)}function Aes(e){"use strict";function t(e){return encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode("0x"+t)})}function n(e){try{return decodeURIComponent(escape(e))}catch(t){return e}}function a(e){if("undefined"!=typeof btoa)return btoa(e);if("undefined"!=typeof Buffer)return new Buffer(e,"binary").toString("base64");throw new Error("No Base64 Encode")}function i(e){if("undefined"!=typeof atob)return atob(e);if("undefined"!=typeof Buffer)return new Buffer(e,"base64").toString("binary");throw new Error("No Base64 Decode")}var s=this;s.cipher=function(e,t){for(var n=4,a=t.length/n-1,i=[[],[],[],[]],o=0;o<4*n;o++)i[o%4][Math.floor(o/4)]=e[o];i=s.addRoundKey(i,t,0,n);for(var r=1;r<a;r++)i=s.subBytes(i,n),i=s.shiftRows(i,n),i=s.mixColumns(i,n),i=s.addRoundKey(i,t,r,n);i=s.subBytes(i,n),i=s.shiftRows(i,n),i=s.addRoundKey(i,t,a,n);for(var l=new Array(4*n),o=0;o<4*n;o++)l[o]=i[o%4][Math.floor(o/4)];return l},s.keyExpansion=function(e){for(var t=4,n=e.length/4,a=n+6,i=new Array(t*(a+1)),o=new Array(4),r=0;r<n;r++){var l=[e[4*r],e[4*r+1],e[4*r+2],e[4*r+3]];i[r]=l}for(var r=n;r<t*(a+1);r++){i[r]=new Array(4);for(var c=0;c<4;c++)o[c]=i[r-1][c];if(r%n==0){o=s.subWord(s.rotWord(o));for(var c=0;c<4;c++)o[c]^=s.rCon[r/n][c]}else n>6&&r%n==4&&(o=s.subWord(o));for(var c=0;c<4;c++)i[r][c]=i[r-n][c]^o[c]}return i},s.subBytes=function(e,t){for(var n=0;n<4;n++)for(var a=0;a<t;a++)e[n][a]=s.sBox[e[n][a]];return e},s.shiftRows=function(e,t){for(var n=new Array(4),a=1;a<4;a++){for(var i=0;i<4;i++)n[i]=e[a][(i+a)%t];for(var i=0;i<4;i++)e[a][i]=n[i]}return e},s.mixColumns=function(e,t){for(var n=0;n<4;n++){for(var a=new Array(4),i=new Array(4),s=0;s<4;s++)a[s]=e[s][n],i[s]=128&e[s][n]?e[s][n]<<1^283:e[s][n]<<1;e[0][n]=i[0]^a[1]^i[1]^a[2]^a[3],e[1][n]=a[0]^i[1]^a[2]^i[2]^a[3],e[2][n]=a[0]^a[1]^i[2]^a[3]^i[3],e[3][n]=a[0]^i[0]^a[1]^a[2]^i[3]}return e},s.addRoundKey=function(e,t,n,a){for(var i=0;i<4;i++)for(var s=0;s<a;s++)e[i][s]^=t[4*n+s][i];return e},s.subWord=function(e){for(var t=0;t<4;t++)e[t]=s.sBox[e[t]];return e},s.rotWord=function(e){for(var t=e[0],n=0;n<3;n++)e[n]=e[n+1];return e[3]=t,e},s.sBox=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],s.rCon=[[0,0,0,0],[1,0,0,0],[2,0,0,0],[4,0,0,0],[8,0,0,0],[16,0,0,0],[32,0,0,0],[64,0,0,0],[128,0,0,0],[27,0,0,0],[54,0,0,0]],s.Ctr={},s.Ctr.encrypt=function(n,i,o){var r=16;128!=o&&192!=o&&256!=o&&(o=128),n=t(n),i=t(i||e);for(var l=o/8,c=new Array(l),p=0;p<l;p++)c[p]=p<i.length?i.charCodeAt(p):0;var d=s.cipher(c,s.keyExpansion(c));d=d.concat(d.slice(0,l-16));for(var u=new Array(r),f=(new Date).getTime(),m=f%1e3,h=Math.floor(f/1e3),_=Math.floor(65535*Math.random()),p=0;p<2;p++)u[p]=m>>>8*p&255;for(var p=0;p<2;p++)u[p+2]=_>>>8*p&255;for(var p=0;p<4;p++)u[p+4]=h>>>8*p&255;for(var g="",p=0;p<8;p++)g+=String.fromCharCode(u[p]);for(var b=s.keyExpansion(d),v=Math.ceil(n.length/r),x="",y=0;y<v;y++){for(var w=0;w<4;w++)u[15-w]=y>>>8*w&255;for(var w=0;w<4;w++)u[15-w-4]=y/4294967296>>>8*w;for(var k=s.cipher(u,b),$=y<v-1?r:(n.length-1)%r+1,j=new Array($),p=0;p<$;p++)j[p]=k[p]^n.charCodeAt(y*r+p),j[p]=String.fromCharCode(j[p]);x+=j.join(""),"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&y%1e3==0&&self.postMessage({progress:y/v})}return x=a(g+x)},s.Ctr.decrypt=function(a,o,r){var l=16;128!=r&&192!=r&&256!=r&&(r=128),a=i(a),o=t(o||e);for(var c=r/8,p=new Array(c),d=0;d<c;d++)p[d]=d<o.length?o.charCodeAt(d):0;var u=s.cipher(p,s.keyExpansion(p));u=u.concat(u.slice(0,c-16));for(var f=new Array(8),m=a.slice(0,8),d=0;d<8;d++)f[d]=m.charCodeAt(d);for(var h=s.keyExpansion(u),_=Math.ceil((a.length-8)/l),g=new Array(_),b=0;b<_;b++)g[b]=a.slice(8+b*l,8+b*l+l);a=g;for(var v="",b=0;b<_;b++){for(var x=0;x<4;x++)f[15-x]=b>>>8*x&255;for(var x=0;x<4;x++)f[15-x-4]=(b+1)/4294967296-1>>>8*x&255;for(var y=s.cipher(f,h),w=new Array(a[b].length),d=0;d<a[b].length;d++)w[d]=y[d]^a[b].charCodeAt(d),w[d]=String.fromCharCode(w[d]);v+=w.join(""),"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&b%1e3==0&&self.postMessage({progress:b/_})}return v=n(v)}}!function(e,t){"object"==typeof exports&&"undefined"!=typeof module&&"function"==typeof require?t(require("../moment")):"function"==typeof define&&define.amd?define(["../moment"],t):t(e.moment)}(this,function(e){"use strict";function t(e,t){var n=e.split("_");return t%10===1&&t%100!==11?n[0]:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?n[1]:n[2]}function n(e,n,a){var i={mm:n?"минута_минуты_минут":"минуту_минуты_минут",hh:"час_часа_часов",dd:"день_дня_дней",MM:"месяц_месяца_месяцев",yy:"год_года_лет"};return"m"===a?n?"минута":"минуту":e+" "+t(i[a],+e)}var a=[/^янв/i,/^фев/i,/^мар/i,/^апр/i,/^ма[йя]/i,/^июн/i,/^июл/i,/^авг/i,/^сен/i,/^окт/i,/^ноя/i,/^дек/i],i=e.defineLocale("ru",{months:{format:"января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря".split("_"),standalone:"январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_")},monthsShort:{format:"янв._февр._мар._апр._мая_июня_июля_авг._сент._окт._нояб._дек.".split("_"),standalone:"янв._февр._март_апр._май_июнь_июль_авг._сент._окт._нояб._дек.".split("_")},weekdays:{standalone:"воскресенье_понедельник_вторник_среда_четверг_пятница_суббота".split("_"),format:"воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу".split("_"),isFormat:/\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/},weekdaysShort:"вс_пн_вт_ср_чт_пт_сб".split("_"),weekdaysMin:"вс_пн_вт_ср_чт_пт_сб".split("_"),monthsParse:a,longMonthsParse:a,shortMonthsParse:a,monthsRegex:/^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i,monthsShortRegex:/^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i,monthsStrictRegex:/^(январ[яь]|феврал[яь]|марта?|апрел[яь]|ма[яй]|июн[яь]|июл[яь]|августа?|сентябр[яь]|октябр[яь]|ноябр[яь]|декабр[яь])/i,monthsShortStrictRegex:/^(янв\.|февр?\.|мар[т.]|апр\.|ма[яй]|июн[ья.]|июл[ья.]|авг\.|сент?\.|окт\.|нояб?\.|дек\.)/i,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY г.",LLL:"D MMMM YYYY г., HH:mm",LLLL:"dddd, D MMMM YYYY г., HH:mm"},calendar:{sameDay:"[Сегодня в] LT",nextDay:"[Завтра в] LT",lastDay:"[Вчера в] LT",nextWeek:function(e){if(e.week()===this.week())return 2===this.day()?"[Во] dddd [в] LT":"[В] dddd [в] LT";switch(this.day()){case 0:return"[В следующее] dddd [в] LT";case 1:case 2:case 4:return"[В следующий] dddd [в] LT";case 3:case 5:case 6:return"[В следующую] dddd [в] LT"}},lastWeek:function(e){if(e.week()===this.week())return 2===this.day()?"[Во] dddd [в] LT":"[В] dddd [в] LT";switch(this.day()){case 0:return"[В прошлое] dddd [в] LT";case 1:case 2:case 4:return"[В прошлый] dddd [в] LT";case 3:case 5:case 6:return"[В прошлую] dddd [в] LT"}},sameElse:"L"},relativeTime:{future:"через %s",past:"%s назад",s:"несколько секунд",m:n,mm:n,h:"час",hh:n,d:"день",dd:n,M:"месяц",MM:n,y:"год",yy:n},meridiemParse:/ночи|утра|дня|вечера/i,isPM:function(e){return/^(дня|вечера)$/.test(e)},meridiem:function(e,t,n){return e<4?"ночи":e<12?"утра":e<17?"дня":"вечера"},ordinalParse:/\d{1,2}-(й|го|я)/,ordinal:function(e,t){switch(t){case"M":case"d":case"DDD":return e+"-й";case"D":return e+"-го";case"w":case"W":return e+"-я";default:return e}},week:{dow:1,doy:7}});return i}),Object.defineProperties(Object.prototype,{__define:{value:function(e,t){return t?Object.defineProperty(this,e,t):Object.defineProperties(this,e),this}},_extend:{value:function(e){var t=function(){};t.prototype=e.prototype,this.prototype=new t,this.prototype.constructor=this,this.__define("superclass",{value:e.prototype,enumerable:!1})}},_mixin:{value:function(e,t,n){var a,i,s={};if(t&&t.length)for(a=0;a<t.length;a++)i=t[a],n&&n.indexOf(i)!=-1||"undefined"!=typeof s[i]&&s[i]==e[i]||(this[i]=e[i]);else for(i in e)n&&n.indexOf(i)!=-1||"undefined"!=typeof s[i]&&s[i]==e[i]||(this[i]=e[i]);return this}},_clone:{value:function(){if(!this||"object"!=typeof this)return this;var e,t,n="function"==typeof this.pop?[]:{};for(e in this)this.hasOwnProperty(e)&&(t=this[e],t?"function"==typeof t||t instanceof DataObj||t instanceof DataManager||t instanceof Date?n[e]=t:"object"==typeof t?n[e]=t._clone():n[e]=t:n[e]=t);return n}}}),Number.prototype.round||(Number.prototype.round=function(e){var t=Math.pow(10,e);return Math.round(this*t)/t}),Number.prototype.pad||(Number.prototype.pad=function(e){for(var t=String(this);t.length<(e||2);)t="0"+t;return t}),Object.observe||Object.unobserve||Object.getNotifier||Object.prototype.__define({observe:{value:function(e,t){e._observers||e.__define({_observers:{value:[],enumerable:!1},_notis:{value:[],enumerable:!1}}),e._observers.push(t)},enumerable:!1},unobserve:{value:function(e,t){if(e._observers){t||(e._observers.length=0);for(var n=0;n<e._observers.length;n++)if(e._observers[n]===t){e._observers.splice(n,1);break}}},enumerable:!1},getNotifier:{value:function(e){var t;return{notify:function(n){e._observers&&n&&(n.object||(n.object=e),e._notis.push(n),n=null,t&&clearTimeout(t),t=setTimeout(function(){e._notis.length&&(e._observers.forEach(function(t){t(e._notis)}),e._notis.length=0),t=!1},4))}}},enumerable:!1}});var $p=new MetaEngine;$p.__define({iface:{value:new InterfaceObjs,writable:!1},current_user:{get:function(){return $p.cat&&$p.cat.users?$p.cat.users.by_id($p.wsql.get_user_param("user_name")):$p.utils.blank.guid}},current_acl:{get:function(){var e,t;return $p.cat&&$p.cat.users_acl&&($p.cat.users_acl.find_rows({owner:$p.current_user},function(t){return e=t,!1}),t=$p.CatUsers_acl.prototype),t||(t={}),e||(this.utils.blank.users_acl?e=this.utils.blank.users_acl:(e=this.utils.blank.users_acl=Object.create(t),e.__define({acl_objs:{value:{_obj:[],each:function(){},find_rows:function(){}}}}))),t.hasOwnProperty("role_available")||t.__define({role_available:{value:function(e){return this.acl_objs._obj.some(function(t){return t.type==e})}},get_acl:{value:function(e){var t=e.split(".");return this._acl&&this._acl[t[0]]?this._acl[t[0]][t[1]]:"e"}}}),e}},load_script:{value:function(e,t,n){return new Promise(function(a,i){var s=document.createElement(t);"script"==t?(s.type="text/javascript",s.src=e,s.async=!0,s.addEventListener("load",n?function(){n(),a()}:a,!1)):(s.type="text/css",s.rel="stylesheet",s.href=e),document.head.appendChild(s),"script"!=t&&a()})}}}),"undefined"!=typeof window&&window.dhx4&&(dhx4.dateFormat.ru="%d.%m.%Y",dhx4.dateLang="ru",dhx4.dateStrings={ru:{monthFullName:["Январь","Февраль","Март","Апрель","Maй","Июнь","Июль","Август","Сентябрь","Oктябрь","Ноябрь","Декабрь"],monthShortName:["Янв","Фев","Maр","Aпр","Maй","Июн","Июл","Aвг","Сен","Окт","Ноя","Дек"],dayFullName:["Воскресенье","Понедельник","Вторник","Среда","Четверг","Пятница","Суббота"],dayShortName:["Вс","Пн","Вт","Ср","Чт","Пт","Сб"]}}),$p.fias=function(){},function(e){e.toString=function(){return"Коды адресного классификатора"},e.types=["владение","здание","помещение"],e[1010]={name:"дом",type:1,order:1,fid:2,syn:[" д."," д "," дом"]},e[1020]={name:"владение",type:1,order:2,fid:1,syn:[" вл."," вл "," влад."," влад "," владен."," владен "," владение"]},e[1030]={name:"домовладение",type:1,order:3,fid:3},e[1050]={name:"корпус",type:2,order:1,syn:[" к."," к "," корп."," корп ","корпус"]},e[1060]={name:"строение",type:2,order:2,fid:1,syn:[" стр."," стр "," строен."," строен ","строение"]},e[1080]={name:"литера",type:2,order:3,fid:3,syn:[" л."," л "," лит."," лит ","литера"]},e[1070]={name:"сооружение",type:2,order:4,fid:2,syn:[" соор."," соор "," сооруж."," сооруж ","сооружение"]},e[1040]={name:"участок",type:2,order:5,syn:[" уч."," уч ","участок"]},e[2010]={name:"квартира",type:3,order:1,syn:["кв.","кв ","кварт.","кварт ","квартира","-"]},e[2030]={name:"офис",type:3,order:2,syn:["оф.","оф ","офис","-"]},e[2040]={name:"бокс",type:3,order:3},e[2020]={name:"помещение",type:3,order:4},e[2050]={name:"комната",type:3,order:5,syn:["комн.","комн ","комната"]},e[101e5]={name:"Почтовый индекс"},e[102e5]={name:"Адресная точка"},e[103e5]={name:"Садовое товарищество"},e[104e5]={name:"Элемент улично-дорожной сети, планировочной структуры дополнительного адресного элемента"},e[105e5]={name:"Промышленная зона"},e[106e5]={name:"Гаражно-строительный кооператив"},e[107e5]={name:"Территория"}}($p.fias),function(e){e.store_url_od="https://chrome.google.com/webstore/detail/hcncallbdlondnoadgjomnhifopfaage",e.argument_is_not_ref="Аргумент не является ссылкой",e.addr_title="Ввод адреса",e.cache_update_title="Обновление кеша браузера",e.cache_update="Выполняется загрузка измененных файлов<br/>и их кеширование в хранилище браузера",e.cancel="Отмена",e.delivery_area_empty="Укажите район доставки",e.empty_login_password="Не указаны имя пользователя или пароль",e.empty_response="Пустой ответ сервера",e.empty_geocoding="Пустой ответ геокодера. Вероятно, отслеживание адреса запрещено в настройках браузера",e.error_geocoding="Ошибка геокодера",e.error_auth="Авторизация пользователя не выполнена",e.error_critical="Критическая ошибка",e.error_metadata="Ошибка загрузки метаданных конфигурации",e.error_network="Ошибка сети или сервера - запрос отклонен",e.error_rights="Ограничение доступа",e.error_low_acl="Недостаточно прав для выполнения операции",e.file_size="Запрещена загрузка файлов<br/>размером более ",e.file_confirm_delete="Подтвердите удаление файла ",e.file_new_date="Файлы на сервере обновлены<br /> Рекомендуется закрыть браузер и войти<br />повторно для применения обновления",e.file_new_date_title="Версия файлов",e.init_catalogues="Загрузка справочников с сервера",e.init_catalogues_meta=": Метаданные объектов",e.init_catalogues_tables=": Реструктуризация таблиц",e.init_catalogues_nom=": Базовые типы + номенклатура",e.init_catalogues_sys=": Технологические справочники", -e.init_login="Укажите имя пользователя и пароль",e.requery="Повторите попытку через 1-2 минуты",e.limit_query="Превышено число обращений к серверу<br/>Запросов за минуту:%1<br/>Лимит запросов:%2<br/>"+e.requery,e.long_operation="Длительная операция",e.logged_in="Авторизован под именем: ",e.log_out_title="Отключиться от сервера?",e.log_out_break="<br/>Завершить синхронизацию?",e.sync_title="Обмен с сервером",e.sync_complite="Синхронизация завершена",e.main_title="Окнософт: заказ дилера ",e.mark_delete_confirm="Пометить объект %1 на удаление?",e.mark_undelete_confirm="Снять пометку удаления с объекта %1?",e.meta={cat:"Справочник",doc:"Документ",cch:"План видов характеристик",cacc:"Планы счетов",tsk:"Задача",ireg:"Регистр сведений",areg:"Регистр накопления",bp:"Бизнес процесс",ts_row:"Строка табличной части",dp:"Обработка",rep:"Отчет"},e.meta_cat="Справочники",e.meta_doc="Документы",e.meta_cch="Планы видов характеристик",e.meta_cacc="Планы счетов",e.meta_tsk="Задачи",e.meta_ireg="Регистры сведений",e.meta_areg="Регистры накопления",e.meta_mgr="Менеджер",e.meta_cat_mgr="Менеджер справочников",e.meta_doc_mgr="Менеджер документов",e.meta_enn_mgr="Менеджер перечислений",e.meta_ireg_mgr="Менеджер регистров сведений",e.meta_areg_mgr="Менеджер регистров накопления",e.meta_accreg_mgr="Менеджер регистров бухгалтерии",e.meta_dp_mgr="Менеджер обработок",e.meta_task_mgr="Менеджер задач",e.meta_bp_mgr="Менеджер бизнес-процессов",e.meta_reports_mgr="Менеджер отчетов",e.meta_charts_of_accounts_mgr="Менеджер планов счетов",e.meta_charts_of_characteristic_mgr="Менеджер планов видов характеристик",e.meta_extender="Модификаторы объектов и менеджеров",e.modified_close="Объект изменен<br/>Закрыть без сохранения?",e.mandatory_title="Обязательный реквизит",e.mandatory_field="Укажите значение реквизита '%1'",e.no_metadata="Не найдены метаданные объекта '%1'",e.no_selected_row="Не выбрана строка табличной части '%1'",e.no_dhtmlx="Библиотека dhtmlx не загружена",e.not_implemented="Не реализовано в текущей версии",e.offline_request="Запрос к серверу в автономном режиме",e.onbeforeunload="Окнософт: легкий клиент. Закрыть программу?",e.order_sent_title="Подтвердите отправку заказа",e.order_sent_message="Отправленный заказ нельзя изменить.<br/>После проверки менеджером<br/>он будет запущен в работу",e.report_error="<i class='fa fa-exclamation-circle fa-2x fa-fw'></i> Ошибка",e.report_prepare="<i class='fa fa-spinner fa-spin fa-2x fa-fw'></i> Подготовка отчета",e.report_need_prepare="<i class='fa fa-info fa-2x fa-fw'></i> Нажмите 'Сформировать' для получения отчета",e.report_need_online="<i class='fa fa-plug fa-2x fa-fw'></i> Нет подключения. Отчет недоступен в автономном режиме",e.request_title="Запрос регистрации",e.request_message="Заявка зарегистрирована. После обработки менеджером будет сформировано ответное письмо",e.select_from_list="Выбор из списка",e.select_grp="Укажите группу, а не элемент",e.select_elm="Укажите элемент, а не группу",e.select_file_import="Укажите файл для импорта",e.srv_overload="Сервер перегружен",e.sub_row_change_disabled="Текущая строка подчинена продукции.<br/>Строку нельзя изменить-удалить в документе<br/>только через построитель",e.sync_script="Обновление скриптов приложения:",e.sync_data="Синхронизация с сервером выполняется:<br />* при первом старте программы<br /> * при обновлении метаданных<br /> * при изменении цен или технологических справочников",e.sync_break="Прервать синхронизацию",e.sync_no_data="Файл не содержит подходящих элементов для загрузки",e.tabular_will_cleared="Табличная часть '%1' будет очищена. Продолжить?",e.unsupported_browser_title="Браузер не поддерживается",e.unsupported_browser="Несовместимая версия браузера<br/>Рекомендуется Google Chrome",e.supported_browsers="Рекомендуется Chrome, Safari или Opera",e.unsupported_mode_title="Режим не поддерживается",e.unsupported_mode="Программа не установлена<br/> в <a href='"+e.store_url_od+"'>приложениях Google Chrome</a>",e.unknown_error="Неизвестная ошибка в функции '%1'",e.value="Значение"}($p.msg),DataManager.prototype.__define({family_name:{get:function(){return $p.msg["meta_"+this.class_name.split(".")[0]+"_mgr"].replace($p.msg.meta_mgr+" ","")}},table_name:{get:function(){return this.class_name.replace(".","_")}},find_rows:{value:function(e,t){return $p._find_rows.call(this,this.by_ref,e,t)}},extra_fields:{value:function(e){var t=$p.cat.destinations||$p.cch.destinations,n=_md.class_name_to_1c(this.class_name).replace(".","_"),a=[];return t&&t.find_rows({predefined_name:n},function(e){var t=e.extra_fields||e.ДополнительныеРеквизиты;return t&&t.each(function(e){e._deleted||e.ПометкаУдаления||a.push(e.property||e.Свойство)}),!1}),a}},extra_properties:{value:function(e){return[]}},obj_constructor:{value:function(e){var t=this.class_name.split("."),n=t[0].charAt(0).toUpperCase()+t[0].substr(1)+t[1].charAt(0).toUpperCase()+t[1].substr(1);return e?n+e.charAt(0).toUpperCase()+e.substr(1)+"Row":n}}}),DataManager.prototype.sync_grid=function(e,t){function n(){if("function"==typeof e.custom_selection)return e.custom_selection(e);if("ram"==i.cachable){if("get_tree"==e.action)return $p.wsql.promise(i.get_sql_struct(e),[]).then($p.iface.data_to_tree);if("get_selection"==e.action)return $p.wsql.promise(i.get_sql_struct(e),[]).then(function(t){return $p.iface.data_to_grid.call(i,t,e)})}else if(0==i.cachable.indexOf("doc")){if("get_tree"==e.action)return i.pouch_tree(e);if("get_selection"==e.action)return i.pouch_selection(e)}else{if("get_tree"==e.action)return i.rest_tree(e);if("get_selection"==e.action)return i.rest_selection(e)}}function a(e){return new Promise(function(n,a){"string"==typeof e?("{"==e.substr(0,1)&&(e=JSON.parse(e)),t&&t.parse?(t.xmlFileUrl="exec",t.parse(e,function(){n(e)},"xml")):n(e)):t instanceof dhtmlXTreeView&&t.loadStruct?t.loadStruct(e,function(){n(e)}):n(e)})}var i=this;return n().then(a).catch($p.record_log)},DataManager.prototype.get_option_list=function(e,t){function n(t){return $p.utils.is_equal(t.value,e)&&(t.selected=!0),t}var a,i,s,o=this,r=[];if(t.presentation&&(a=o.metadata().input_by_string)&&(i=t.presentation.like,delete t.presentation,t.or=[],a.forEach(function(e){s={},s[e]={like:i},t.or.push(s)})),"ram"==o.cachable||t&&t._local)return o.find_rows(t,function(e){r.push(n({text:e.presentation,value:e.ref}))}),Promise.resolve(r);if("e1cib"!=o.cachable)return o.pouch_find_rows(t).then(function(e){return e.forEach(function(e){r.push(n({text:e.presentation,value:e.ref}))}),r});var l={selection:t,top:t._top},c=o instanceof DocManager||o instanceof BusinessProcessManager;return delete t._top,c?l.fields=["ref","date","number_doc"]:o.metadata().main_presentation_name?l.fields=["ref","name"]:l.fields=["ref","id"],_rest.load_array(l,o).then(function(e){return e.forEach(function(e){r.push(n({text:c?e.number_doc+" от "+$p.moment(e.date).format($p.moment._masks.ldt):e.name||e.id,value:e.ref}))}),r})},DataManager.prototype.tabular_captions=function(e,t){},DataManager.prototype.get_property_grid_xml=function(e,t,n){var a,i,s,o,r,l,c,p=this,d="<rows>",u=function(){if(!e)if(s=p.metadata(),s.form&&s.form.obj&&s.form.obj.head)e=s.form.obj.head;else{if(e={" ":[]},t instanceof CatObj?(s.code_length&&e[" "].push("id"),s.main_presentation_name&&e[" "].push("name")):t instanceof DocObj&&(e[" "].push("number_doc"),e[" "].push("date")),!t.is_folder)for(a in s.fields)"predefined_name"==a||s.fields[a].hide||e[" "].push(a);s.tabular_sections&&s.tabular_sections.extra_fields&&(e["Дополнительные реквизиты"]=[])}},f=function(e,t){l=$p.utils.is_data_obj(e)?e.presentation:e,t.type.is_ref||(t.type.date_part?l=$p.moment(l).format($p.moment._masks[t.type.date_part]):"boolean"==t.type.types[0]&&(l=l?"1":"0"))},m=function(e){r=_md.control_by_type(s.type,e),f(e,s)},h=function(e,a){if(a){var i=e.property||e.param||e.Параметр||e.Свойство,u=void 0!=e.value?e.value:e.Значение;i.empty()?(c=a+"|empty",r="ro",l="",s={synonym:"?"}):(s={synonym:i.presentation,type:i.type},c=a+"|"+i.ref,m(u),"edn"==r&&(r="calck"),i.mandatory&&(r+='" class="cell_mandatory'))}else if("object"==typeof e)c=e.id,s=n&&n.metadata&&n.metadata[c],s?e.synonym&&(s.synonym=e.synonym):s={synonym:e.synonym},r=e.type,l="",e.hasOwnProperty("txt")?l=e.txt:void 0!==(o=t[c])&&f(o,s.type?s:_md.get(p.class_name,c));else if(n&&n.metadata&&void 0!==(s=n.metadata[e]))c=e,m(o=t[e]);else{if(void 0===(o=t[e]))return;s=_md.get(p.class_name,c=e),m(o)}d+='<row id="'+c+'"><cell>'+(s.synonym||s.name)+'</cell><cell type="'+r+'">'+l+"</cell></row>"};u();for(a in e){" "!=a&&(d+='<row open="1"><cell>'+a+"</cell>");for(i in e[a])h(e[a][i]);if(n&&a==n.title&&t[n.ts]){var _,g=p.extra_fields(t),b="property,param,Свойство,Параметр".split(","),v=t[n.ts]._owner._metadata.tabular_sections[t[n.ts]._name].fields;b.some(function(e){if(v[e])return _=e,!0})&&(t[n.ts].forEach(function(e){var t=g.indexOf(e[_]);t!=-1&&g.splice(t,1)}),g.forEach(function(e){var a=t[n.ts].add();a[_]=e})),t[n.ts].find_rows(n.selection,function(e){h(e,n.ts)})}" "!=a&&(d+="</row>")}return d+="</rows>"},DataManager.prototype.print=function(e,t,n){function a(e){n&&n.progressOff&&n.progressOff(),e&&e.focus()}if(n&&n.progressOn&&n.progressOn(),setTimeout(a,3e3),this._printing_plates[t]instanceof DataObj&&(t=this._printing_plates[t]),t instanceof DataObj&&t.execute)return e instanceof DataObj?t.execute(e).then(a):this.get(e,!0,!0).then(t.execute.bind(t)).then(a);var i={};return $p.ajax.default_attr(i,$p.job_prm.irest_url()),i.url+=this.rest_name+"(guid'"+$p.utils.fix_guid(e)+"')/Print(model="+t+", browser_uid="+$p.wsql.get_user_param("browser_uid")+")",$p.ajax.get_and_show_blob(i.url,i,"get").then(a)},DataManager.prototype.printing_plates=function(){var e={},t=this;return t._printing_plates||(t.metadata().printing_plates?t._printing_plates=t.metadata().printing_plates:("ram"==t.metadata().cachable||t.metadata().cachable&&0==t.metadata().cachable.indexOf("doc"))&&(t._printing_plates={})),!t._printing_plates&&$p.ajax.authorized?($p.ajax.default_attr(e,$p.job_prm.irest_url()),e.url+=t.rest_name+"/Print()",$p.ajax.get_ex(e.url,e).then(function(e){return t._printing_plates=JSON.parse(e.response),t._printing_plates}).catch(function(){}).then(function(e){return e||(t._printing_plates={})})):Promise.resolve(t._printing_plates)},RefDataManager._extend(DataManager),RefDataManager.prototype.__define({push:{value:function(e,t){t&&t!=e.ref?(delete this.by_ref[e.ref],this.by_ref[t]=e):this.by_ref[e.ref]=e}},each:{value:function(e){for(var t in this.by_ref)if(t&&t!=$p.utils.blank.guid&&1==e.call(this,this.by_ref[t]))break}},forEach:{value:function(e){return this.each.call(this,e)}},get:{value:function(e,t,n){var a=this.by_ref[e]||this.by_ref[e=$p.utils.fix_guid(e)];if(!a){if(n&&!t)return;a=new($p[this.obj_constructor()])(e,this,(!0))}return t===!1?a:void 0===t&&e===$p.utils.blank.guid?a:a.is_new()?a.load():t?Promise.resolve(a):a}},create:{value:function(e,t,n){e&&"object"==typeof e||(e={}),e.ref&&$p.utils.is_guid(e.ref)&&!$p.utils.is_empty_guid(e.ref)||(e.ref=$p.utils.generate_guid());var a=this.by_ref[e.ref];if(!a)if(a=new($p[this.obj_constructor()])(e,this),!t&&e.ref&&e.presentation&&2==Object.keys(e).length);else{a instanceof DocObj&&a.date==$p.utils.blank.date&&(a.date=new Date);var i=this.handle_event(a,"after_create");if(this instanceof DocManager||this instanceof TaskManager||this instanceof BusinessProcessManager?a.number_doc||a.new_number_doc():!a.id&&a._metadata.code_length&&a.new_number_doc(),i===!1)return Promise.resolve(a);if("object"==typeof i&&i.then)return i;if("e1cib"==this.cachable&&t){var s={};return $p.ajax.default_attr(s,$p.job_prm.irest_url()),s.url+=this.rest_name+"/Create()",$p.ajax.get_ex(s.url,s).then(function(e){return a._mixin(JSON.parse(e.response),void 0,["ref"])})}}return n?a:Promise.resolve(a)}},unload_obj:{value:function(e){delete this.by_ref[e],this.alatable.some(function(t,n,a){if(t.ref==e)return a.splice(n,1),!0})}},find:{value:function(e,t){return $p._find(this.by_ref,e,t)}},load_array:{value:function(e,t){for(var n,a,i=[],s=0;s<e.length;s++){if(n=$p.utils.fix_guid(e[s]),a=this.by_ref[n])(a.is_new()||t)&&(a._mixin(e[s]),a._set_loaded());else{if("update_only"==t)continue;a=new($p[this.obj_constructor()])(e[s],this),t&&a._set_loaded()}i.push(a)}return i}},first_folder:{value:function(e){for(var t in this.by_ref){var n=this.by_ref[t];if(n.is_folder&&(!e||$p.utils.is_equal(e,n.owner)))return n}return this.get()}},get_sql_struct:{value:function(e){function t(){function t(){var e=[],t="_t_.ref, _t_.`_deleted`";return r.form&&r.form.selection?r.form.selection.fields.forEach(function(t){e.push(t)}):o instanceof DocManager?(e.push("posted"),e.push("date"),e.push("number_doc")):(r.hierarchical&&r.group_hierarchy?e.push("is_folder"):e.push("0 as is_folder"),o instanceof ChartOfAccountManager?(e.push("id"),e.push("name as presentation")):r.main_presentation_name?e.push("name as presentation"):r.code_length?e.push("id as presentation"):e.push("'...' as presentation"),r.has_owners&&e.push("owner"),r.code_length&&e.push("id")),e.forEach(function(e){t+=e.indexOf(" as ")!=-1?", "+e:_md.sql_mask(e,!0)}),t}function n(){var e,t="";if(r.form&&r.form.selection)for(var n in r.form.selection.fields)r.form.selection.fields[n].indexOf(" as ")!=-1&&r.form.selection.fields[n].indexOf("_t_.")==-1&&(e=r.form.selection.fields[n].split(" as "),e[0]=e[0].split("."),e[0].length>1&&(t&&(t+="\n"),t+="left outer join "+e[0][0]+" on "+e[0][0]+".ref = _t_."+e[1]));return t}function a(){var t;return t=o instanceof ChartOfAccountManager?" WHERE ("+(u?0:1):r.hierarchical?r.has_owners?" WHERE ("+(c||u?1:0)+" OR _t_.parent = '"+p+"') AND ("+(l==$p.utils.blank.guid?1:0)+" OR _t_.owner = '"+l+"') AND ("+(u?0:1):" WHERE ("+(c||u?1:0)+" OR _t_.parent = '"+p+"') AND ("+(u?0:1):r.has_owners?" WHERE ("+(l==$p.utils.blank.guid?1:0)+" OR _t_.owner = '"+l+"') AND ("+(u?0:1):" WHERE ("+(u?0:1),o.sql_selection_where_flds?t+=o.sql_selection_where_flds(u):o instanceof DocManager?t+=" OR _t_.number_doc LIKE '"+u+"'":((r.main_presentation_name||o instanceof ChartOfAccountManager)&&(t+=" OR _t_.name LIKE '"+u+"'"),r.code_length&&(t+=" OR _t_.id LIKE '"+u+"'")),t+=") AND (_t_.ref != '"+$p.utils.blank.guid+"')",e.selection&&("function"==typeof e.selection||e.selection.forEach(function(e){for(var n in e)if("function"==typeof e[n])t+="\n AND "+e[n](o,n)+" ";else if(r.fields.hasOwnProperty(n)||"ref"===n)if(e[n]===!0)t+="\n AND _t_."+n+" ";else if(e[n]===!1)t+="\n AND (not _t_."+n+") ";else if("object"==typeof e[n])if($p.utils.is_data_obj(e[n])||$p.utils.is_guid(e[n]))t+="\n AND (_t_."+n+" = '"+e[n]+"') ";else{var a,i=Object.keys(e[n]),s=e[n][i[0]],l=r.fields[n];l&&l.type.is_ref&&(a=_md.value_mgr({},n,l.type,!0,s)),t+="not"==i[0]?"\n AND (not _t_."+n+" = '"+s+"') ":"in"==i[0]?"\n AND (_t_."+n+" in ("+e[n].in.reduce(function(e,t){return e&&(e+=","),e+="number"==typeof t?t.toString():"'"+t+"'"},"")+")) ":"\n AND (_t_."+n+" = '"+s+"') "}else t+="string"==typeof e[n]?"\n AND (_t_."+n+" = '"+e[n]+"') ":"\n AND (_t_."+n+" = "+e[n]+") ";else"is_folder"==n&&r.hierarchical&&r.group_hierarchy})),t}function i(){return o instanceof ChartOfAccountManager?"ORDER BY id":r.hierarchical?r.group_hierarchy?"ORDER BY _t_.is_folder desc, is_initial_value, presentation":"ORDER BY _t_.parent desc, is_initial_value, presentation":"ORDER BY is_initial_value, presentation"}function s(){function t(t){t&&(f=e.set_parent=t.parent.ref,p=f,c=!1),u&&u.indexOf("%")==-1&&(u="%"+u+"%")}r.has_owners&&(l=e.owner,e.selection&&"function"!=typeof e.selection&&e.selection.forEach(function(e){e.owner&&(l="object"==typeof e.owner?e.owner.valueOf():e.owner,delete e.owner)}),l||(l=$p.utils.blank.guid)),d!=$p.utils.blank.guid&&c&&r.hierarchical?t(o.get(d,!1)):t()}var l,c=!e.parent,p=e.parent||$p.utils.blank.guid,d=e.initial_value||$p.utils.blank.guid,u=e.filter||"",f=$p.utils.blank.guid;s();var m;return m=o.sql_selection_list_flds?o.sql_selection_list_flds(d):("SELECT %2, case when _t_.ref = '"+d+"' then 0 else 1 end as is_initial_value FROM `"+o.table_name+"` AS _t_ %j %3 %4 LIMIT 300").replace("%2",t()).replace("%j",n()),m.replace("%3",a()).replace("%4",i())}function n(){var t="CREATE TABLE IF NOT EXISTS ";if(e&&e.postgres){t+=o.table_name+" (ref uuid PRIMARY KEY NOT NULL, _deleted boolean",o instanceof DocManager?t+=", posted boolean, date timestamp with time zone, number_doc character(11)":(r.code_length&&(t+=", id character("+r.code_length+")"),t+=", name character varying(50), is_folder boolean");for(i in r.fields)i.length>30?r.fields[i].short_name?s=r.fields[i].short_name:(c++,s=i[0]+c+i.substr(i.length-27)):s=i,t+=", "+s+_md.sql_type(o,i,r.fields[i].type,!0)+_md.sql_composite(r.fields,i,s,!0);for(i in r.tabular_sections)t+=", ts_"+i+" JSON"}else{t+="`"+o.table_name+"` (ref CHAR PRIMARY KEY NOT NULL, `_deleted` BOOLEAN",t+=o instanceof DocManager?", posted boolean, date Date, number_doc CHAR":", id CHAR, name CHAR, is_folder BOOLEAN";for(i in r.fields)t+=_md.sql_mask(i)+_md.sql_type(o,i,r.fields[i].type)+_md.sql_composite(r.fields,i);for(i in r.tabular_sections)t+=", `ts_"+i+"` JSON"}return t+=")"}function a(){var e=["ref","_deleted"],t="INSERT INTO `"+o.table_name+"` (ref, `_deleted`",n="(?";"cat"==o.class_name.substr(0,3)?(t+=", id, name, is_folder",e.push("id"),e.push("name"),e.push("is_folder")):"doc"==o.class_name.substr(0,3)&&(t+=", posted, date, number_doc",e.push("posted"),e.push("date"),e.push("number_doc"));for(i in r.fields)t+=_md.sql_mask(i),e.push(i);for(i in r.tabular_sections)t+=", `ts_"+i+"`",e.push("ts_"+i);for(t+=") VALUES ",i=1;i<e.length;i++)n+=", ?";return n+=")",t+=n,{sql:t,fields:e,values:n}}var i,s,o=this,r=o.metadata(),l={},c=0,p=e&&e.action?e.action:"create_table";return"create_table"==p?l=n():["insert","update","replace"].indexOf(p)!=-1?l[o.table_name]=a():"select"==p?l="SELECT * FROM `"+o.table_name+"` WHERE ref = ?":"select_all"==p?l="SELECT * FROM `"+o.table_name+"`":"delete"==p?l="DELETE FROM `"+o.table_name+"` WHERE ref = ?":"drop"==p?l="DROP TABLE IF EXISTS `"+o.table_name+"`":"get_tree"==p?l=!e.filter||e.filter.is_folder?"SELECT ref, parent, name as presentation FROM `"+o.table_name+"` WHERE is_folder order by parent, name":"SELECT ref, parent, name as presentation FROM `"+o.table_name+"` order by parent, name":"get_selection"==p&&(l=t()),l}},caption_flds:{value:function(e){var t=e.metadata||this.metadata(),n='<column id="%1" width="%2" type="%3" align="%4" sort="%5">%6</column>',a=[],i="";if(t.form&&t.form.selection?a=t.form.selection.cols:this instanceof DocManager?(a.push(new Col_struct("date","160","ro","left","server","Дата")),a.push(new Col_struct("number_doc","140","ro","left","server","Номер")),t.fields.note&&a.push(new Col_struct("note","*","ro","left","server",t.fields.note.synonym)),t.fields.responsible&&a.push(new Col_struct("responsible","*","ro","left","server",t.fields.responsible.synonym))):this instanceof ChartOfAccountManager?(a.push(new Col_struct("id","140","ro","left","server","Код")),a.push(new Col_struct("presentation","*","ro","left","server","Наименование"))):a.push(new Col_struct("presentation","*","ro","left","server","Наименование")),e.get_header&&a.length){i="<head>";for(var s in a)i+=n.replace("%1",a[s].id).replace("%2",a[s].width).replace("%3",a[s].type).replace("%4",a[s].align).replace("%5",a[s].sort).replace("%6",a[s].caption);i+="</head>"}return{head:i,acols:a}}},load_cached_server_array:{value:function(e,t){var n,a=[],i=this,s=t?{class_name:i.class_name,rest_name:t}:i,o=!t;if(e.forEach(function(e){n=i.get(e.ref||e,!1,!0),(!n||o&&n.is_new())&&a.push(e.ref||e)}),a.length){var r={url:"",selection:{ref:{in:a}}};return o&&(r.fields=["ref"]),$p.rest.build_select(r,s),$p.ajax.get_ex(r.url,r).then(function(t){var n=JSON.parse(t.response);if(o)n=n.value;else{n=n.data;for(var a in n)!n[a].ref&&n[a].id&&(n[a].ref=n[a].id),n[a].Код&&(n[a].id=n[a].Код,delete n[a].Код),n[a]._not_set_loaded=!0}return i.load_array(n),e})}return Promise.resolve(e)}},predefined:{value:function(e){return this._predefined||(this._predefined={}),this._predefined[e]||(this._predefined[e]=this.get(),this.find_rows({predefined_name:e},function(t){return this._predefined[e]=t,!1})),this._predefined[e]}}}),DataProcessorsManager._extend(DataManager),DataProcessorsManager.prototype.__define({create:{value:function(){return new($p[this.obj_constructor()])({},this)}},unload_obj:{value:function(){}}}),EnumManager._extend(RefDataManager),EnumManager.prototype.__define({get:{value:function(e){if(e instanceof EnumObj)return e;e&&e!=$p.utils.blank.guid||(e="_");var t=this[e];return t||(t=new EnumObj({name:e},this)),t}},push:{value:function(e,t){this.__define(t,{value:e})}},each:{value:function(e){this.alatable.forEach(function(t){t.ref&&"_"!=t.ref&&t.ref!=$p.utils.blank.guid&&e.call(this[t.ref])}.bind(this))}}}),EnumManager.prototype.get_sql_struct=function(e){var t="CREATE TABLE IF NOT EXISTS ",n=e&&e.action?e.action:"create_table";return e&&e.postgres?"create_table"==n?t+=this.table_name+" (ref character varying(255) PRIMARY KEY NOT NULL, sequence INT, synonym character varying(255))":["insert","update","replace"].indexOf(n)!=-1?(t={},t[this.table_name]={sql:"INSERT INTO "+this.table_name+" (ref, sequence, synonym) VALUES ($1, $2, $3)",fields:["ref","sequence","synonym"],values:"($1, $2, $3)"}):"delete"==n&&(t="DELETE FROM "+this.table_name+" WHERE ref = $1"):"create_table"==n?t+="`"+this.table_name+"` (ref CHAR PRIMARY KEY NOT NULL, sequence INT, synonym CHAR)":["insert","update","replace"].indexOf(n)!=-1?(t={},t[this.table_name]={sql:"INSERT INTO `"+this.table_name+"` (ref, sequence, synonym) VALUES (?, ?, ?)",fields:["ref","sequence","synonym"],values:"(?, ?, ?)"}):"delete"==n&&(t="DELETE FROM `"+this.table_name+"` WHERE ref = ?"),t},EnumManager.prototype.get_option_list=function(e,t){function n(t){return $p.utils.is_equal(t.value,e)&&(t.selected=!0),t}var a,i=[],s="";if(t)for(var o in t)"_"!=o.substr(0,1)&&("ref"==o?a=t[o].hasOwnProperty("in")?t[o].in:t[o]:s=t[o]);return"object"==typeof s&&(s=s.like?s.like:""),s=s.toLowerCase(),this.alatable.forEach(function(e){if(!s||e.synonym&&e.synonym.toLowerCase().indexOf(s)!=-1){if(a)if(Array.isArray(a)){if(!a.some(function(t){return t.name==e.ref||t.ref==e.ref||t==e.ref}))return}else if(a.name!=e.ref&&a.ref!=e.ref&&a!=e.ref)return;i.push(n({text:e.synonym||"",value:e.ref}))}}),Promise.resolve(i)},RegisterManager._extend(DataManager),RegisterManager.prototype.__define({get_sql_struct:{value:function(e){function t(){function t(){var e=[],t="_t_.ref";if(r.form&&r.form.selection)r.form.selection.fields.forEach(function(t){e.push(t)});else for(var n in r.dimensions)e.push(n);return e.forEach(function(e){t+=e.indexOf(" as ")!=-1?", "+e:_md.sql_mask(e,!0)}),t}function n(){var e,t="";if(r.form&&r.form.selection)for(var n in r.form.selection.fields)r.form.selection.fields[n].indexOf(" as ")!=-1&&r.form.selection.fields[n].indexOf("_t_.")==-1&&(e=r.form.selection.fields[n].split(" as "),e[0]=e[0].split("."),e[0].length>1&&(t&&(t+="\n"),t+="left outer join "+e[0][0]+" on "+e[0][0]+".ref = _t_."+e[1]));return t}function a(){var t=" WHERE ("+(s?0:1);return o.sql_selection_where_flds&&(t+=o.sql_selection_where_flds(s)),t+=")",e.selection&&("function"==typeof e.selection||e.selection.forEach(function(e){for(var n in e)if("function"==typeof e[n])t+="\n AND "+e[n](o,n)+" ";else if(r.fields.hasOwnProperty(n))if(e[n]===!0)t+="\n AND _t_."+n+" ";else if(e[n]===!1)t+="\n AND (not _t_."+n+") ";else if("object"==typeof e[n])if($p.utils.is_data_obj(e[n]))t+="\n AND (_t_."+n+" = '"+e[n]+"') ";else{var a,i=Object.keys(e[n]),s=e[n][i[0]],l=r.fields[n];l&&l.type.is_ref&&(a=_md.value_mgr({},n,l.type,!0,s)),t+="not"==i[0]?"\n AND (not _t_."+n+" = '"+s+"') ":"\n AND (_t_."+n+" = '"+s+"') "}else t+="string"==typeof e[n]?"\n AND (_t_."+n+" = '"+e[n]+"') ":"\n AND (_t_."+n+" = "+e[n]+") ";else"is_folder"==n&&r.hierarchical&&r.group_hierarchy})),t}function i(){return""}var s=e.filter||"";s&&s.indexOf("%")==-1&&(s="%"+s+"%");var l;return l=o.sql_selection_list_flds?o.sql_selection_list_flds():("SELECT %2 FROM `"+o.table_name+"` AS _t_ %j %3 %4 LIMIT 300").replace("%2",t()).replace("%j",n()),l.replace("%3",a()).replace("%4",i())}function n(){var t="CREATE TABLE IF NOT EXISTS ",n=!0;if(e&&e.postgres){t+=o.table_name+" (",r.splitted&&(t+="zone integer",n=!1);for(s in r.dimensions)n?(t+=s,n=!1):t+=", "+s,t+=_md.sql_type(o,s,r.dimensions[s].type,!0)+_md.sql_composite(r.dimensions,s,"",!0);for(s in r.resources)t+=", "+s+_md.sql_type(o,s,r.resources[s].type,!0)+_md.sql_composite(r.resources,s,"",!0);for(s in r.attributes)t+=", "+s+_md.sql_type(o,s,r.attributes[s].type,!0)+_md.sql_composite(r.attributes,s,"",!0);t+=", PRIMARY KEY (",n=!0,r.splitted&&(t+="zone",n=!1);for(s in r.dimensions)n?(t+=s,n=!1):t+=", "+s}else{t+="`"+o.table_name+"` (ref CHAR PRIMARY KEY NOT NULL, `_deleted` BOOLEAN";for(s in r.dimensions)t+=_md.sql_mask(s)+_md.sql_type(o,s,r.dimensions[s].type);for(s in r.resources)t+=_md.sql_mask(s)+_md.sql_type(o,s,r.resources[s].type);for(s in r.attributes)t+=_md.sql_mask(s)+_md.sql_type(o,s,r.attributes[s].type)}return t+=")"}function a(){var e="INSERT OR REPLACE INTO `"+o.table_name+"` (",t=[],n=!0;for(s in r.dimensions)n?(e+=s,n=!1):e+=", "+s,t.push(s);for(s in r.resources)e+=", "+s,t.push(s);for(s in r.attributes)e+=", "+s,t.push(s);for(e+=") VALUES (?",s=1;s<t.length;s++)e+=", ?";return e+=")",{sql:e,fields:t}}function i(){var t="SELECT * FROM `"+o.table_name+"` WHERE ",n=!0;e._values=[];for(var a in r.dimensions)n?n=!1:t+=" and ",t+="`"+a+"`=?",e._values.push(e[a]);return n&&(t+="1"),t}var s,o=this,r=o.metadata(),l={},c=e&&e.action?e.action:"create_table";return"create_table"==c?l=n():c in{insert:"",update:"",replace:""}?l[o.table_name]=a():"select"==c?l=i():"select_all"==c?l=i():"delete"==c?l="DELETE FROM `"+o.table_name+"` WHERE ref = ?":"drop"==c?l="DROP TABLE IF EXISTS `"+o.table_name+"`":"get_selection"==c&&(l=t()),l}},get_ref:{value:function(e){if(e instanceof RegisterRow&&(e=e._obj),e.ref)return e.ref;var t="",n=this.metadata().dimensions;for(var a in n)t+=t?"¶":"",t+=n[a].type.is_ref?$p.utils.fix_guid(e[a]):!e[a]&&n[a].type.digits?"0":n[a].date_part?$p.moment(e[a]||$p.utils.blank.date).format($p.moment.defaultFormatUtc):void 0!=e[a]?String(e[a]):"$";return t}},caption_flds:{value:function(e){var t=e.metadata||this.metadata(),n='<column id="%1" width="%2" type="%3" align="%4" sort="%5">%6</column>',a=[],i="";if(t.form&&t.form.selection)a=t.form.selection.cols;else for(var s in t.dimensions)a.push(new Col_struct(s,"*","ro","left","server",t.dimensions[s].synonym));if(e.get_header&&a.length){i="<head>";for(var o in a)i+=n.replace("%1",a[o].id).replace("%2",a[o].width).replace("%3",a[o].type).replace("%4",a[o].align).replace("%5",a[o].sort).replace("%6",a[o].caption);i+="</head>"}return{head:i,acols:a}}},create:{value:function(e){e&&"object"==typeof e||(e={});var t=this.by_ref[e.ref];if(!t){t=new($p[this.obj_constructor()])(e,this);var n=this.handle_event(t,"after_create");if(n===!1)return Promise.resolve(t);if("object"==typeof n&&n.then)return n}return Promise.resolve(t)}}}),InfoRegManager._extend(RegisterManager),InfoRegManager.prototype.slice_first=function(e){},InfoRegManager.prototype.slice_last=function(e){},LogManager._extend(InfoRegManager),AccumRegManager._extend(RegisterManager),CatManager._extend(RefDataManager),CatManager.prototype.by_name=function(e){var t;return this.find_rows({name:e},function(e){return t=e,!1}),t||(t=this.get()),t},CatManager.prototype.by_id=function(e){var t;return this.find_rows({id:e},function(e){return t=e,!1}),t||(t=this.get()),t},CatManager.prototype.path=function(e){var t,n=[];if(t=e instanceof DataObj?e:this.get(e,!1,!0),t&&n.push({ref:t.ref,presentation:t.presentation}),t&&this.metadata().hierarchical)for(;;){if(t=t.parent,t.empty())break;n.push({ref:t.ref,presentation:t.presentation})}return n},ChartOfCharacteristicManager._extend(CatManager),ChartOfAccountManager._extend(CatManager),DocManager._extend(RefDataManager),TaskManager._extend(CatManager),BusinessProcessManager._extend(CatManager),DataObj.prototype._getter=function(e){var t,n=this._metadata.fields[e].type,a=this._obj?this._obj[e]:"";return"type"==e&&"object"==typeof a?a:"ref"==e?a:n.is_ref?n.digits&&"number"==typeof a?a:n.hasOwnProperty("str_len")&&!$p.utils.is_guid(a)?a:(t=_md.value_mgr(this._obj,e,n))?$p.utils.is_data_mgr(t)?t.get(a,!1):$p.utils.fetch_type(a,t):a?(console.log([e,n,this._obj]),null):void 0:n.date_part?$p.utils.fix_date(this._obj[e],!0):n.digits?$p.utils.fix_number(this._obj[e],!n.hasOwnProperty("str_len")):"boolean"==n.types[0]?$p.utils.fix_boolean(this._obj[e]):this._obj[e]||""},DataObj.prototype.__setter=function(e,t){var n,a=this._metadata.fields[e].type;"type"==e&&t.types?this._obj[e]=t:"ref"==e?this._obj[e]=$p.utils.fix_guid(t):a.is_ref?a.digits&&"number"==typeof t||a.hasOwnProperty("str_len")&&"string"==typeof t&&!$p.utils.is_guid(t)?this._obj[e]=t:(this._obj[e]=$p.utils.fix_guid(t),n=_md.value_mgr(this._obj,e,a,!1,t),n?n instanceof EnumManager?"string"==typeof t?this._obj[e]=t:t?"object"==typeof t&&(this._obj[e]=t.ref||t.name||""):this._obj[e]="":t&&t.presentation?(!t.type||t instanceof DataObj||delete t.type,n.create(t)):$p.utils.is_data_mgr(n)||(this._obj[e]=$p.utils.fetch_type(t,n)):"object"!=typeof t&&(this._obj[e]=t)):a.date_part?this._obj[e]=$p.utils.fix_date(t,!0):a.digits?this._obj[e]=$p.utils.fix_number(t,!a.hasOwnProperty("str_len")):"boolean"==a.types[0]?this._obj[e]=$p.utils.fix_boolean(t):this._obj[e]=t},DataObj.prototype.__notify=function(e){this._data._silent||Object.getNotifier(this).notify({type:"update",name:e,oldValue:this._obj[e]})},DataObj.prototype._setter=function(e,t){this._obj[e]!=t&&(this.__notify(e),this.__setter(e,t),this._data._modified=!0)},DataObj.prototype._getter_ts=function(e){return this._ts_(e)},DataObj.prototype._setter_ts=function(e,t){var n=this._ts_(e);n instanceof TabularSection&&Array.isArray(t)&&n.load(t)},DataObj.prototype.__define({valueOf:{value:function(){return this.ref}},toJSON:{value:function(){return this._obj}},toString:{value:function(){return this.presentation}},_metadata:{get:function(){return this._manager.metadata()}},_deleted:{get:function(){return!!this._obj._deleted}},_modified:{get:function(){return!!this._data&&!!this._data._modified}},is_new:{value:function(){return this._data._is_new}},_set_loaded:{value:function(e){return this._manager.push(this,e),this._data._modified=!1,this._data._is_new=!1,this}},mark_deleted:{value:function(e){return this._obj._deleted=!!e,this.save(),this.__notify("_deleted"),this}},ref:{get:function(){return this._obj.ref},set:function(e){this._obj.ref=$p.utils.fix_guid(e)},enumerable:!0,configurable:!0},empty:{value:function(){return $p.utils.is_empty_guid(this._obj.ref)}},load:{value:function(){var e=function(){return e=null,this._data._modified=!1,this}.bind(this);return this.ref==$p.utils.blank.guid?(this instanceof CatObj?this.id="000000000":this.number_doc="000000000",Promise.resolve(this)):this._manager.cachable&&"e1cib"!=this._manager.cachable?$p.wsql.pouch.load_obj(this).then(e):_rest.load_obj(this).then(e)}},unload:{value:function(){var e,t=this._obj;this._manager.unload_obj(this.ref),this._observers&&(this._observers.length=0),this._notis&&(this._notis.length=0);for(e in this._metadata.tabular_sections)this[e].clear(!0);for(e in this)this.hasOwnProperty(e)&&delete this[e];for(e in t)delete t[e];["_ts_","_obj","_data"].forEach(function(e){delete this[e]}.bind(this)),e=t=null}},save:{value:function(e,t,n){if(this instanceof DocObj&&"boolean"==typeof e){var a=this.posted;this.posted=e}var i,s=this._manager.handle_event(this,"before_save"),o=function(){return s===!1?this instanceof DocObj&&"boolean"==typeof a&&this.posted!=a&&(this.posted=a):this._data._modified=!1,i=null,s=null,o=null,this}.bind(this);if(s===!1)return Promise.reject(o());if(s instanceof Promise||"object"==typeof s&&s.then)return s.then(o);if(this._metadata.hierarchical&&!this._obj.parent&&(this._obj.parent=$p.utils.blank.guid), -this instanceof DocObj||this instanceof TaskObj||this instanceof BusinessProcessObj?($p.utils.blank.date==this.date&&(this.date=new Date),this.number_doc||this.new_number_doc()):this.id||this.new_number_doc(),$p.msg&&$p.msg.show_msg)for(var r in this._metadata.fields)if(this._metadata.fields[r].mandatory&&!this._obj[r])return $p.msg.show_msg({title:$p.msg.mandatory_title,type:"alert-error",text:$p.msg.mandatory_field.replace("%1",this._metadata.fields[r].synonym)}),s=!1,Promise.reject(o());return i=this._manager.cachable&&"e1cib"!=this._manager.cachable?$p.wsql.pouch.save_obj:_rest.save_irest,i(this,{post:e,operational:t,attachments:n}).then(function(e){return e._manager.handle_event(e,"after_save")}).then(o)}},get_attachment:{value:function(e){return this._manager.get_attachment(this.ref,e)}},save_attachment:{value:function(e,t,n){return this._manager.save_attachment(this.ref,e,t,n).then(function(t){return this._attachments||(this._attachments={}),this._attachments[e]&&t.stub||(this._attachments[e]=t),t}.bind(this))}},delete_attachment:{value:function(e){return this._manager.delete_attachment(this.ref,e).then(function(t){return this._attachments&&delete this._attachments[e],t}.bind(this))}},_silent:{value:function(e){"boolean"==typeof e?this._data._silent=e:(this._data._silent=!0,setTimeout(function(){this._data._silent=!1}.bind(this)))}},print:{value:function(e,t){return this._manager.print(this,e,t)}}}),CatObj._extend(DataObj),CatObj.prototype.__define("id",{get:function(){return this._obj.id||""},set:function(e){this.__notify("id"),this._obj.id=e},enumerable:!0}),CatObj.prototype.__define("name",{get:function(){return this._obj.name||""},set:function(e){this.__notify("name"),this._obj.name=String(e)},enumerable:!0}),DocObj._extend(DataObj),DocObj.prototype.__define({posted:{get:function(){return this._obj.posted||!1},set:function(e){this.__notify("posted"),this._obj.posted=$p.utils.fix_boolean(e)},enumerable:!0}}),doc_props_date_number(DocObj.prototype),DataProcessorObj._extend(DataObj),TaskObj._extend(CatObj),doc_props_date_number(TaskObj.prototype),BusinessProcessObj._extend(CatObj),doc_props_date_number(BusinessProcessObj.prototype),EnumObj._extend(DataObj),EnumObj.prototype.__define({order:{get:function(){return this._obj.sequence},set:function(e){this._obj.sequence=parseInt(e)},enumerable:!0},name:{get:function(){return this._obj.ref},set:function(e){this._obj.ref=String(e)},enumerable:!0},synonym:{get:function(){return this._obj.synonym||""},set:function(e){this._obj.synonym=String(e)},enumerable:!0},presentation:{get:function(){return this.synonym||this.name}},empty:{value:function(){return!this.ref||"_"==this.ref}}}),RegisterRow._extend(DataObj),RegisterRow.prototype.__define({_metadata:{get:function(){var e=this._manager.metadata();return e.fields||(e.fields={}._mixin(e.dimensions)._mixin(e.resources)._mixin(e.attributes)),e}},ref:{get:function(){return this._manager.get_ref(this)},enumerable:!0},presentation:{get:function(){return this._metadata.obj_presentation||this._metadata.synonym}}}),TabularSection.prototype.toString=function(){return"Табличная часть "+this._owner._manager.class_name+"."+this._name},TabularSection.prototype.get=function(e){return this._obj[e]?this._obj[e]._row:null},TabularSection.prototype.count=function(){return this._obj.length},TabularSection.prototype.clear=function(e){for(var t in this._obj)delete this._obj[t];return this._obj.length=0,e||this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name}),this},TabularSection.prototype.del=function(e,t){var n,a=this._obj;if("undefined"!=typeof e){if("number"==typeof e)n=e;else if(a[e.row-1]._row===e)n=e.row-1;else for(var i in a)if(a[i]._row===e){n=Number(i),delete a[i]._row;break}void 0!=n&&(a.splice(n,1),a.forEach(function(e,t){e.row=t+1}),t||this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name}),this._owner._data._modified=!0)}},TabularSection.prototype.find=function(e,t){var n=$p._find(this._obj,e,t);if(n)return n._row},TabularSection.prototype.find_rows=function(e,t){var n=this,a=t?function(e){return t.call(n,e._row)}:null;return $p._find_rows.call(n,n._obj,e,a)},TabularSection.prototype.swap=function(e,t){var n=this._obj[e];this._obj[e]=this._obj[t],this._obj[t]=n,this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name})},TabularSection.prototype.add=function(e,t){var n=new($p[this._owner._manager.obj_constructor(this._name)])(this);e||(e={});for(var a in n._metadata.fields)n[a]=e[a]||"";return n._obj.row=this._obj.push(n._obj),n._obj.__define("_row",{value:n,enumerable:!1}),t||this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name}),e=null,this._owner._data._modified=!0,n},TabularSection.prototype.each=function(e){var t=this;t._obj.forEach(function(n){return e.call(t,n._row)})},TabularSection.prototype.forEach=TabularSection.prototype.each,TabularSection.prototype.group_by=function(e,t){try{var n=this.aggregate(e,t,"SUM",!0);return this.clear(!0).load(n)}catch(e){}},TabularSection.prototype.sort=function(e){"string"==typeof e&&(e=e.split(","));var t="select * from ? order by ",n=!0;e.forEach(function(e){e=e.trim().replace(/\s{1,}/g," ").split(" "),n?n=!1:t+=", ",t+="`"+e[0]+"`",e[1]&&(t+=" "+e[1])});try{return n=$p.wsql.alasql(t,[this._obj]),this.clear(!0).load(n)}catch(e){$p.record_log(e)}},TabularSection.prototype.aggregate=function(e,t,n,a){if("string"==typeof e&&(e=e.split(",")),"string"==typeof t&&(t=t.split(",")),n||(n="sum"),!e.length&&1==t.length&&"sum"==n)return this._obj.reduce(function(e,n,a,i){return e+n[t[0]]},0);var i,s=!0;t.forEach(function(e){i?i+=", "+n+"(`"+e+"`) `"+e+"`":i="select "+n+"(`"+e+"`) `"+e+"`"}),e.forEach(function(e){i?i+=", `"+e+"`":i="select `"+e+"`"}),i+=" from ? ",e.forEach(function(e){s?(i+="group by ",s=!1):i+=", ",i+="`"+e+"`"});try{return s=$p.wsql.alasql(i,[this._obj]),a||(s=1==t.length?s.length?s[0][t[0]]:0:s.length?s[0]:{}),s}catch(e){$p.record_log(e)}},TabularSection.prototype.load=function(e){var t,n=this;return n.clear(!0),e instanceof TabularSection?t=e._obj:Array.isArray(e)&&(t=e),t&&t.forEach(function(e){n.add(e,!0)}),this._owner._data._silent||Object.getNotifier(n._owner).notify({type:"rows",tabular:n._name}),n},TabularSection.prototype.sync_grid=function(e,t){for(var n={rows:[]},a=[],i=0;i<e.getColumnCount();i++)a.push(e.getColumnId(i));if(e.clearAll(),this.find_rows(t,function(e){var t=[];a.forEach(function(n){$p.utils.is_data_obj(e[n])?t.push(e[n].presentation):t.push(e[n])}),n.rows.push({id:e.row,data:t})}),e.objBox)try{e.parse(n,"json"),e.callEvent("onGridReconstructed",[])}catch(e){}},TabularSection.prototype.toJSON=function(){return this._obj},TabularSectionRow.prototype.__define("_metadata",{get:function(){return this._owner._owner._metadata.tabular_sections[this._owner._name]},enumerable:!1}),TabularSectionRow.prototype.__define("row",{get:function(){return this._obj.row||0},enumerable:!0}),TabularSectionRow.prototype.__define("_clone",{value:function(){return new($p[this._owner._owner._manager.obj_constructor(this._owner._name)])(this._owner)._mixin(this._obj)},enumerable:!1}),TabularSectionRow.prototype._getter=DataObj.prototype._getter,TabularSectionRow.prototype._setter=function(e,t){if(this._obj[e]!=t&&(t||this._obj[e]!=$p.utils.blank.guid)){if(this._owner._owner._data._silent||Object.getNotifier(this._owner._owner).notify({type:"row",row:this,tabular:this._owner._name,name:e,oldValue:this._obj[e]}),this._metadata.fields[e].choice_type){var n;n=2==this._metadata.fields[e].choice_type.path.length?this[this._metadata.fields[e].choice_type.path[1]]:this._owner._owner[this._metadata.fields[e].choice_type.path[0]],n&&n.type&&(t=$p.utils.fetch_type(t,n.type))}DataObj.prototype.__setter.call(this,e,t),this._owner._owner._data._modified=!0}};var _rest=$p.rest=new Rest;DataManager.prototype.__define("rest_name",{get:function(){var e=this.class_name.split("."),t={cat:"Catalog",doc:"Document",ireg:"InformationRegister",areg:"AccumulationRegister",cch:"ChartOfCharacteristicTypes",cacc:"ChartOfAccounts",tsk:"Task",bp:"BusinessProcess"};return t[e[0]]+"_"+_md.syns_1с(e[1])},enumerable:!1}),DataManager.prototype.rest_tree=function(e){var t,n,a=this,i=a.metadata(),s=[];return $p.ajax.default_attr(e,!i.irest&&$p.job_prm.rest?$p.job_prm.rest_url():$p.job_prm.irest_url()),e.url+=this.rest_name+"?allowedOnly=true&$format=json&$top=1000&$select=Ref_Key,DeletionMark,Parent_Key,Description&$filter=IsFolder eq true",$p.ajax.get_ex(e.url,e).then(function(e){return JSON.parse(e.response)}).then(function(e){for(var a=0;a<e.value.length;a++)n=e.value[a],t={ref:n.Ref_Key,_deleted:n.DeletionMark,parent:n.Parent_Key,presentation:n.Description},s.push(t);return $p.iface.data_to_tree(s)})},DataManager.prototype.rest_selection=function(e){if("get_tree"==e.action)return this.rest_tree(e);var t,n,a,i,s,o,r=this,l=r.metadata(),c=[],p=[];return s=function(){var e="$select=Ref_Key,DeletionMark";return l.form&&l.form.selection?l.form.selection.fields.forEach(function(e){c.push(e)}):r instanceof DocManager?(c.push("posted"),c.push("date"),c.push("number_doc")):r instanceof TaskManager?(c.push("name as presentation"),c.push("date"),c.push("number_doc"),c.push("completed")):r instanceof BusinessProcessManager?(c.push("date"),c.push("number_doc"),c.push("started"),c.push("finished")):(l.hierarchical&&l.group_hierarchy?c.push("is_folder"):c.push("0 as is_folder"),l.main_presentation_name?c.push("name as presentation"):l.code_length?c.push("id as presentation"):c.push("'...' as presentation"),l.has_owners&&c.push("owner"),l.code_length&&c.push("id")),c.forEach(function(t){var n;if(t.indexOf(" as ")!=-1)if(n=t.split(" as ")[0].split("."),1==n.length)t=n[0];else{if("_t_"!=n[0])return;t=n[1]}"0"!=t&&(a=_md.syns_1с(t),_md.get(r.class_name,t).type.is_ref&&a.indexOf("_Key")==-1&&_md.get(r.class_name,t).type.types.length&&_md.get(r.class_name,t).type.types[0].indexOf("enm.")==-1&&(a+="_Key"),e+=","+a)}),c.push("ref"),c.push("_deleted"),e}(),$p.ajax.default_attr(e,!l.irest&&$p.job_prm.rest?$p.job_prm.rest_url():$p.job_prm.irest_url()),e.url+=(l.irest&&l.irest.selection?l.irest.selection:this.rest_name)+"?allowedOnly=true&$format=json&$top=1000&"+s,_md.get(r.class_name,"date")&&(e.date_from||e.date_till)&&(e.url+="&$filter="+_rest.filter_date("Date",e.date_from,e.date_till),o=!0),l.hierarchical&&e.parent&&(e.url+=o?" and ":"&$filter=",e.url+="Parent_Key eq guid'"+e.parent+"'",o=!0),l.has_owners&&e.owner&&(e.url+=o?" and ":"&$filter=",e.url+="Owner_Key eq guid'"+e.owner+"'",o=!0),e.filter&&(e.url+=o?" and ":"&$filter=",e.url+="$filter eq '"+e.filter+"'",o=!0),$p.ajax.get_ex(e.url,e).then(function(e){return JSON.parse(e.response)}).then(function(s){for(var o=0;o<s.value.length;o++)n=s.value[o],t={},c.forEach(function(e){var s;if("ref"==e)return void(t[e]=n.Ref_Key);if(e.indexOf(" as ")!=-1?(s=e.split(" as ")[1],e=e.split(" as ")[0].split("."),e=e[e.length-1]):s=e,a=_md.syns_1с(e),i=_md.get(r.class_name,e))if(a.indexOf("_Key")==-1&&i.type.is_ref&&i.type.types.length&&i.type.types[0].indexOf("enm.")==-1&&(a+="_Key"),i.type.date_part)t[s]=$p.moment(n[a]).format($p.moment._masks[i.type.date_part]);else if(i.type.is_ref)if(n[a]&&n[a]!=$p.utils.blank.guid){var o=_md.value_mgr(t,e,i.type,!1,n[a]);o?t[s]=o.get(n[a]).presentation:t[s]=""}else t[s]="";else t[s]=n[a]}),p.push(t);return $p.iface.data_to_grid.call(r,p,e)})},InfoRegManager.prototype.rest_slice_last=function(e){e.period||(e.period=$p.utils.date_add_day(new Date,1));var t=this,n=t.metadata(),a="Period=datetime'"+$p.moment(e.period).format($p.moment._masks.iso)+"'",i="";for(var s in n.dimensions)if(void 0!==e[s]){var o=_md.syns_1с(s),r=n.dimensions[s];o.indexOf("_Key")==-1&&r.type.is_ref&&r.type.types.length&&r.type.types[0].indexOf("enm.")==-1?(o+="_Key",i&&(i+=" and "),i+=o+" eq guid'"+e[s].ref+"'"):(i&&(i+=" and "),i+=r.type.digits?o+" eq "+$p.utils.fix_number(e[s]):r.type.date_part?o+" eq datetime'"+$p.moment(e[s]).format($p.moment._masks.iso)+"'":o+" eq '"+e[s]+"'")}return i&&(a+=",Condition='"+i+"'"),$p.ajax.default_attr(e,$p.job_prm.rest_url()),e.url+=this.rest_name+"/SliceLast(%sl)?allowedOnly=true&$format=json&$top=1000".replace("%sl",a),_rest.ajax_to_data(e,t).then(function(e){return t.load_array(e)})},DataObj.prototype.to_atom=function(e){function t(e){var t=e._metadata.fields,i=e instanceof TabularSectionRow?"\n\t<d:":"\n<d:";for(n in t){if(a=t[n],r=_md.syns_1с(n),l=e[n],l instanceof EnumObj)l=l.empty()?"":l.name;else if(l instanceof DataObj)r.indexOf("_Key")==-1&&(r+="_Key"),l=l.ref;else if(a.type.date_part)l=l.getFullYear()<1e3?"0001-01-01T00:00:00Z":$p.moment(l).format($p.moment.defaultFormatUtc);else if(void 0==l)continue;p+=i+r+">"+l+"</d:"+r+">"}}var n,a,i,s,o,r,l,c='<entry><category term="StandardODATA.%n" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"/>\t\t\t\t\n<title type="text"/><updated>%d</updated><author/><summary/><content type="application/xml">\t\t\t\t\n<m:properties xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">\t\t\t%p\t\t\t\n</m:properties></content></entry>'.replace("%n",this._manager.rest_name).replace("%d",$p.moment().format($p.moment.defaultFormatUtc)),p="\n<d:Ref_Key>"+this.ref+"</d:Ref_Key>\n<d:DeletionMark>"+this._deleted+"</d:DeletionMark>";this instanceof DocObj?(p+="\n<d:Date>"+$p.moment(this.date).format($p.moment.defaultFormatUtc)+"</d:Date>",p+="\n<d:Number>"+this.number_doc+"</d:Number>"):(this._metadata.main_presentation_name&&(p+="\n<d:Description>"+this.name+"</d:Description>"),this._metadata.code_length&&(p+="\n<d:Code>"+this.id+"</d:Code>"),this._metadata.hierarchical&&this._metadata.group_hierarchy&&(p+="\n<d:IsFolder>"+this.is_folder+"</d:IsFolder>")),t(this);for(i in this._metadata.tabular_sections)o=this._metadata.tabular_sections[i],r="StandardODATA."+this._manager.rest_name+"_"+_md.syns_1с(i)+"_RowType",s=this[i],s.count()?(p+="\n<d:"+_md.syns_1с(i)+' m:type="Collection('+r+')">',s.each(function(e){p+='\n\t<d:element m:type="'+r+'">',p+="\n\t<d:LineNumber>"+e.row+"</d:LineNumber>",t(e),p+="\n\t</d:element>"}),p+="\n</d:"+_md.syns_1с(i)+">"):p+="\n<d:"+_md.syns_1с(i)+' m:type="Collection('+r+')" />';return c.replace("%p",p)},DataManager.prototype.__define({pouch_load_array:{value:function(e,t){var n={limit:e.length+1,include_docs:!0,keys:e.map(function(e){return this.class_name+"|"+e}.bind(this))};return t&&(n.attachments=!0,n.binary=!0),this.pouch_db.allDocs(n).then(function(e){return $p.wsql.pouch.load_changes(e,{})})}},pouch_load_view:{value:function(e){var t,n=this,a=[],i={limit:1e3,include_docs:!0,startkey:n.class_name+"|",endkey:n.class_name+"|￿"};return new Promise(function(s,o){function r(l,c){c?c.rows.length?(i.startkey=c.rows[c.rows.length-1].key,i.skip=1,c.rows.forEach(function(e){t=e.doc,key=t._id.split("|"),t.ref=key[1],a.push(t)}),n.load_array(a),a.length=0,n.pouch_db.query(e,i,r)):s():l&&o(l)}n.pouch_db.query(e,i,r)})}},pouch_db:{get:function(){return this.cachable.indexOf("_remote")!=-1?$p.wsql.pouch.remote[this.cachable.replace("_remote","")]:$p.wsql.pouch.local[this.cachable]||$p.wsql.pouch.remote[this.cachable]}},pouch_find_rows:{value:function(e){var t,n,a,i,s,o,r=this,l=[],c=0,p=0,d=0,u={limit:100,include_docs:!0,startkey:r.class_name+"|",endkey:r.class_name+"|￿"};return e&&(e._top?(s=e._top,delete e._top):s=300,e._raw&&(n=e._raw,delete e._raw),e._total_count&&(i=e._total_count,delete e._total_count),e._view&&(a=e._view,delete e._view),e._key&&("des"==e._key._order_by?(u.startkey=e._key.endkey||e._key+"￿",u.endkey=e._key.startkey||e._key,u.descending=!0):(u.startkey=e._key.startkey||e._key,u.endkey=e._key.endkey||e._key+"￿")),"number"==typeof e._skip&&(p=e._skip,delete e._skip),e._attachments&&(u.attachments=!0,u.binary=!0,delete e._attachments)),i&&(o=!0,i=0,Object.keys(e).length<=1&&e._key&&e._key.hasOwnProperty("_search"))?(u.include_docs=!1,u.limit=1e5,r.pouch_db.query(a,u).then(function(t){return t.rows.forEach(function(t){if(!e._key._search||t.key[t.key.length-1].toLowerCase().indexOf(e._key._search)!=-1){if(i++,p&&(d++,d<p))return;if(s&&(c++,c>s))return;l.push(t.id)}}),delete u.startkey,delete u.endkey,u.descending&&delete u.descending,u.keys=l,u.include_docs=!0,r.pouch_db.allDocs(u)}).then(function(e){return{rows:e.rows.map(function(e){var t=e.doc;return t.ref=t._id.split("|")[1],n||(delete t._id,delete t._rev),t}),_total_count:i}})):new Promise(function(f,m){function h(a,h){h?h.rows.length?(u.startkey=h.rows[h.rows.length-1].key,u.skip=1,h.rows.forEach(function(a){t=a.doc,key=t._id.split("|"),t.ref=key[1],n||(delete t._id,delete t._rev),$p._selection.call(r,t,e)&&(o&&i++,p&&(d++,d<p)||s&&(c++,c>s)||l.push(t))}),s&&c>s&&!o?f(n?l:r.load_array(l)):_()):f(o?{rows:n?l:r.load_array(l),_total_count:i}:n?l:r.load_array(l)):a&&m(a)}function _(){a?r.pouch_db.query(a,u,h):r.pouch_db.allDocs(u,h)}_()})}},pouch_selection:{value:function(e){var t,n,a,i=this,s=e.metadata||i.metadata(),o=["ref","_deleted"],r={_raw:!0,_total_count:!0,_top:e.count||30,_skip:e.start||0},l=[];if(s.form&&s.form.selection?s.form.selection.fields.forEach(function(e){o.push(e)}):i instanceof DocManager?(o.push("posted"),o.push("date"),o.push("number_doc")):i instanceof TaskManager?(o.push("name as presentation"),o.push("date"),o.push("number_doc"),o.push("completed")):i instanceof BusinessProcessManager?(o.push("date"),o.push("number_doc"),o.push("started"),o.push("finished")):(s.hierarchical&&s.group_hierarchy?o.push("is_folder"):o.push("0 as is_folder"),s.main_presentation_name?o.push("name as presentation"):s.code_length?o.push("id as presentation"):o.push("'...' as presentation"),s.has_owners&&o.push("owner"),s.code_length&&o.push("id")),_md.get(i.class_name,"date")&&(e.date_from||e.date_till)&&(e.date_from||(e.date_from=new Date("2015-01-01")),e.date_till||(e.date_till=$p.utils.date_add_day(new Date,1)),r.date={between:[e.date_from,e.date_till]}),s.hierarchical&&e.parent&&(r.parent=e.parent),e.selection)if(Array.isArray(e.selection))e.selection.forEach(function(e){for(a in e)"_"==a[0]&&"_view"!=a&&"_key"!=a||(r[a]=e[a])});else for(a in e.selection)"_"==a[0]&&"_view"!=a&&"_key"!=a||(r[a]=e.selection[a]);return r._key&&r._key._drop_date&&r.date&&delete r.date,!e.filter||r._key&&r._key._search||(1==s.input_by_string.length?r[s.input_by_string]={like:e.filter}:(r.or=[],s.input_by_string.forEach(function(t){var n={};n[t]={like:e.filter},r.or.push(n)}))),r._key&&r._key._order_by&&(r._key._order_by=e.direction),i.pouch_find_rows(r).then(function(s){return s.hasOwnProperty("_total_count")&&s.hasOwnProperty("rows")&&(e._total_count=s._total_count,s=s.rows),s.forEach(function(e){t={},o.forEach(function(s){if("ref"==s)return void(t[s]=e[s]);if(s.indexOf(" as ")!=-1?(a=s.split(" as ")[1],s=s.split(" as ")[0].split("."),s=s[s.length-1]):a=s,n=_md.get(i.class_name,s))if(n.type.date_part)t[a]=$p.moment(e[s]).format($p.moment._masks[n.type.date_part]);else if(n.type.is_ref)if(e[s]&&e[s]!=$p.utils.blank.guid){var o=_md.value_mgr(t,s,n.type,!1,e[s]);o?t[a]=o.get(e[s]).presentation:t[a]=""}else t[a]="";else"number"==typeof e[s]&&n.type.fraction_figits?t[a]=e[s].toFixed(n.type.fraction_figits):t[a]=e[s]}),l.push(t)}),$p.iface.data_to_grid.call(i,l,e)}).catch($p.record_log)}},pouch_tree:{value:function(e){return this.pouch_find_rows({is_folder:!0,_raw:!0,_top:e.count||300,_skip:e.start||0}).then(function(e){return e.sort(function(e,t){return e.parent==$p.utils.blank.guid&&t.parent!=$p.utils.blank.guid?-1:t.parent==$p.utils.blank.guid&&e.parent!=$p.utils.blank.guid?1:e.name<t.name?-1:e.name>t.name?1:0}),e.map(function(e){return{ref:e.ref,parent:e.parent,presentation:e.name}})}).then($p.iface.data_to_tree)}},save_attachment:{value:function(e,t,n,a){a||(a={type:"text/plain"}),n instanceof Blob||a.indexOf("text")!=-1||(n=new Blob([n],{type:a}));var i,s=this.pouch_db;return e=this.class_name+"|"+$p.utils.fix_guid(e),s.get(e).then(function(e){e&&(i=e._rev)}).catch(function(e){if(404!=e.status)throw e}).then(function(){return s.putAttachment(e,t,i,n,a)})}},get_attachment:{value:function(e,t){return this.pouch_db.getAttachment(this.class_name+"|"+$p.utils.fix_guid(e),t)}},delete_attachment:{value:function(e,t){var n,a=this.pouch_db;return e=this.class_name+"|"+$p.utils.fix_guid(e),a.get(e).then(function(e){e&&(n=e._rev)}).catch(function(e){if(404!=e.status)throw e}).then(function(){return a.removeAttachment(e,t,n)})}}}),DataObj.prototype.__define({new_number_doc:{value:function(e){if(this._metadata.code_length){e||(e=($p.current_acl&&$p.current_acl.prefix||"")+(this.organization&&this.organization.prefix?this.organization.prefix:$p.wsql.get_user_param("zone")+"-"));var t=this,n="",a=this.date instanceof Date?this.date.getFullYear():0,i=this._metadata.code_length-e.length;return"ram"==this._manager.cachable?Promise.resolve(this.new_cat_id(e)):t._manager.pouch_db.query("doc/number_doc",{limit:1,include_docs:!1,startkey:[t._manager.class_name,a,e+"￿"],endkey:[t._manager.class_name,a,e],descending:!0}).then(function(a){if(a.rows.length){for(var s=a.rows[0].key[2],o=s.length-1;o>0&&!isNaN(parseInt(s[o]));o--)n=s[o]+n;n=(parseInt(n||0)+1).toFixed(0)}else n="1";for(;n.length<i;)n="0"+n;return t instanceof DocObj||t instanceof TaskObj||t instanceof BusinessProcessObj?t.number_doc=e+n:t.id=e+n,t})}}},new_cat_id:{value:function(e){e||(e=($p.current_acl&&$p.current_acl.prefix||"")+(this.organization&&this.organization.prefix?this.organization.prefix:$p.wsql.get_user_param("zone")+"-"));var t=this._metadata.code_length-e.length,n=this instanceof DocObj||this instanceof TaskObj||this instanceof BusinessProcessObj?"number_doc":"id",a="",i=$p.wsql.alasql("select top 1 "+n+" as id from ? where "+n+" like '"+e+"%' order by "+n+" desc",[this._manager.alatable]);if(i.length){for(var s=i[0].id||"",o=s.length-1;o>0&&!isNaN(parseInt(s[o]));o--)a=s[o]+a;a=(parseInt(a||0)+1).toFixed(0)}else a="1";for(;a.length<t;)a="0"+a;return this[n]=e+a,this}}}),$p.iface.OBtnAuthSync=function(){function e(){$p.wsql.pouch.authorized?dhtmlx.confirm({title:$p.msg.log_out_title,text:$p.msg.logged_in+$p.wsql.pouch.authorized+$p.msg.log_out_break,cancel:$p.msg.cancel,callback:function(e){e&&$p.wsql.pouch.log_out()}}):$p.iface.frm_auth({modal_dialog:!0})}function t(e){e&&a?clearTimeout(a):i.forEach(function(t){e?t.buttons.sync.innerHTML='<i class="fa fa-refresh fa-spin md-fa-lg"></i>':$p.wsql.pouch.authorized?t.buttons.sync.innerHTML='<i class="fa fa-refresh md-fa-lg"></i>':t.buttons.sync.innerHTML='<i class="fa fa-ban md-fa-lg"></i>'}),a=e?setTimeout(t,3e3):0}function n(){i.forEach(function(e){$p.wsql.pouch.authorized?(e.buttons.auth.title="Отключиться от сервера",e.buttons.auth.innerHTML='<span class="span_user">'+$p.wsql.pouch.authorized+"</span>",e.buttons.sync.title="Синхронизация выполняется...",e.buttons.sync.innerHTML='<i class="fa fa-refresh md-fa-lg"></i>'):(e.buttons.auth.title="Войти на сервер и включить синхронизацию данных",e.buttons.auth.innerHTML=' <i class="fa fa-sign-in md-fa-lg"></i><span class="span_user">Вход...</span>',e.buttons.sync.title="Синхронизация не выполняется - пользователь не авторизован на сервере",e.buttons.sync.innerHTML='<i class="fa fa-ban md-fa-lg"></i>')})}var a,i=[];this.bind=function(t){return t.buttons.auth.onclick=e,t.buttons.sync.onclick=null,i.push(t),setTimeout(n),t},$p.on({pouch_load_data_start:function(e){$p.iface.sync||$p.iface.wnd_sync(),$p.iface.sync.create($p.eve.stepper),$p.eve.stepper.frm_sync.setItemValue("text_bottom","Читаем справочники"),e.hasOwnProperty("local_rows")&&e.local_rows<10?($p.eve.stepper.wnd_sync.setText("Первый запуск - подготовка данных"),$p.eve.stepper.frm_sync.setItemValue("text_processed","Загрузка начального образа")):($p.eve.stepper.wnd_sync.setText("Загрузка данных из IndexedDB"),$p.eve.stepper.frm_sync.setItemValue("text_processed","Извлечение начального образа")),t(!0)},pouch_load_data_page:function(e){if(t(!0),$p.eve.stepper.wnd_sync){var n=e.docs_written||e.page*e.limit;$p.eve.stepper.frm_sync.setItemValue("text_current","Обработано элементов: "+n+" из "+e.total_rows),$p.eve.stepper.frm_sync.setItemValue("text_bottom","Текущий запрос: "+e.page+" ("+(100*n/e.total_rows).toFixed(0)+"%)")}},pouch_change:function(e,n){t(!0)},pouch_load_data_loaded:function(e){$p.eve.stepper.wnd_sync&&(e.docs_written?$p.iface.sync.close():$p.iface.sync.close())},pouch_load_data_error:function(e){t(),$p.eve.stepper.wnd_sync&&$p.iface.sync.close()},log_in:function(e){n()},log_out:function(){n()}})};var eXcell_proto=new eXcell;eXcell_proto.input_keydown=function(e,t){function n(e){t.source.on_select&&t.source.on_select.call(t.source,e)}if(8===e.keyCode||46===e.keyCode)t.setValue(""),t.grid.editStop(),t.source.on_select&&t.source.on_select.call(t.source,"");else if(9===e.keyCode||13===e.keyCode)t.grid.editStop();else if(115===e.keyCode)t.cell.firstChild.childNodes[1].onclick(e);else if(113===e.keyCode)if(t.source.tabular_section){if(t.mgr=_md.value_mgr(t.source.row,t.source.col,t.source.row._metadata.fields[t.source.col].type),t.mgr){var a=t.source.row[t.source.col];t.mgr.form_obj(t.source.wnd,{o:a,on_select:n})}}else if(1==t.fpath.length&&(t.mgr=_md.value_mgr(t.source.o._obj,t.fpath[0],t.source.o._metadata.fields[t.fpath[0]].type),t.mgr)){var a=t.source.o[t.fpath[0]];t.mgr.form_obj(t.source.wnd,{o:a,on_select:n})}return $p.iface.cancel_bubble(e)},eXcell_ocombo.prototype=eXcell_proto,window.eXcell_ocombo=eXcell_ocombo,window.eXcell_ref=eXcell_ocombo,window.eXcell_refc=eXcell_ocombo,eXcell_pwd.prototype=eXcell_proto,window.eXcell_pwd=eXcell_pwd,dhtmlXCalendarObject.prototype._dateToStr=function(e,t){return e instanceof Date&&e.getFullYear()<1e3?"":window.dhx4.date2str(e,t||this._dateFormat,this._dateStrings())},eXcell_dhxCalendar.prototype.edit=function(){var e=this.grid.getPosition(this.cell);this.grid._grid_calendarA._show(!1,!1),this.grid._grid_calendarA.setPosition(e[0],e[1]+this.cell.offsetHeight),this.grid._grid_calendarA._last_operation_calendar=!1,this.grid.callEvent("onCalendarShow",[this.grid._grid_calendarA,this.cell.parentNode.idd,this.cell._cellIndex]),this.cell._cediton=!0,this.val=this.cell.val,this.val instanceof Date&&this.val.getFullYear()<1e3&&(this.val=new Date),this._val=this.cell.innerHTML;var t=this.grid._grid_calendarA.draw;this.grid._grid_calendarA.draw=function(){},this.grid._grid_calendarA.setDateFormat(this.grid._dtmask||"%d.%m.%Y"),this.grid._grid_calendarA.setDate(this.val||new Date),this.grid._grid_calendarA.draw=t},eXcell_dhxCalendar.prototype.setCValue=function(e,t){this.cell.innerHTML=e instanceof Date?this.grid._grid_calendarA._dateToStr(e):e,this.grid._grid_calendarA.getFormatedDate(this.grid._dtmask||"%d/%m/%Y",e).toString(),this.grid.callEvent("onCellChanged",[this.cell.parentNode.idd,this.cell._cellIndex,arguments.length>1?t:e])},function(){function e(e,t,n,a){if(n.indexOf("odata/standard.odata")!=-1||n.indexOf("/hs/rest")!=-1){var i,s;$p.ajax.authorized?(i=$p.ajax.username,s=$p.aes.Ctr.decrypt($p.ajax.password)):$p.job_prm.guest_name?(i=$p.job_prm.guest_name,s=$p.aes.Ctr.decrypt($p.job_prm.guest_pwd)):(i=$p.wsql.get_user_param("user_name"),s=$p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd"))),e.open(t,n,a,i,s),e.withCredentials=!0,e.setRequestHeader("Authorization","Basic "+btoa(unescape(encodeURIComponent(i+":"+s))))}else e.open(t,n,a)}dhx4.ajax._call=function(t,n,a,i,s,o,r){var l=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),c=null!=navigator.userAgent.match(/AppleWebKit/)&&null!=navigator.userAgent.match(/Qt/)&&null!=navigator.userAgent.match(/Safari/);if(1==i&&(l.onreadystatechange=function(){if(4==l.readyState||1==c&&3==l.readyState){if((200!=l.status||""==l.responseText)&&!dhx4.callEvent("onAjaxError",[{xmlDoc:l,filePath:n,async:i}]))return;window.setTimeout(function(){"function"==typeof s&&s.apply(window,[{xmlDoc:l,filePath:n,async:i}]),null!=o&&("undefined"!=typeof o.postData?dhx4.ajax.postLong(o.url,o.postData,s):dhx4.ajax.getLong(o.url,s)),s=null,l=null},1)}}),"GET"==t&&(n+=this._dhxr(n)),l.open(t,n,i),e(l,t,n,i),null!=r)for(var p in r)l.setRequestHeader(p,r[p]);else"POST"==t||"PUT"==t||"DELETE"==t?l.setRequestHeader("Content-Type","application/x-www-form-urlencoded"):"GET"==t&&(a=null);return l.setRequestHeader("X-Requested-With","XMLHttpRequest"),l.send(a),1!=i&&(4==l.readyState||1==c&&3==l.readyState)&&(200==l.status&&""!=l.responseText||dhx4.callEvent("onAjaxError",[{xmlDoc:l,filePath:n,async:i}])),{xmlDoc:l,filePath:n,async:i}},dhtmlx.ajax.prototype.send=function(t,n,a){var i=this.getXHR();if("function"==typeof a&&(a=[a]),"object"==typeof n){var s=[];for(var o in n){var r=n[o];null!==r&&r!==dhtmlx.undefined||(r=""),s.push(o+"="+encodeURIComponent(r))}n=s.join("&")}n&&!this.post&&(t=t+(t.indexOf("?")!=-1?"&":"?")+n,n=null),e(i,this.post?"POST":"GET",t,!this._sync),this.post&&i.setRequestHeader("Content-type","application/x-www-form-urlencoded");var l=this;return i.onreadystatechange=function(){if(!i.readyState||4==i.readyState){if(a&&l)for(var e=0;e<a.length;e++)a[e]&&a[e].call(l.master||l,i.responseText,i.responseXML,i);l.master=null,a=l=null}},i.send(n||null),i}}(),dhtmlXCellObject.prototype.is_visible=function(){var e=this.cell.getBoundingClientRect();return e.right>0&&e.bottom>0},$p.iface.data_to_grid=function(e,t){function n(e){var t;return t=e.hasOwnProperty("posted")?e.posted?"cell_doc_posted":"cell_doc":e.is_folder?"cell_ref_folder":"cell_ref_elm",e._deleted&&(t+="_deleted"),t}function a(e){return e instanceof Date?e.getHours()||e.getMinutes()?$p.moment(e).format($p.moment._masks.date_time):$p.moment(e).format($p.moment._masks.date):"number"==typeof e?e:$p.iface.normalize_xml(e||"")}if(this.data_to_grid)return this.data_to_grid(e,t);var i="<?xml version='1.0' encoding='UTF-8'?><rows total_count='%1' pos='%2' set_parent='%3'>".replace("%1",t._total_count||e.length).replace("%2",t.start).replace("%3",t.set_parent||""),s=this.caption_flds(t);return i+=s.head,e.forEach(function(e){i+='<row id="'+e.ref+'"><cell class="'+n(e)+'">'+a(e[s.acols[0].id])+"</cell>";for(var t=1;t<s.acols.length;t++)i+="<cell>"+a(e[s.acols[t].id])+"</cell>";i+="</row>"}),i+"</rows>"},$p.iface.data_to_tree=function(e){function t(n,a){var i={id:a.ref,text:a.presentation,items:[]};n.push(i),$p._find_rows(e,{parent:a.ref},function(e){t(i.items,e)}),i.items.length||delete i.items}var n=[{id:$p.utils.blank.guid,text:"..."}];return $p._find_rows(e,{parent:$p.utils.blank.guid},function(e){t(n,e)}),n},$p.iface.ODropdownList=ODropdownList,dhtmlXCellObject.prototype.attachDynTree=function(e,t,n){this.setCollapsedText&&this.setCollapsedText("Дерево"),t||(t={is_folder:!0});var a=this.attachTreeView();return a.__define({filter:{get:function(){},set:function(e){t=e},enumerable:!1,configurable:!1}}),setTimeout(function(){e.sync_grid({action:"get_tree",filter:t},a).then(function(e){n&&n(e)})}),a},OCombo._extend(dhtmlXCombo),$p.iface.OCombo=OCombo,$p.iface.select_from_list=function(e,t){return new Promise(function(n,a){function i(e){"cancel"!=e&&(s=c.getSelectedRowId()),l.close()}Array.isArray(e)&&e.length?1==e.length&&n(e[0]):n(void 0);var s,o,r={name:"wnd_select_from_list",wnd:{id:"wnd_select_from_list",width:300,height:300,modal:!0,center:!0,caption:$p.msg.select_from_list,allow_close:!0,on_close:function(){return s&&n(e[parseInt(s)-1]),!0}}},l=$p.iface.dat_blank(null,r.wnd),c=l.attachGrid(),p=l.attachToolbar({items:[{id:"select",type:"button",text:$p.msg.select_from_list},{id:"cancel",type:"button",text:"Отмена"}],onClick:i});c.setIconsPath(dhtmlx.image_path),c.setImagePath(dhtmlx.image_path),c.setHeader($p.msg.value),c.setColTypes("ro"),c.enableAutoWidth(!0,1200,600),c.attachEvent("onRowDblClicked",i),c.enableMultiselect(!!t),c.setNoHeader(!0),c.init(),p.addSpacer("select"),l.hideHeader(),l.cell.offsetParent.querySelector(".dhxwin_brd").style.border="none",e.forEach(function(e,t){ -var n;n="object"==typeof e?e.presentation||e.text||e.toString():e.toString(),c.addRow(1+t,n),e.selected&&(o=1+t)}),o&&c.selectRowById(o)})},$p.iface.ODateRangePicker=ODateRangePicker,dhtmlXCellObject.prototype.attachHeadFields=function(e){function t(e){if(a)u.entBox&&!u.entBox.parentElement?setTimeout(u.destructor):e.forEach(function(e){"unload"==e.type?d&&d.close?d.close():u.destructor():u.forEachRow(function(t){t==e.name&&u.cells(t,1).setValue(a[e.name])})});else{var i=[];e.forEach(function(e){i.indexOf[e.object]==-1&&(i.push(e.object),Object.unobserve(e.object,t),c&&c instanceof TabularSection&&Object.unobserve(e.object,n))}),i=null}}function n(t){var n;t.forEach(function(t){!n&&u.clearAll&&l==t.tabular&&(n=!0,u.clearAll(),u.parse(o.get_property_grid_xml(i,a,{title:e.ts_title,ts:l,selection:r,metadata:s}),function(){},"xml"))})}var a,i,s,o,r,l,c,p,d=this,u=d.attachGrid(),f=u.destructor;return new dhtmlXPropertyGrid(u),u.setInitWidthsP("40,60"),u.setDateFormat("%d.%m.%Y %H:%i"),u.init(),u.setSizes(),u.attachEvent("onPropertyChanged",function(e,t,n){if(e||u&&u.getSelectedRowId())return p.on_select(t)}),u.attachEvent("onCheckbox",function(e,t,n){return void 0!=a[e]?p.on_select(n,{obj:a,field:e}):e.split("|").length>1?p.on_select(n,u.get_cell_field(e)):void 0}),u.attachEvent("onKeyPress",function(e,t,n){switch(e){case 13:case 9:u.editStop&&u.editStop();break;case 46:}}),e.read_only&&u.setEditable(!1),u.__define({selection:{get:function(){return r},set:function(e){r=e,this.reload()}},reload:{value:function(){n([{tabular:l}])}},get_cell_field:{value:function(e){if(a){var t={row_id:e||u.getSelectedRowId()},n=t.row_id.split("|");if(n.length<2)return{obj:a,field:n[0]}._mixin(p);var i;return r?a[n[0]].find_rows(r,function(e){if(e.property==n[1]||e.param==n[1]||e.Свойство==n[1]||e.Параметр==n[1])return i=e,!1}):i=a[n[0]].find(n[1]),i?(t.obj=i,i["Значение"]?(t.field="Значение",t.property=i.Свойство||i.Параметр):(t.field="value",t.property=i.property||i.param),t._mixin(p)):void 0}},enumerable:!1},_obj:{get:function(){return a}},_owner_cell:{get:function(){return d}},destructor:{value:function(){a&&Object.unobserve(a,t),c&&c instanceof TabularSection&&Object.unobserve(c,n),a=null,c=null,s=null,o=null,p=null,f.call(u)}},attach:{value:function(e){a&&Object.unobserve(a,t),c&&c instanceof TabularSection&&Object.unobserve(a,n),e.oxml&&(i=e.oxml),e.selection&&(r=e.selection),a=e.obj,s=e.metadata||a._metadata.fields,o=a._manager,l=e.ts||"",c=l?a[l]:a.extra_fields||a["ДополнительныеРеквизиты"],c&&!l&&(l=a.extra_fields?"extra_fields":"ДополнительныеРеквизиты"),p={on_select:function(e,t){if(t||(t=u.get_cell_field()),t){var n=o.handle_event(a,"value_change",{field:t.field,value:e,tabular_section:t.row_id?l:"",grid:u,cell:u.cells(t.row_id||t.field,1),wnd:p.pwnd});return"boolean"!=typeof n&&(t.obj[t.field]=e,n=!0),n}},pwnd:e.pwnd||d},Object.observe(a,t,["update","unload"]),c&&c instanceof TabularSection&&Object.observe(a,n,["row","rows"]),l&&!e.ts_title&&(e.ts_title=a._metadata.tabular_sections[l].synonym),n([{tabular:l}])}}}),e&&u.attach(e),u},dhtmlXGridObject.prototype.get_cell_value=function(){var e=this.get_cell_field();if(e&&e.obj)return e.obj[e.field]},dhtmlXCellObject.prototype.attachTabular=function(e){function t(e){var t=m.getSelectedRowId();return t&&!isNaN(Number(t))?Number(t)-1:void(e||$p.msg.show_msg({type:"alert-warning",text:$p.msg.no_selected_row.replace("%1",o._metadata.tabular_sections[r].synonym||r),title:(o._metadata.obj_presentation||o._metadata.synonym)+": "+o.presentation}))}function n(e,t,n,a,i){if(2!=e||a==i)return!0;var s=m.get_cell_field(),l=c.handle_event(o,"value_change",{field:s.field,value:a,tabular_section:r,grid:m,row:s.obj,cell:t&&n?m.cells(t,n):m.getSelectedCellIndex()>=0?m.cells():null,wnd:g.pwnd});return"boolean"!=typeof l&&(s.obj[s.field]=a,l=!0),l}function a(e){m.clearAll&&e.some(function(e){if("rows"==e.type&&e.tabular==r)return l.sync_grid(m,f),!0})}function i(e){if(e.length>20)try{l.sync_grid(m,f)}catch(e){}else e.forEach(function(e){r==e.tabular&&(e.row&&m.getSelectedRowId()==e.row.row?void 0!=m.getColIndexById(e.name)&&m.cells(e.row.row,m.getColIndexById(e.name)).setCValue($p.utils.is_data_obj(e.row[e.name])?e.row[e.name].presentation:e.row[e.name]):l.sync_grid(m,f))})}function s(e){if(e.clipboardData.types.indexOf("text/plain")!=-1)try{$p.eve.callEvent("tabular_paste",[{obj:o,grid:m,tsname:r,e:e,data:e.clipboardData.getData("text/plain")}])}catch(e){return}}var o=e.obj,r=e.ts,l=o[r],c=o._manager,p=e.metadata||c.metadata().tabular_sections[r].fields,d=this,u=e.ts_captions||{},f=e.selection;if(e.ts_captions||_md.ts_captions(c.class_name,r,u)){var m=this.attachGrid(),h=this.attachToolbar(),_=m.destructor,g={on_select:function(e){n(2,null,null,e)},pwnd:e.pwnd||d,is_tabular:!0};return m.setDateFormat("%d.%m.%Y %H:%i"),m.enableAccessKeyMap(),m._add_row=function(){if(!e.read_only){var t;if(f)for(var n in f)p[n]&&("object"!=typeof f[n]||$p.is_data_obj(f[n]))&&(t||(t={}),t[n]=f[n]);var a=l.add(t);if(c.handle_event(o,"add_row",{tabular_section:r,grid:m,row:a,wnd:g.pwnd})===!1)return;setTimeout(function(){m.selectRowById(a.row)},100)}},m._del_row=function(){if(!e.read_only){var n=t();if(void 0!=n){if(c.handle_event(o,"del_row",{tabular_section:r,grid:m,row:n,wnd:g.pwnd})===!1)return;l.del(n),setTimeout(function(){m.selectRowById(n<l.count()?n+1:n)},100)}}},h.setIconsPath(dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()),h.loadStruct(e.toolbar_struct||$p.injected_data["toolbar_add_del.xml"],function(){this.attachEvent("onclick",function(e){switch(e){case"btn_add":m._add_row();break;case"btn_delete":m._del_row()}})}),m.setIconsPath(dhtmlx.image_path),m.setImagePath(dhtmlx.image_path),m.setHeader(u.headers),u.min_widths&&m.setInitWidths(u.widths),u.min_widths&&m.setColumnMinWidth(u.min_widths),u.aligns&&m.setColAlign(u.aligns),m.setColSorting(u.sortings),m.setColTypes(u.types),m.setColumnIds(u.fields.join(",")),m.enableAutoWidth(!0,1200,600),m.enableEditTabOnly(!0),m.init(),e.read_only&&(m.setEditable(!1),h.forEachItem(function(e){["btn_add","btn_delete"].indexOf(e)!=-1&&h.disableItem(e)})),m.__define({selection:{get:function(){return f},set:function(e){f=e,a([{tabular:r,type:"rows"}])}},destructor:{value:function(){o&&(Object.unobserve(o,i),Object.unobserve(o,a)),o=null,l=null,p=null,c=null,g=null,d.detachToolbar(),m.entBox.removeEventListener("paste",s),_.call(m)}},get_cell_field:{value:function(){if(l){var e,n,a=t(!0),i=m.getSelectedCellIndex();if(void 0!=a?e=l.get(a):m._last&&(e=l.get(m._last.row)),i>=0?n=m.getColumnId(i):m._last&&(n=m.getColumnId(m._last.cindex)),e&&n)return{obj:e,field:n,metadata:p[n]}._mixin(g)}}},refresh_row:{value:function(e){m.selectRowById(e.row),m.forEachCell(e.row,function(t,n){var a=e[m.getColumnId(n)];t.setCValue($p.utils.is_data_obj(a)?a.presentation:a)})}}}),m.attachEvent("onEditCell",n),m.attachEvent("onRowSelect",function(e,t){l&&(m._last={row:e-1,cindex:t})}),a([{tabular:r,type:"rows"}]),Object.observe(o,i,["row"]),Object.observe(o,a,["rows"]),m.entBox.addEventListener("paste",s),m}},$p.iface.Toolbar_filter=function(e){function t(){i&&clearTimeout(i),i=setTimeout(function(){i&&a.call_event()},500)}function n(e,t){"min"==t?a.сalendar.setSensitiveRange(e.value,null):a.сalendar.setSensitiveRange(null,e.value)}var a=this,i=0,s="desktop"==$p.job_prm.device_type?300:120,o={};e.pos||(e.pos=6),a.__define({custom_selection:{get:function(){return o},enumerable:!1,configurable:!1},toolbar:{get:function(){return e.toolbar},enumerable:!1,configurable:!1},call_event:{value:function(){i&&(clearTimeout(i),i=0),e.onchange.call(a,a.get_filter())}}}),a.toolbar.addText("div_filter",e.pos,""),a.div=a.toolbar.objPull[a.toolbar.idPrefix+"div_filter"],e.pos++,(e.manager instanceof DocManager||e.manager instanceof BusinessProcessManager||e.manager instanceof TaskManager||e.period)&&(s="desktop"==$p.job_prm.device_type?180:120,a.toolbar.addInput("input_date_from",e.pos,"","desktop"==$p.job_prm.device_type?80:72),e.pos++,a.toolbar.addText("lbl_date_till",e.pos,"-"),e.pos++,a.toolbar.addInput("input_date_till",e.pos,"","desktop"==$p.job_prm.device_type?80:72),e.pos++,a.input_date_from=a.toolbar.getInput("input_date_from"),a.input_date_from.onclick=function(){n(a.input_date_till,"max")},a.input_date_till=a.toolbar.getInput("input_date_till"),a.input_date_till.onclick=function(){n(a.input_date_from,"min")},a.сalendar=new dhtmlXCalendarObject([a.input_date_from,a.input_date_till]),a.сalendar.attachEvent("onclick",a.call_event),e.date_from||(e.date_from=new Date((new Date).getFullYear().toFixed()+"-01-01")),e.date_till||(e.date_till=$p.utils.date_add_day(new Date,1)),a.input_date_from.value=$p.moment(e.date_from).format("L"),a.input_date_till.value=$p.moment(e.date_till).format("L"),"doc"!=e.manager.cachable||e.custom_selection||(o._view={get value(){return"doc/by_date"}},o._key={get value(){var t=a.get_filter(!0);return{startkey:[e.manager.class_name,t.date_from.getFullYear(),t.date_from.getMonth()+1,t.date_from.getDate()],endkey:[e.manager.class_name,t.date_till.getFullYear(),t.date_till.getMonth()+1,t.date_till.getDate()],_drop_date:!0,_order_by:!0,_search:t.filter.toLowerCase()}}})),e.hide_filter?a.input_date_till?a.toolbar.addSpacer("input_date_till"):a.toolbar.addSpacer("div_filter"):(a.toolbar.addSeparator("filter_sep",e.pos),e.pos++,a.toolbar.addInput("input_filter",e.pos,"",s),a.input_filter=a.toolbar.getInput("input_filter"),a.input_filter.onchange=a.call_event,a.input_filter.onclick=function(){var e=a.input_filter.value;setTimeout(function(){e!=a.input_filter.value&&a.call_event()})},a.input_filter.onkeydown=t,a.input_filter.type="search",a.input_filter.setAttribute("placeholder","Фильтр"),a.toolbar.addSpacer("input_filter"))},$p.iface.Toolbar_filter.prototype.__define({get_filter:{value:function(e){var t,n,a={date_from:this.input_date_from?$p.utils.date_add_day(dhx4.str2date(this.input_date_from.value),0,!0):"",date_till:this.input_date_till?$p.utils.date_add_day(dhx4.str2date(this.input_date_till.value),1,!0):"",filter:this.input_filter?this.input_filter.value:""};if(!e)for(t in this.custom_selection)a.selection||(a.selection=[]),n={},n[t]=this.custom_selection[t].value,a.selection.push(n);return a}},add_filter:{value:function(e){var t=this.toolbar.getPosition("input_filter")-2,n=dhx4.newId(),a=(this.toolbar.getWidth("input_filter")/2).round(0);this.toolbar.setWidth("input_filter",a),this.toolbar.addText("lbl_"+n,t,e.text||""),t++,this.toolbar.addInput("input_"+n,t,"",a),this.custom_selection[e.name]=this.toolbar.getInput("input_"+n)}}}),$p.iface.dat_blank=function(e,t){t||(t={});var n,a=(e||$p.iface.w).createWindow({id:dhx4.newId(),left:t.left||700,top:t.top||20,width:t.width||220,height:t.height||300,move:!0,park:!t.allow_close,center:!!t.center,resize:!0,caption:t.caption||"Tools"}),i={x:(e||$p.iface.w).vp.clientWidth,y:(e||$p.iface.w).vp.clientHeight};return a.getPosition()[0]+a.getDimension()[0]>i.x?(i.x=i.x-a.getDimension()[0],n=!0):i.x=a.getPosition()[0],a.getPosition()[1]+a.getDimension()[1]>i.y?(i.y=i.y-a.getDimension()[1],n=!0):i.y=a.getPosition()[1],n&&(i.x<0||i.y<0?a.maximize():a.setPosition(i.x,i.y)),e=null,t.hasOwnProperty("allow_minmax")&&!t.allow_minmax&&a.button("minmax").hide(),t.allow_close?a.button("park").hide():a.button("close").hide(),a.attachEvent("onClose",function(){var e="function"!=typeof t.on_close||t.on_close(a);if(e)return t.pwnd_modal&&t.pwnd&&t.pwnd.setModal&&t.pwnd.setModal(1),e}),a.setIconCss("without_icon"),a.cell.parentNode.children[1].classList.add("dat_gui"),$p.iface.bind_help(a,t.help_path),a.elmnts={grids:{}},a.wnd_options=function(e){var t=a.getPosition(),n=a.getDimension(),i=a.isParked();e.left=t[0],e.top=t[1],e.width=n[0],e.parked=i,i||(e.height=n[1])},a.bottom_toolbar=function(e){var t={wrapper:a.cell,width:"100%",height:"28px",bottom:"0px",left:"0px",name:"tb_bottom",buttons:[{name:"btn_cancel",text:"Отмена",title:"Закрыть без сохранения",width:"60px",float:"right"},{name:"btn_ok",b:"Ок",title:"Применить изменения",width:"30px",float:"right"}],onclick:function(e){return!1}}._mixin(e),n=new OTooolBar(t),i=a.attachStatusBar({height:12});return i.style.zIndex=-1e3,i.firstChild.style.backgroundColor="transparent",i.firstChild.style.border="none",n},t.modal&&(t.pwnd&&t.pwnd.setModal&&(t.pwnd_modal=t.pwnd.isModal(),t.pwnd.setModal(0)),a.setModal(1)),a},$p.iface.pgrid_on_select=function(e){if(void 0!==e){var t=this.grid instanceof dhtmlXGridObject?this.grid:this,n=t.getUserData("","source"),a=t.getSelectedRowId();if(void 0!=n.o[a])"number"==typeof n.o[a]?n.o[a]=$p.utils.fix_number(e,!0):n.o[a]=e;else if(a.indexOf("fprms")>-1){var i=$p._find(n.o.fprms,a.split("|")[1]);i.value=e}t.cells().setValue($p.utils.is_data_obj(e)?e.presentation:e||""),n.grid_on_change&&n.grid_on_change.call(t,a,e)}},$p.iface.pgrid_on_change=function(e,t,n){e&&$p.iface.pgrid_on_select.call(this,t)},$p.iface.pgrid_on_checkbox=function(e,t,n){var a=this.grid instanceof dhtmlXGridObject?this.grid:this,i=a.getUserData("","source");void 0!=i.o[e]&&(i.o[e]=n),i.grid_on_change&&i.grid_on_change(e,n)},$p.iface.frm_auth=function(e,t,n){function a(n,a){$p.ajax.username=n,$p.ajax.password=$p.aes.Ctr.encrypt(a),n?($p.wsql.get_user_param("user_name")!=n&&$p.wsql.set_user_param("user_name",n),$p.wsql.pouch.log_in(n,a).then(function(){$p.wsql.get_user_param("enable_save_pwd")?$p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd"))!=a&&$p.wsql.set_user_param("user_pwd",$p.aes.Ctr.encrypt(a)):""!=$p.wsql.get_user_param("user_pwd")&&$p.wsql.set_user_param("user_pwd",""),$p.eve.logged_in=!0,e.modal_dialog?s.close():t&&t()}).catch(function(e){l=!0,o.onerror(e)}).then(function(){$p.iface.sync&&$p.iface.sync.close(),s&&s.progressOff&&(s.progressOff(),!l&&e.hide_header&&s.hideHeader()),$p.iface.cell_tree&&!l&&$p.iface.cell_tree.expand()})):this.validate()}function i(e){if(l=!1,this.resetValidateCss(),"guest"==this.getCheckedValue("type")){var t=this.getItemValue("guest"),n="";$p.job_prm.guests&&$p.job_prm.guests.length&&$p.job_prm.guests.some(function(e){if(e.username==t)return n=$p.aes.Ctr.decrypt(e.password),!0}),a.call(this,t,n)}else"auth"==this.getCheckedValue("type")&&a.call(this,this.getItemValue("login"),this.getItemValue("password"))}e||(e={});var s,o,r,l;e.modal_dialog?(e.options||(e.options={name:"frm_auth",caption:"Вход на сервер",width:360,height:300,center:!0,allow_close:!0,allow_minmax:!0,modal:!0}),s=$p.iface.dat_blank(e._dxw,e.options),s.attachEvent("onClose",function(e){return l?n&&n(err):t&&t(),!0}),o=s.attachForm()):(s=e.cell||$p.iface.docs,o=$p.iface.auth=s.attachForm(),$p.msg.show_msg($p.msg.init_login,s)),o.loadStruct($p.injected_data["form_auth.xml"],function(){var t;if($p.job_prm.guests&&$p.job_prm.guests.length){var n=$p.job_prm.guests.map(function(e){var n={text:e.username,value:e.username};return $p.wsql.get_user_param("user_name")==e.username&&(n.selected=!0,t=e.username),n});t||(n[0].selected=!0,t=n[0].value),o.reloadOptions("guest",n)}$p.wsql.get_user_param("user_name")&&$p.wsql.get_user_param("user_name")!=t&&(o.setItemValue("login",$p.wsql.get_user_param("user_name")),o.setItemValue("type","auth"),$p.wsql.get_user_param("enable_save_pwd")&&$p.wsql.get_user_param("user_pwd")&&o.setItemValue("password",$p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd")))),e.modal_dialog||((r=((s.getWidth?s.getWidth():s.cell.offsetWidth)-500)/2)>=10?o.cont.style.paddingLeft=r.toFixed()+"px":o.cont.style.paddingLeft="20px"),setTimeout(function(){dhx4.callEvent("on_draw_auth",[o]),($p.wsql.get_user_param("autologin")||e.try_auto)&&(t||$p.wsql.get_user_param("user_name")&&$p.wsql.get_user_param("user_pwd"))&&i.call(o)})}),o.attachEvent("onButtonClick",i),o.attachEvent("onKeyDown",function(e,t,n,a){13==t.keyCode&&("password"!=n&&"guest"!=this.getCheckedValue("type")||i.call(this))}),o.onerror=function(e){$p.ajax.authorized=!1;var t=e.message.toLowerCase();t.indexOf("auth")!=-1?($p.msg.show_msg({title:$p.msg.main_title+$p.version,type:"alert-error",text:$p.msg.error_auth}),o.setItemValue("password",""),o.validate()):t.indexOf("gateway")==-1&&t.indexOf("net")==-1||$p.msg.show_msg({title:$p.msg.main_title+$p.version,type:"alert-error",text:$p.msg.error_network})}},$p.iface.open_settings=function(e){var t=e||("undefined"!=typeof event?event:void 0);t&&t.preventDefault();var n=$p.job_prm.parse_url();return $p.iface.set_hash(n.obj,n.ref,n.frm,"settings"),$p.iface.cancel_bubble(t)},$p.iface.swith_view=function(e){var t,n=$p.iface,a=function(e){function t(e,t){return e.text>t.text?1:e.text<t.text?-1:void 0}if(n.tree){if(n.tree._view!=e&&["rep","cal"].indexOf(e)==-1){if(n.tree.deleteChildItems(0),"oper"==e){var a,i,s={id:0,item:[{id:"oper_cat",text:$p.msg.meta_cat,open:!0,item:[]},{id:"oper_doc",text:$p.msg.meta_doc,item:[]},{id:"oper_cch",text:$p.msg.meta_cch,item:[]},{id:"oper_cacc",text:$p.msg.meta_cacc,item:[]},{id:"oper_tsk",text:$p.msg.meta_tsk,item:[]}]},o=s.item[0].item;for(a in $p.cat)"function"!=typeof $p.cat[a]&&(i=$p.cat[a].metadata(),i.hide||o.push({id:"oper.cat."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),o=s.item[1].item;for(a in $p.doc)"function"!=typeof $p.doc[a]&&(i=$p.doc[a].metadata(),i.hide||o.push({id:"oper.doc."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),o=s.item[2].item;for(a in $p.cch)"function"!=typeof $p.cch[a]&&(i=$p.cch[a].metadata(),i.hide||o.push({id:"oper.cch."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),o=s.item[3].item;for(a in $p.cacc)"function"!=typeof $p.cacc[a]&&(i=$p.cacc[a].metadata(),i.hide||o.push({id:"oper.cacc."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),o=s.item[4].item;for(a in $p.tsk)"function"!=typeof $p.tsk[a]&&(i=$p.tsk[a].metadata(),i.hide||o.push({id:"oper.tsk."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),n.tree.parse(s,function(){var e=$p.job_prm.parse_url();e.obj&&n.tree.selectItem(e.view+"."+e.obj,!0)},"json")}else n.tree.loadXML(n.tree.tree_filteres,function(){});n.tree._view=e}}else{var r=$p.job_prm.parse_url();if(r.obj){var l=r.obj.split(".");if(l.length>1){var c=$p.md.mgr_by_class_name(r.obj);"function"==typeof n.docs.close&&n.docs.close(),c&&c.form_list(n.docs,{})}}}};return 0==e.indexOf(n.docs.getViewName())?n.docs.getViewName():(t=n.docs.showView(e),1==t&&("cal"!=e||window.dhtmlXScheduler||($p.load_script("dist/dhtmlxscheduler.min.js","script",function(){scheduler.config.first_hour=8,scheduler.config.last_hour=22,n.docs.scheduler=n.docs.attachScheduler(new Date("2015-11-20"),"week","scheduler_here"),n.docs.scheduler.attachEvent("onBeforeViewChange",function(e,t,n,a){return"timeline"!=n||($p.msg.show_not_implemented(),!1)})}),$p.load_script("dist/dhtmlxscheduler.css","link"))),a(e),void("def"==e?n.main.showStatusBar():n.main.hideStatusBar()))},$p.iface.OTooolBar=OTooolBar,$p.iface.add_button=function(e,t,n){var a=document.createElement("div"),i="";return a.name=(t?t.name+"_":"")+n.name,e.appendChild(a),a.className=0==n.name.indexOf("sep_")?"md_otooolbar_sep":"md_otooolbar_button",n.hasOwnProperty("class_name")&&a.classList.add(n.class_name),n.img&&(i='<img src="'+(t?t.image_path:"")+n.img+'">'),n.b?i+='<b style="vertical-align: super;"> '+n.b+"</b>":n.text?i+='<span style="vertical-align: super;"> '+n.text+"</span>":n.css&&a.classList.add(n.css),a.innerHTML=i,n.float&&(a.style.float=n.float),n.clear&&(a.style.clear=n.clear),n.width&&(a.style.width=n.width),n.paddingRight&&(a.style.paddingRight=n.paddingRight),n.paddingLeft&&(a.style.paddingLeft=n.paddingLeft),n.tooltip&&(a.title=n.tooltip),a},"undefined"!=typeof window&&"dhtmlx"in window&&(eXcell_addr.prototype=eXcell_proto,window.eXcell_addr=eXcell_addr),DataManager.prototype.form_obj=function(e,t){function n(){h||((e instanceof dhtmlXLayoutCell||e instanceof dhtmlXSideBarCell||e instanceof dhtmlXCarouselCell)&&(t.bind_pwnd||t.Приклеить)?("function"==typeof e.close&&e.close(!0),f=e,f.close=function(t){var n=f||e;(t||d())&&(n&&(n.elmnts&&["vault","vault_pop"].forEach(function(e){n.elmnts[e]&&n.elmnts[e].unload&&n.elmnts[e].unload()}),v&&v.class_name&&$p.eve.callEvent("frm_close",[v.class_name,y&&y._obj?y.ref:""]),n.conf&&(n.detachToolbar(),n.detachStatusBar(),n.conf.unloading=!0,n.detachObject(!0))),p(t))},f.elmnts={grids:{}}):(m={name:"wnd_obj_"+v.class_name,wnd:{top:80+40*Math.random(),left:120+80*Math.random(),width:700,height:400,modal:!0,center:!1,pwnd:e,allow_close:!0,allow_minmax:!0,on_close:u,caption:x.obj_presentation||x.synonym}},f=$p.iface.dat_blank(null,m.wnd)),f.ref||f.__define({ref:{get:function(){return y?y.ref:$p.utils.blank.guid},enumerable:!1,configurable:!0},set_text:{value:function(e){if(t&&t.set_text||f&&f.setText){var n=y.presentation;if(!n)return;y instanceof CatObj?n=(x.obj_presentation||x.synonym)+": "+n:y instanceof DocObj&&(n+=y.posted?" (проведен)":" (не проведен)"),y._modified&&n.lastIndexOf("*")!=n.length-1?n+=" *":y._modified||n.lastIndexOf("*")!=n.length-1||(n=n.replace(" *","")),(e||g!==n)&&(g=n,t.set_text?t.set_text(n):f.setText(n))}},enumerable:!1,configurable:!0}}),f.elmnts.frm_tabs=f.attachTabbar({arrows_mode:"auto",offsets:{top:0,right:0,bottom:0,left:0}}),f.elmnts.frm_tabs.addTab("tab_header"," Реквизиты ",null,null,!0),f.elmnts.tabs={tab_header:f.elmnts.frm_tabs.cells("tab_header")},f.elmnts.frm_toolbar=f.attachToolbar(),f.elmnts.frm_toolbar.setIconsPath(dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()),f.elmnts.frm_toolbar.loadStruct(t.toolbar_struct||$p.injected_data["toolbar_obj.xml"],function(){f===e&&(this.cont.style.top="4px"),this.addSpacer("btn_unpost"),this.attachEvent("onclick",t.toolbar_click||s);var n=$p.current_acl.get_acl(v.class_name);v instanceof DocManager&&n.indexOf("p")!=-1?(this.enableItem("btn_post"),t.toolbar_struct||this.setItemText("btn_save_close","<b>Провести и закрыть</b>")):this.hideItem("btn_post"),v instanceof DocManager&&n.indexOf("o")!=-1?this.enableItem("btn_unpost"):this.hideItem("btn_unpost"),n.indexOf("e")==-1&&(this.hideItem("btn_save_close"),this.disableItem("btn_save")),t.on_select&&this.setItemText("btn_save_close","Записать и выбрать"),v instanceof CatManager||v instanceof DocManager?(v.printing_plates().then(function(e){for(var t in e)f.elmnts.frm_toolbar.addListOption("bs_print",t,"~","button",e[t].toString())}),f.elmnts.vault_pop=new dhtmlXPopup({toolbar:this,id:"btn_files"}),f.elmnts.vault_pop.attachEvent("onShow",r)):this.disableItem("bs_print"),f!=e&&this.hideItem("btn_close")}),h=!0)}function a(e){y&&f&&f.set_text()}function i(){if(h||(clearTimeout(_),n()),f.set_text(),!t.hide_header&&f.showHeader&&f.showHeader(),t.draw_tabular_sections)t.draw_tabular_sections(y,f,l);else if(!y.is_folder)if(x.form&&x.form.obj&&x.form.obj.tabular_sections_order)x.form.obj.tabular_sections_order.forEach(function(e){l(e)});else for(var e in x.tabular_sections)"extra_fields"!==e&&y[e]instanceof TabularSection&&l(e);if(t.draw_pg_header)t.draw_pg_header(y,f);else{var i=$p.current_acl.get_acl(v.class_name);f.elmnts.pg_header=f.elmnts.tabs.tab_header.attachHeadFields({obj:y,pwnd:f,read_only:i.indexOf("e")==-1}),f.attachEvent("onResizeFinish",function(e){f.elmnts.pg_header.enableAutoHeight(!1,f.elmnts.tabs.tab_header._getHeight()-20,!0)})}return Object.observe(y,a,["update","row"]),{wnd:f,o:y}}function s(e){"btn_save_close"==e?c("close"):"btn_save"==e?c("save"):"btn_post"==e?c("post"):"btn_unpost"==e?c("unpost"):"btn_close"==e?f.close():"btn_go_connection"==e?o():"prn_"==e.substr(0,4)?v.print(y,e,f):"btn_import"==e?v.import(null,y):"btn_export"==e&&v.export({items:[y],pwnd:f,obj:!0})}function o(){$p.msg.show_not_implemented()}function r(){f.elmnts.vault||(f.elmnts.vault=f.elmnts.vault_pop.attachVault(400,250,{_obj:y,buttonClear:!1,autoStart:!0,filesLimit:10,mode:"pouch"}),f.elmnts.vault.conf.wnd=f)}function l(e,t){if(_md.ts_captions(v.class_name,e)){f.elmnts.frm_tabs.addTab("tab_"+e," "+x.tabular_sections[e].synonym+" "),f.elmnts.tabs["tab_"+e]=f.elmnts.frm_tabs.cells("tab_"+e);var n=$p.current_acl.get_acl(v.class_name);if(f.elmnts.grids[e]=f.elmnts.tabs["tab_"+e].attachTabular({obj:y,ts:e,pwnd:f,read_only:n.indexOf("e")==-1,toolbar_struct:t}),n.indexOf("e")==-1){var a=f.elmnts.tabs["tab_"+e].getAttachedToolbar();a.disableItem("btn_add"),a.disableItem("btn_delete")}}}function c(e){f.progressOn();var n;y instanceof DocObj&&("post"==e?n=!0:"unpost"==e?n=!1:"close"==e&&$p.current_acl.get_acl(v.class_name).indexOf("p")!=-1&&(n=!0)),y.save(n).then(function(){f.progressOff(),"close"==e?(t.on_select&&t.on_select(y),f.close()):f.set_text()}).catch(function(e){f.progressOff(),e instanceof Error&&$p.record_log(e)})}function p(n){t&&t.on_close&&!n&&t.on_close(),n||(delete f.ref,delete f.set_text,Object.unobserve(y,a),v=f=y=x=m=e=t=null)}function d(){return!(y._modified&&!b)||(dhtmlx.confirm({title:y.presentation,text:$p.msg.modified_close,cancel:$p.msg.cancel,callback:function(e){e&&(b=!0,"ram"==y._manager.cachable?this.close():y.is_new()?(y.unload(),this.close()):(setTimeout(y.load.bind(y),100),this.close()))}.bind(f)}),!1)}function u(e){if(d())return setTimeout(p),e&&e.elmnts&&["vault","vault_pop"].forEach(function(t){e.elmnts[t]&&e.elmnts[t].unload&&e.elmnts[t].unload()}),v&&v.class_name&&$p.eve.callEvent("frm_close",[v.class_name,y&&y._obj?y.ref:""]),!0}var f,m,h,_,g,b,v=this,x=v.metadata(),y=t.o;return _=setTimeout(n),$p.utils.is_data_obj(y)?y.is_new()&&t.on_select?v.create({},!0).then(function(e){return y=e,e=null,i()}):y.is_new()&&!y.empty()?y.load().then(i):Promise.resolve(i()):(e&&e.progressOn&&e.progressOn(),v.get(t.hasOwnProperty("ref")?t.ref:t,!0,!0).then(function(t){return y=t,t=null,e&&e.progressOff&&e.progressOff(),i()}).catch(function(t){e&&e.progressOff&&e.progressOff(),f.close(),$p.record_log(t)}))},DataObj.prototype.form_obj=function(e,t){return t||(t={}),t.o=this,this._manager.form_obj(e,t)},DataProcessorsManager.prototype.form_rep=function(e,t){function n(){if((e instanceof dhtmlXLayoutCell||e instanceof dhtmlXSideBarCell||e instanceof dhtmlXCarouselCell)&&(t.bind_pwnd||t.Приклеить)){if(o==e&&o._mgr==c)return;"function"==typeof e.close&&e.close(!0),o=e,o.close=function(t){var n=o||e;(t||check_modified())&&(n&&n.conf&&(n.detachToolbar(),n.detachStatusBar(),n.conf.unloading=!0,n.detachObject(!0)),s(t))},o.elmnts={grids:{}}}else r={name:"wnd_rep_"+c.class_name,wnd:{top:80+40*Math.random(),left:120+80*Math.random(),width:700,height:400,modal:!0,center:!1,pwnd:e,allow_close:!0,allow_minmax:!0,on_close:frm_close,caption:p.obj_presentation||p.synonym}},o=$p.iface.dat_blank(null,r.wnd);o._mgr=c,o.report=c.create(),o.set_text||o.__define({set_text:{value:function(e){if(t&&t.set_text||o&&o.setText){var n=p.obj_presentation||p.synonym;(e||l!==n)&&(l=n,t.set_text?t.set_text(n):o.setText(n))}},configurable:!0}}),o.elmnts.layout=o.attachLayout({pattern:"2U",cells:[{id:"a",text:"Отчет",header:!1},{id:"b",text:"Параметры",collapsed_text:"Параметры",width:220}],offsets:{top:0,right:0,bottom:0,left:0}}),o.elmnts.frm_toolbar=o.attachToolbar(),o.elmnts.frm_toolbar.setIconsPath(dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()),o.elmnts.frm_toolbar.loadStruct(t.toolbar_struct||$p.injected_data["toolbar_rep.xml"],function(){o===e&&(this.cont.style.top="4px"),this.addSpacer("btn_run"),this.attachEvent("onclick",t.toolbar_click||a)}),o.set_text(),!t.hide_header&&o.showHeader&&o.showHeader(),o.elmnts.table=new $p.HandsontableDocument(o.elmnts.layout.cells("a"),{allow_offline:o.report.allow_offline,autorun:!1}).then(function(e){if(!e._online)return o.elmnts.table=null}),o.elmnts.frm_prm=document.createElement("DIV"),o.elmnts.frm_prm.style="height: 100%; min-height: 300px; width: 100%",o.elmnts.layout.cells("b").attachObject(o.elmnts.frm_prm),o.report.daterange=new $p.iface.ODateRangePicker(o.elmnts.frm_prm,t)}function a(e){"btn_close"==e?o.close():"btn_run"==e&&o.report.build().then(i).catch(i)}function i(e){o.elmnts.table.requery(e)}function s(n){t&&t.on_close&&!n&&t.on_close(),n||(delete o.set_text,o.elmnts.table&&o.elmnts.table.hot.destroy(),o.report.daterange&&o.report.daterange.remove(),o.report=null,c=o=p=r=e=t=null)}var o,r,l,c=this,p=c.metadata();return t||(t={}),t.date_from||(t.date_from=new Date((new Date).getFullYear().toFixed()+"-01-01")),t.date_till||(t.date_till=new Date((new Date).getFullYear().toFixed()+"-12-31")),n(),o},DataManager.prototype.form_selection=function(e,t){function n(){return e instanceof dhtmlXCellObject?(e instanceof dhtmlXTabBarCell||"function"!=typeof e.close||e.close(!0),m=e,m.close=function(t){(m||e)&&((m||e).detachToolbar(),(m||e).detachStatusBar(),(m||e).conf&&((m||e).conf.unloading=!0),(m||e).detachObject(!0)),p(t)},t.hide_header||setTimeout(function(){m.showHeader()})):(m=$p.iface.w.createWindow(null,0,0,700,500),m.centerOnScreen(),m.setModal(1),m.button("park").hide(),m.button("minmax").show(),m.button("minmax").enable(),m.attachEvent("onClose",d)),$p.iface.bind_help(m),m.setText&&!t.hide_text&&m.setText("Список "+(h.class_name.indexOf("doc.")==-1?'справочника "':'документов "')+(_.list_presentation||_.synonym)+'"'),document.body.addEventListener("keydown",a,!1),m.elmnts={},!t.status_bar&&t.smart_rendering||(m.elmnts.status_bar=m.attachStatusBar()),t.smart_rendering||m.elmnts.status_bar.setText("<div id='"+h.class_name.replace(".","_")+"_select_recinfoArea'></div>"),m.elmnts.toolbar=m.attachToolbar(),m.elmnts.toolbar.setIconsPath(dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()),m.elmnts.toolbar.loadStruct(t.toolbar_struct||$p.injected_data["toolbar_selection.xml"],function(){this.attachEvent("onclick",o),m===e&&(this.cont.parentElement.classList.add("dhx_cell_toolbar_no_borders"),this.cont.parentElement.classList.remove("dhx_cell_toolbar_def"),this.cont.style.top="4px");var n={manager:h,toolbar:this,onchange:i,hide_filter:t.hide_filter,custom_selection:t.custom_selection};t.date_from&&(n.date_from=t.date_from),t.date_till&&(n.date_till=t.date_till),t.period&&(n.period=t.period),m.elmnts.filter=new $p.iface.Toolbar_filter(n);var a=$p.current_acl.get_acl(h.class_name);a.indexOf("i")==-1&&this.hideItem("btn_new"),a.indexOf("v")==-1&&this.hideItem("btn_edit"),a.indexOf("d")==-1&&this.hideItem("btn_delete"),y||(this.hideItem("btn_select"),this.hideItem("sep1"),$p.iface.docs&&$p.iface.docs.getViewName&&"oper"==$p.iface.docs.getViewName()&&this.addListOption("bs_more","btn_order_list","~","button","<i class='fa fa-briefcase fa-lg fa-fw'></i> Список заказов")),this.addListOption("bs_more","btn_import","~","button","<i class='fa fa-upload fa-lg fa-fw'></i> Загрузить из файла"),this.addListOption("bs_more","btn_export","~","button","<i class='fa fa-download fa-lg fa-fw'></i> Выгрузить в файл"),h.printing_plates?h.printing_plates().then(function(e){var t;for(var n in e)m.elmnts.toolbar.addListOption("bs_print",n,"~","button",e[n].toString()),t=!0;t||m.elmnts.toolbar.hideItem("bs_print")}):m.elmnts.toolbar.hideItem("bs_print"),s()}),m._mgr=h,m}function a(e){function t(){var e;return $p.iface.w.forEachWindow(function(t){t==m||!t.isModal()&&$p.iface.w.getTopmostWindow()!=t||(e=!0)}),e}if(m&&m.is_visible&&m.is_visible())if(e.ctrlKey&&70==e.keyCode){if(!t())return setTimeout(function(){m.elmnts.filter.input_filter&&"desktop"==$p.job_prm.device_type&&m.elmnts.filter.input_filter.focus()}),$p.iface.cancel_bubble(e)}else if(e.shiftKey&&116==e.keyCode){if(!t())return setTimeout(function(){m.elmnts.grid.reload()}),e.preventDefault&&e.preventDefault(),$p.iface.cancel_bubble(e)}else 27==e.keyCode&&(t()||setTimeout(function(){m.close()}))}function i(e){m&&m.elmnts&&(g&&(e.filter||e.hide_tree?m.elmnts.cell_tree.collapse():m.elmnts.cell_tree.expand()),m.elmnts.grid.reload())}function s(){var e,n,a,i,s,o;g?(e=m.attachLayout("2U"),a=e.cells("b"),a.hideHeader(),n=m.elmnts.cell_tree=e.cells("a"),n.setWidth("220"),n.hideHeader(),i=m.elmnts.tree=n.attachDynTree(h,null,function(){setTimeout(function(){s&&s.reload&&s.reload()},20)}),i.attachEvent("onSelect",function(e,t){t&&(this.do_not_reload?delete this.do_not_reload:setTimeout(function(){ -s&&s.reload&&s.reload()},20))}),i.attachEvent("onDblClick",function(e){r(e)})):(a=m,setTimeout(function(){s&&s.reload&&s.reload()},20)),s=m.elmnts.grid=a.attachGrid(),s.setIconsPath(dhtmlx.image_path),s.setImagePath(dhtmlx.image_path),s.attachEvent("onBeforeSorting",f),s.attachEvent("onBeforePageChanged",function(){return!!this.getRowsNum()}),s.attachEvent("onXLE",function(){a.progressOff()}),s.attachEvent("onXLS",function(){a.progressOn()}),s.attachEvent("onDynXLS",function(e,t){var n=u(e,t);if(n)return h.sync_grid(n,s),!1}),s.attachEvent("onRowDblClicked",function(e,t){if(i&&i.items[e]){i.selectItem(e);var n=i.getParentId(e);n&&n!=$p.utils.blank.guid&&i.openItem(n)}else r(e)}),t.smart_rendering?s.enableSmartRendering(!0,50):(s.setPagingWTMode(!0,!0,!0,[20,30,60]),s.enablePaging(!0,30,8,h.class_name.replace(".","_")+"_select_recinfoArea"),s.setPagingSkin("toolbar",dhtmlx.skin)),$p.iface.docs&&$p.iface.docs.getViewName&&"oper"==$p.iface.docs.getViewName()&&s.enableMultiselect(!0),s.reload=function(){var e=u();return e?(a.progressOn(),s.clearAll(),h.sync_grid(e,s).then(function(n){if("object"==typeof n)$p.msg.check_soap_result(n);else if(!o){if(e.initial_value){var r=n.indexOf("set_parent"),l=n.indexOf("'>",r),c=n.substr(r+12,l-r-12);$p.utils.is_guid(c)&&g&&(i.do_not_reload=!0,i.selectItem(c,!1)),s.selectRowById(e.initial_value)}else e.parent&&$p.utils.is_guid(e.parent)&&g&&(i.do_not_reload=!0,i.selectItem(e.parent,!1));s.setColumnMinWidth(200,s.getColIndexById("presentation")),s.enableAutoWidth(!0,1200,600),s.setSizes(),o=!0,m.elmnts.filter.input_filter&&"desktop"==$p.job_prm.device_type&&m.elmnts.filter.input_filter.focus(),t.on_grid_inited&&t.on_grid_inited()}v&&o&&s.setSortImgState(!0,b,v),a.progressOff()})):Promise.resolve()}}function o(e){if(!t.toolbar_click||t.toolbar_click(e,m,h)!==!1)if("btn_select"==e)r();else if("btn_new"==e)h.create({},!0).then(function(e){t.on_new?t.on_new(e,m):$p.job_prm.keep_hash?e.form_obj(m):(e._set_loaded(e.ref),$p.iface.set_hash(h.class_name,e.ref))});else if("btn_edit"==e){var n=m.elmnts.grid.getSelectedRowId();n?t.on_edit?t.on_edit(h,n,m):$p.job_prm.keep_hash?h.form_obj(m,{ref:n}):$p.iface.set_hash(h.class_name,n):$p.msg.show_msg({type:"alert-warning",text:$p.msg.no_selected_row.replace("%1",""),title:$p.msg.main_title})}else"prn_"==e.substr(0,4)?l(e):"btn_order_list"==e?$p.iface.set_hash("","","","def"):"btn_delete"==e?c():"btn_import"==e?h.import():"btn_export"==e?h.export(m.elmnts.grid.getSelectedRowId()):"btn_requery"==e&&(x={},m.elmnts.grid.reload())}function r(n){n||(n=m.elmnts.grid.getSelectedRowId());var a;if(t.selection&&t.selection.forEach(function(e){for(var t in e)"is_folder"==t&&(a=e[t])}),m.elmnts.tree&&m.elmnts.tree.items[n]&&m.elmnts.tree.getSelectedId()!=n)return void m.elmnts.tree.selectItem(n,!0);if(n&&a===!0&&m.elmnts.grid.cells(n,0).cell.classList.contains("cell_ref_elm"))return void $p.msg.show_msg($p.msg.select_grp);if(!n&&m.elmnts.tree||m.elmnts.tree&&m.elmnts.tree.getSelectedId()==n){if(a===!1)return void $p.msg.show_msg($p.msg.select_elm);n=m.elmnts.tree.getSelectedId()}n&&(t.on_edit?t.on_edit(h,n,m):y?h.get(n,!0).then(function(t){m.close(),y.call(e.grid||e,t)}):$p.job_prm.keep_hash?h.form_obj(m,{ref:n}):$p.iface.set_hash(h.class_name,n))}function l(e){var t=m.elmnts.grid.getSelectedRowId();t?h.print(t,e,m):$p.msg.show_msg({type:"alert-warning",text:$p.msg.no_selected_row.replace("%1",""),title:$p.msg.main_title})}function c(){var e=m.elmnts.grid.getSelectedRowId();e?h.get(e,!0,!0).then(function(e){dhtmlx.confirm({title:$p.msg.main_title,text:e._deleted?$p.msg.mark_undelete_confirm.replace("%1",e.presentation):$p.msg.mark_delete_confirm.replace("%1",e.presentation),cancel:"Отмена",callback:function(t){t&&e.mark_deleted(!e._deleted)}})}):$p.msg.show_msg({type:"alert-warning",text:$p.msg.no_selected_row.replace("%1",""),title:$p.msg.main_title})}function p(n){document.body.removeEventListener("keydown",a),t&&t.on_close&&!n&&t.on_close(),n||(h=m=_=x=y=e=t=null)}function d(){return setTimeout(p,10),e.on_unload&&e.on_unload.call(e.grid||e),w&&($p.eve.detachEvent(w),w=null),!0}function u(e,n){var a=m.elmnts.filter.get_filter()._mixin({action:"get_selection",metadata:_,class_name:h.class_name,order_by:m.elmnts.grid.columnIds[b]||b,direction:v,start:e||((m.elmnts.grid.currentPage||1)-1)*m.elmnts.grid.rowsBufferOutSize,count:n||m.elmnts.grid.rowsBufferOutSize,get_header:void 0==x.get_header}),i=g?m.elmnts.tree.getSelectedId():null;if(t.smart_rendering&&(a.smart_rendering=!0),t.date_from&&!a.date_from&&(a.date_from=t.date_from),t.date_till&&!a.date_till&&(a.date_till=t.date_till),t.initial_value&&(a.initial_value=t.initial_value),t.custom_selection&&(a.custom_selection=t.custom_selection),t.selection)if(a.selection)if(Array.isArray(t.selection))t.selection.forEach(function(e){a.selection.push(e)});else for(var s in t.selection){res.selection||(res.selection=[]);var o={};o[s]=t.selection[s],a.selection.push(o)}else a.selection=t.selection;t.owner&&!a.owner&&(a.owner=t.owner),a.parent=!i&&!t.parent||a.filter?null:i||t.parent,g&&!a.parent&&(a.parent=$p.utils.blank.guid);for(var r in a)if(x[r]!=a[r])return x=a,a}function f(e){var t=m.elmnts.grid.getSortingState();return b=e,v="des"==t[1]?"asc":"des",m.elmnts.grid.reload(),!0}e||(e=t&&t.pwnd?t.pwnd:{}),t||e instanceof dhtmlXCellObject||(t=e,e={}),t||(t={});var m,h=this,_=t.metadata||h.metadata(),g=_.hierarchical&&!(h instanceof ChartOfAccountManager),b=0,v="asc",x={},y=e.on_select||t.on_select,w=$p.eve.attachEvent("frm_close",function(e,t){h&&h.class_name==e&&m&&m.elmnts&&m.elmnts.grid.reload().then(function(){$p.utils.is_empty_guid(t)||m.elmnts.grid.selectRowById(t,!1,!0,!0)})});return g&&t.initial_value&&t.initial_value!=$p.utils.blank.guid&&!t.parent?h.get(t.initial_value,!0).then(function(e){return t.parent=e.parent.ref,t.set_parent=t.parent,n()}):n()},DataManager.prototype.form_list=function(e,t){return this.form_selection(e,t)},$p.iface.wnd_sync=function(){function e(){var e={name:"wnd_sync",wnd:{id:"wnd_sync",top:130,left:200,width:496,height:290,modal:!0,center:!0,caption:"Подготовка данных"}};t.wnd_sync=$p.iface.dat_blank(null,e.wnd);var n=[{type:"block",name:"form_block_1",list:[{type:"label",name:"form_label_1",label:$p.msg.sync_data},{type:"block",name:"form_block_2",list:[{type:"template",name:"img_long",className:"img_long"},{type:"newcolumn"},{type:"template",name:"text_processed"},{type:"template",name:"text_current"},{type:"template",name:"text_bottom"}]}]},{type:"button",name:"form_button_1",value:$p.msg.sync_break}];t.frm_sync=t.wnd_sync.attachForm(n),t.frm_sync.attachEvent("onButtonClick",function(e){t&&(t.do_break=!0)}),t.frm_sync.setItemValue("text_processed","Инициализация"),t.frm_sync.setItemValue("text_bottom","Загружается структура таблиц...")}var t,n=$p.iface.sync={};n.create=function(n){t=n,e()},n.update=function(e){t.frm_sync.setItemValue("text_processed","Обработано элементов: "+t.step*t.step_size+" из "+t.count_all);var n,a="",i=0;for(var s in e){if(i++,i>4)break;a&&(a+="<br />"),n=$p.cat[s].metadata(),a+=(n.list_presentation||n.synonym)+" ("+e[s].length+")"}t.frm_sync.setItemValue("text_current","Текущий запрос: "+t.step+" ("+Math.round(t.step*t.step_size*100/t.count_all)+"%)"),t.frm_sync.setItemValue("text_bottom",a)},n.close=function(){t&&t.wnd_sync&&(t.wnd_sync.close(),delete t.wnd_sync,delete t.frm_sync)}},DataManager.prototype.export=function(e){function t(){$p.wsql.restore_options("data_manager",l),l.wnd.caption="Экспорт "+r.family_name+" '"+(r.metadata().synonym||r.metadata().name)+"'",o=$p.iface.dat_blank(null,l.wnd),o.bottom_toolbar({buttons:[{name:"btn_cancel",text:'<i class="fa fa-times fa-lg"></i> Отмена',title:"Отмена",width:"80px",float:"right"},{name:"btn_ok",b:'<i class="fa fa-floppy-o"></i> Ок',title:"Выполнить экспорт",width:"50px",float:"right"}],onclick:function(e){return"btn_ok"==e?i():o.close(),!1}}),o.button("close").show(),o.button("park").hide(),o.attachEvent("onClose",s);var t=[{type:"fieldset",name:"form_range",label:"Выгрузить",list:[{type:"settings",labelWidth:320,labelAlign:"left",position:"label-right"},{type:"radio",name:"range",label:"Выделенные строки",value:"selected"},{type:"radio",name:"range",label:"Весь справочник",value:"all"}]},{type:"fieldset",name:"form_fieldset_2",label:"Дополнительно выгрузить",list:[{type:"settings",labelWidth:160,position:"label-right"},{type:"checkbox",name:"meta",label:"Описание метаданных",labelAlign:"left",position:"label-right",checked:l.meta},{type:"newcolumn"},{type:"checkbox",name:"relation",label:"Связанные объекты",position:"label-right",checked:l.relation,tooltip:"Связанные объекты по ссылкам (пока не реализовано)"}]},{type:"fieldset",name:"fieldset_format",label:"Формат файла",list:[{type:"settings",labelWidth:60,labelAlign:"left",position:"label-right"},{type:"radio",name:"format",label:"json",value:"json",tooltip:"Выгрузить в формате JSON"},{type:"newcolumn"},{type:"radio",name:"format",label:"xlsx",value:"xlsx",tooltip:"Выгрузить в офисном формате XLSX"},{type:"newcolumn"},{type:"radio",name:"format",label:"atom",value:"atom",tooltip:"Выгрузить в формате XML Atom"}]}];o.elmnts.frm=o.attachForm(t),o.elmnts.frm.setItemValue("range",l.range||"all"),e.items&&1==e.items.length?(e.obj?o.elmnts.frm.setItemLabel("range","selected","Тек. объект: "+e.items[0].presentation):r.get(e.items[0],!0).then(function(e){o.elmnts.frm.setItemLabel("range","selected","Тек. объект: "+e.presentation)}),o.elmnts.frm.setItemValue("range","selected")):e.items&&e.items.length&&o.elmnts.frm.setItemLabel("range","selected","Выделенные строки ("+e.items.length+" элем.)"),r instanceof DocManager&&o.elmnts.frm.setItemLabel("range","all","Все документы из кеша (0 элем.)"),o.elmnts.frm.setItemValue("format",l.format||"json"),o.elmnts.frm.attachEvent("onChange",n),n(),e.pwnd&&e.pwnd.isModal&&e.pwnd.isModal()&&(e.set_pwnd_modal=!0,e.pwnd.setModal(!1)),o.setModal(!0)}function n(){o.elmnts.frm.setItemValue("relation",!1),o.elmnts.frm.disableItem("relation"),"all"==o.elmnts.frm.getItemValue("range")?(o.elmnts.frm.disableItem("format","atom"),"atom"==o.elmnts.frm.getItemValue("format")&&o.elmnts.frm.setItemValue("format","json")):o.elmnts.frm.enableItem("format","atom"),"json"==o.elmnts.frm.getItemValue("format")?o.elmnts.frm.enableItem("meta"):"sql"==o.elmnts.frm.getItemValue("format")?(o.elmnts.frm.setItemValue("meta",!1),o.elmnts.frm.disableItem("meta")):(o.elmnts.frm.setItemValue("meta",!1),o.elmnts.frm.disableItem("meta"))}function a(){return l.format=o.elmnts.frm.getItemValue("format"),l.range=o.elmnts.frm.getItemValue("range"),l.meta=o.elmnts.frm.getItemValue("meta"),l.relation=o.elmnts.frm.getItemValue("relation"),l}function i(){function t(){e.obj?$p.wsql.alasql("SELECT * INTO XLSX('"+r.table_name+".xlsx',{headers:true}) FROM ?",[e.items[0]._obj]):$p.wsql.alasql("SELECT * INTO XLSX('"+r.table_name+".xlsx',{headers:true}) FROM "+r.table_name)}a();var n={meta:{},items:{}},i=n.items[r.class_name]=[];if(l.meta&&(n.meta[r.class_name]=r.metadata()),"json"==l.format)e.obj?i.push(e.items[0]._obj):r.each(function(t){"all"!=l.range&&e.items.indexOf(t.ref)==-1||i.push(t._obj)}),e.items.length&&!i.length?r.get(e.items[0],!0).then(function(e){i.push(e._obj),alasql.utils.saveFile(r.table_name+".json",JSON.stringify(n,null,4))}):alasql.utils.saveFile(r.table_name+".json",JSON.stringify(n,null,4));else if("xlsx"==l.format)window.xlsx?t():$p.load_script("//cdn.jsdelivr.net/js-xlsx/latest/xlsx.core.min.js","script",t);else if("atom"==l.format&&e.items.length){var s=e.obj?Promise.resolve(e.items[0]):r.get(e.items[0],!0);s.then(function(e){alasql.utils.saveFile(r.table_name+".xml",e.to_atom())})}else $p.msg.show_not_implemented()}function s(t){return $p.iface.popup.hide(),o.wnd_options(l.wnd),$p.wsql.save_options("data_manager",a()),o.setModal(!1),e.set_pwnd_modal&&e.pwnd.setModal&&e.pwnd.setModal(!0),!0}e&&"string"==typeof e?e={items:e.split(",")}:e||(e={items:[]});var o,r=this,l={name:"export",wnd:{top:130,left:200,width:480,height:350}};t()},DataManager.prototype.import=function(e,t){function n(e){function n(e,n){var a=_md.mgr_by_class_name(e);if(n.length)if(t){if(t._manager==a)for(var s in n)$p.utils.fix_guid(n[s])==t.ref&&(i=!0,a.load_array([n[s]],!0))}else i=!0,a.load_array(n,!0)}if(o.close(),a.files.length){var s=new FileReader;s.onload=function(e){try{var t=JSON.parse(s.result);if(t.items)for(var a in t.items)n(a,t.items[a]);else["cat","doc","ireg","areg","cch","cacc"].forEach(function(e){if(t[e])for(var a in t[e])n(e+"."+a,t.cat[a])});i||$p.msg.show_msg($p.msg.sync_no_data)}catch(e){$p.msg.show_msg(e.message)}},s.readAsText(a.files[0])}}var a,i;if(!e&&void 0!=typeof window){var s={name:"import",wnd:{width:300,height:100,caption:$p.msg.select_file_import}},o=$p.iface.dat_blank(null,s.wnd);a=document.createElement("input"),a.setAttribute("id","json_file"),a.setAttribute("type","file"),a.setAttribute("accept",".json"),a.setAttribute("value","*.json"),a.onchange=n,o.button("close").show(),o.button("park").hide(),o.attachObject(a),o.centerOnScreen(),o.setModal(!0),setTimeout(function(){a.click()},100)}},$p.eve.__define({set_offline:{value:function(e){var t=$p.job_prm.offline;$p.job_prm.offline=!(!e&&!$p.wsql.get_user_param("offline","boolean")),t!=$p.job_prm.offline&&(t=$p.job_prm.offline)}},on_rotate:{value:function(e){$p.job_prm.device_orient=0==window.orientation||180==window.orientation?"portrait":"landscape","undefined"!=typeof e&&$p.eve.callEvent("onOrientationChange",[$p.job_prm.device_orient])}},steps:{value:{load_meta:0,authorization:1,create_managers:2,process_access:3,load_data_files:4,load_data_db:5,load_data_wsql:6,save_data_wsql:7}},log_in:{value:function(e){var t,n={};return e($p.eve.steps.load_meta),$p.ajax.default_attr(n,$p.job_prm.irest_url()),($p.job_prm.offline?Promise.resolve({responseURL:"",response:""}):$p.ajax.get_ex(n.url,n)).then(function(e){if($p.job_prm.offline||($p.job_prm.irest_enabled=!0),"{"==e.response[0])return JSON.parse(e.response)}).catch(function(){}).then(function(n){return e($p.eve.steps.authorization),t=n,t.root=!0,$p.job_prm.offline||$p.job_prm.irest_enabled?t:$p.ajax.get_ex($p.job_prm.rest_url()+"?$format=json",!0).then(function(){return t})}).catch(function(e){throw $p.iface.auth.onerror&&$p.iface.auth.onerror(e),e}).then(function(t){return e($p.eve.steps.load_data_files),$p.job_prm.offline?t:($p.eve.callEvent("log_in",[$p.ajax.authorized=!0]),"string"==typeof t&&(t=JSON.parse(t)),void($p.msg.check_soap_result(t)||($p.wsql.get_user_param("enable_save_pwd")?$p.wsql.set_user_param("user_pwd",$p.ajax.password):$p.wsql.get_user_param("user_pwd")&&$p.wsql.set_user_param("user_pwd",""),t.now_1c&&t.now_js&&$p.wsql.set_user_param("time_diff",t.now_1c-t.now_js))))}).then(function(){_md.printing_plates(t.printing_plates)})}}}),function(w,eve,msg){var timer_setted=!1,cache;w.addEventListener("online",eve.set_offline),w.addEventListener("offline",function(){eve.set_offline(!0)}),w.addEventListener("load",function(){setTimeout(function(){function navigate(e){e&&(location.origin+location.pathname).indexOf(e)==-1&&location.replace(e)}function init_params(){function e(){var e=dhtmlx.codebase,t=!0,n=!0;e.indexOf("cdn.jsdelivr.net")!=-1&&(e="//cdn.jsdelivr.net/metadata/latest/");for(var a=0;a<document.styleSheets.length;a++)document.styleSheets[a].href&&(document.styleSheets[a].href.indexOf("dhx_web")==-1&&document.styleSheets[a].href.indexOf("dhx_terrace")==-1||(t=!1),document.styleSheets[a].href.indexOf("metadata.css")!=-1&&(n=!1));dhtmlx.skin=$p.wsql.get_user_param("skin")||$p.job_prm.skin||"dhx_web",t&&$p.load_script(e+("dhx_web"==dhtmlx.skin?"dhx_web.css":"dhx_terrace.css"),"link"),n&&$p.load_script(e+"metadata.css","link"),$p.job_prm.additional_css&&$p.job_prm.additional_css.forEach(function(e){(dhx4.isIE||e.indexOf("ie_only")==-1)&&$p.load_script(e,"link")}),dhtmlx.image_path="//oknosoft.github.io/metadata.js/lib/imgs/",dhtmlx.skin_suffix=function(){return dhtmlx.skin.replace("dhx","")+"/"},dhx4.ajax.cache=!0,$p.iface.__define("w",{value:new dhtmlXWindows,enumerable:!1}),$p.iface.w.setSkin(dhtmlx.skin),$p.iface.__define("popup",{value:new dhtmlXPopup,enumerable:!1})}$p.wsql.init_params(),"dhtmlx"in w&&e(),"undefined"==typeof w.orientation?$p.job_prm.device_orient=w.innerWidth>w.innerHeight?"landscape":"portrait":eve.on_rotate(),w.addEventListener("orientationchange",eve.on_rotate,!1),eve.stepper={step:0,count_all:0,step_size:57,files:0},eve.set_offline(!navigator.onLine),setTimeout(function(){$p.wsql.pouch.load_data().catch($p.record_log);var e;(e=document.querySelector("#splash"))&&e.parentNode.removeChild(e),eve.callEvent("iface_init",[$p])},20),(cache=w.applicationCache)&&(cache.addEventListener("noupdate",function(e){},!1),cache.addEventListener("cached",function(e){timer_setted=!0,$p.iface.appcache&&$p.iface.appcache.close()},!1),cache.addEventListener("updateready",function(e){try{cache.swapCache()}catch(e){}$p.iface.do_reload()},!1),cache.addEventListener("error",$p.record_log,!1))}if(!w.JSON||!w.indexedDB)throw eve.redirect=!0,msg.show_msg({type:"alert-error",text:msg.unsupported_browser,title:msg.unsupported_browser_title}),msg.unsupported_browser;$p.__define("job_prm",{value:new JobPrm,writable:!1}),($p.job_prm.use_ip_geo||$p.job_prm.use_google_geo)&&($p.ipinfo=new IPInfo),$p.job_prm.use_google_geo&&(window.google&&window.google.maps?location_callback():$p.on("iface_init",function(){setTimeout(function(){$p.load_script("//maps.google.com/maps/api/js?callback=$p.ipinfo.location_callback","script",function(){})},100)})),$p.job_prm.allow_post_message&&w.addEventListener("message",function(event){if(("*"==$p.job_prm.allow_post_message||$p.job_prm.allow_post_message==event.origin)&&"string"==typeof event.data)try{var res=eval(event.data);if(res&&event.source){if("object"==typeof res)res=JSON.stringify(res);else if("function"==typeof res)return;event.source.postMessage(res,"*")}}catch(e){$p.record_log(e)}}),$p.job_prm.__define("device_type",{get:function(){var e=$p.wsql.get_user_param("device_type");return e||(e=function(e){return e<800?"phone":e<1024?"tablet":"desktop"}(Math.max(screen.width,screen.height)),$p.wsql.set_user_param("device_type",e)),e},set:function(e){$p.wsql.set_user_param("device_type",e)}}),document.body.addEventListener("keydown",function(e){eve.callEvent("keydown",[e])},!1),setTimeout(init_params,10)},10)},!1),w.onbeforeunload=function(){if(!eve.redirect)return msg.onbeforeunload},w.addEventListener("popstat",$p.iface.hash_route),w.addEventListener("hashchange",$p.iface.hash_route)}(window,$p.eve,$p.msg),SpreadsheetDocument.prototype.__define({clear:{value:function(){for(;this._attr.content.firstChild;)this._attr.content.removeChild(this._attr.content.firstChild)}},put:{value:function(e,t){var n;e instanceof HTMLElement?(n=document.createElement(e.tagName),n.innerHTML=e.innerHTML,t||(t=e.attributes)):(n=document.createElement("DIV"),n.innerHTML=e),t&&Object.keys(t).forEach(function(e){"id"!=e&&"id"!=t[e].name&&n.setAttribute(t[e].name||e,t[e].value||t[e])}),this._attr.content.appendChild(n)}},content:{get:function(){return this._attr.content},set:function(e){this.clear(),"string"==typeof e?this._attr.content.innerHTML=e:e instanceof HTMLElement&&(this._attr.content.innerHTML=e.innerHTML)}},title:{get:function(){return this._attr.title},set:function(e){this._attr.title=e}}}),$p.SpreadsheetDocument=SpreadsheetDocument,$p.HandsontableDocument=HandsontableDocument,$p.injected_data._mixin({"form_auth.xml":'<?xml version="1.0" encoding="UTF-8"?>\n<items>\n\t<item type="settings" position="label-left" labelWidth="80" inputWidth="180" noteWidth="180"/>\n\t<item type="fieldset" name="data" inputWidth="auto" label="Авторизация">\n\n <item type="radio" name="type" labelWidth="auto" position="label-right" checked="true" value="guest" label="Гостевой (демо) режим">\n <item type="select" name="guest" label="Роль">\n <option value="Дилер" label="Дилер"/>\n </item>\n </item>\n\n\t\t<item type="radio" name="type" labelWidth="auto" position="label-right" value="auth" label="Есть учетная запись">\n\t\t\t<item type="input" value="" name="login" label="Логин" validate="NotEmpty" />\n\t\t\t<item type="password" value="" name="password" label="Пароль" validate="NotEmpty" />\n\t\t</item>\n\n\t\t<item type="button" value="Войти" name="submit"/>\n\n <item type="template" name="text_options" className="order_dealer_options" inputWidth="170"\n value="<a href=\'#\' onclick=\'$p.iface.open_settings();\' title=\'Страница настроек программы\' > <i class=\'fa fa-cog fa-lg\'></i> Настройки </a> <a href=\'//www.oknosoft.ru/feedback\' target=\'_blank\' style=\'margin-left: 9px;\' title=\'Задать вопрос через форму обратной связи\' > <i class=\'fa fa-question-circle fa-lg\'></i> Вопрос </a>" />\n\n\t</item>\n</items>',"toolbar_add_del.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n <item id="sep0" type="separator"/>\r\n <item type="button" id="btn_add" text="<i class=\'fa fa-plus-circle fa-fw\'></i> Добавить" title="Добавить строку" />\r\n <item type="button" id="btn_delete" text="<i class=\'fa fa-times fa-fw\'></i> Удалить" title="Удалить строку" />\r\n</toolbar>',"toolbar_obj.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n <item id="sep0" type="separator"/>\r\n <item type="button" id="btn_save_close" text="<b>Записать и закрыть</b>" title="Рассчитать, записать и закрыть" />\r\n <item type="button" id="btn_save" text="<i class=\'fa fa-floppy-o fa-fw\'></i>" title="Рассчитать и записать данные"/>\r\n <item type="button" id="btn_post" enabled="false" text="<i class=\'fa fa-check-square-o fa-fw\'></i>" title="Провести документ" />\r\n <item type="button" id="btn_unpost" enabled="false" text="<i class=\'fa fa-square-o fa-fw\'></i>" title="Отмена проведения" />\r\n\r\n <item type="button" id="btn_files" text="<i class=\'fa fa-paperclip fa-fw\'></i>" title="Присоединенные файлы"/>\r\n\r\n <item type="buttonSelect" id="bs_print" text="<i class=\'fa fa-print fa-fw\'></i>" title="Печать" openAll="true">\r\n </item>\r\n\r\n <item type="buttonSelect" id="bs_create_by_virtue" text="<i class=\'fa fa-bolt fa-fw\'></i>" title="Создать на основании" openAll="true" >\r\n <item type="button" id="btn_message" enabled="false" text="Сообщение" />\r\n </item>\r\n\r\n <item type="buttonSelect" id="bs_go_to" text="<i class=\'fa fa-external-link fa-fw\'></i>" title="Перейти" openAll="true" >\r\n <item type="button" id="btn_go_connection" enabled="false" text="Связи" />\r\n </item>\r\n\r\n <item type="buttonSelect" id="bs_more" text="<i class=\'fa fa-th-large fa-fw\'></i>" title="Дополнительно" openAll="true">\r\n\r\n <item type="button" id="btn_import" text="<i class=\'fa fa-upload fa-fw\'></i> Загрузить из файла" />\r\n <item type="button" id="btn_export" text="<i class=\'fa fa-download fa-fw\'></i> Выгрузить в файл" />\r\n </item>\r\n\r\n <item id="sep1" type="separator"/>\r\n <item type="button" id="btn_close" text="<i class=\'fa fa-times fa-fw\'></i>" title="Закрыть форму"/>\r\n <item id="sep2" type="separator"/>\r\n\r\n</toolbar>\r\n',"toolbar_ok_cancel.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n <item id="btn_ok" type="button" img="" imgdis="" text="<b>Ок</b>" />\r\n <item id="btn_cancel" type="button"\timg="" imgdis="" text="Отмена" />\r\n</toolbar>',"toolbar_rep.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n <item id="sep0" type="separator"/>\r\n <item type="button" id="btn_run" text="<i class=\'fa fa-play fa-fw\'></i> Сформировать" title="Сформировать отчет"/>\r\n\r\n <item type="buttonSelect" id="bs_more" text="<i class=\'fa fa-th-large fa-fw\'></i>" title="Дополнительно" openAll="true">\r\n\r\n <item type="button" id="btn_print" text="<i class=\'fa fa-print fa-fw\'></i> Печать" />\r\n\r\n <item id="sep3" type="separator"/>\r\n\r\n <item type="button" id="btn_export" text="<i class=\'fa fa-file-excel-o fa-fw\'></i> Выгрузить в файл" />\r\n\r\n <item id="sep4" type="separator"/>\r\n\r\n <item type="button" id="btn_import" text="<i class=\'fa fa-folder-open-o fa-fw\'></i> Выбрать вариант" />\r\n <item type="button" id="btn_export" text="<i class=\'fa fa-floppy-o fa-fw\'></i> Сохранить вариант" />\r\n\r\n </item>\r\n\r\n <item id="sep1" type="separator"/>\r\n\r\n</toolbar>\r\n',"toolbar_selection.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n\r\n <item id="sep0" type="separator"/>\r\n\r\n <item id="btn_select" type="button" title="Выбрать элемент списка" text="<b>Выбрать</b>" />\r\n\r\n <item id="sep1" type="separator"/>\r\n <item id="btn_new" type="button"\ttext="<i class=\'fa fa-plus-circle fa-fw\'></i>"\ttitle="Создать" />\r\n <item id="btn_edit" type="button"\ttext="<i class=\'fa fa-pencil fa-fw\'></i>"\ttitle="Изменить" />\r\n <item id="btn_delete" type="button"\ttext="<i class=\'fa fa-times fa-fw\'></i>"\ttitle="Удалить" />\r\n <item id="sep2" type="separator"/>\r\n\r\n <item type="buttonSelect" id="bs_print" text="<i class=\'fa fa-print fa-fw\'></i> Печать" openAll="true" >\r\n </item>\r\n\r\n <item type="buttonSelect" id="bs_more" text="<i class=\'fa fa-th-large fa-fw\'></i>" title="Дополнительно" openAll="true">\r\n <item id="btn_requery" type="button"\ttext="<i class=\'fa fa-refresh fa-fw\'></i> Обновить список" />\r\n </item>\r\n\r\n <item id="sep3" type="separator"/>\r\n\r\n</toolbar>'});var xmlToJSON=function(){this.version="1.3";var e={mergeCDATA:!0,grokAttr:!0,grokText:!0,normalize:!0,xmlns:!0,namespaceKey:"_ns",textKey:"_text",valueKey:"_value",attrKey:"_attr",cdataKey:"_cdata",attrsAsObject:!0,stripAttrPrefix:!0,stripElemPrefix:!0,childrenAsArray:!0},t=new RegExp(/(?!xmlns)^.*:/),n=new RegExp(/^\s+|\s+$/g);return this.grokType=function(e){return/^\s*$/.test(e)?null:/^(?:true|false)$/i.test(e)?"true"===e.toLowerCase():isFinite(e)?parseFloat(e):e},this.parseString=function(e,t){return this.parseXML(this.stringToXML(e),t)},this.parseXML=function(a,i){for(var s in i)e[s]=i[s];var o={},r=0,l="";if(e.xmlns&&a.namespaceURI&&(o[e.namespaceKey]=a.namespaceURI),a.attributes&&a.attributes.length>0){var c={};for(r;r<a.attributes.length;r++){var p=a.attributes.item(r);m={};var d="";d=e.stripAttrPrefix?p.name.replace(t,""):p.name,e.grokAttr?m[e.valueKey]=this.grokType(p.value.replace(n,"")):m[e.valueKey]=p.value.replace(n,""),e.xmlns&&p.namespaceURI&&(m[e.namespaceKey]=p.namespaceURI),e.attrsAsObject?c[d]=m:o[e.attrKey+d]=m}e.attrsAsObject&&(o[e.attrKey]=c)}if(a.hasChildNodes())for(var u,f,m,h=0;h<a.childNodes.length;h++)u=a.childNodes.item(h),4===u.nodeType?e.mergeCDATA?l+=u.nodeValue:o.hasOwnProperty(e.cdataKey)?(o[e.cdataKey].constructor!==Array&&(o[e.cdataKey]=[o[e.cdataKey]]),o[e.cdataKey].push(u.nodeValue)):e.childrenAsArray?(o[e.cdataKey]=[],o[e.cdataKey].push(u.nodeValue)):o[e.cdataKey]=u.nodeValue:3===u.nodeType?l+=u.nodeValue:1===u.nodeType&&(0===r&&(o={}),f=e.stripElemPrefix?u.nodeName.replace(t,""):u.nodeName,m=xmlToJSON.parseXML(u),o.hasOwnProperty(f)?(o[f].constructor!==Array&&(o[f]=[o[f]]),o[f].push(m)):(e.childrenAsArray?(o[f]=[],o[f].push(m)):o[f]=m,r++));else l||(e.childrenAsArray?(o[e.textKey]=[],o[e.textKey].push(null)):o[e.textKey]=null);if(l)if(e.grokText){var _=this.grokType(l.replace(n,""));null!==_&&void 0!==_&&(o[e.textKey]=_)}else e.normalize?o[e.textKey]=l.replace(n,"").replace(/\s+/g," "):o[e.textKey]=l.replace(n,"");return o},this.xmlToString=function(e){try{var t=e.xml?e.xml:(new XMLSerializer).serializeToString(e);return t}catch(e){return null}},this.stringToXML=function(e){try{var t=null;if(window.DOMParser){var n=new DOMParser;return t=n.parseFromString(e,"text/xml")}return t=new ActiveXObject("Microsoft.XMLDOM"),t.async=!1,t.loadXML(e),t}catch(e){return null}},this}();"undefined"!=typeof module&&null!==module&&module.exports?module.exports=xmlToJSON:"function"==typeof define&&define.amd&&define(function(){return xmlToJSON});/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ -var saveAs=saveAs||function(e){"use strict";if(!("undefined"==typeof e||"undefined"!=typeof navigator&&/MSIE [1-9]\./.test(navigator.userAgent))){var t=e.document,n=function(){return e.URL||e.webkitURL||e},a=t.createElementNS("http://www.w3.org/1999/xhtml","a"),i="download"in a,s=function(e){var t=new MouseEvent("click");e.dispatchEvent(t)},o=/constructor/i.test(e.HTMLElement),r=/CriOS\/[\d]+/.test(navigator.userAgent),l=function(t){(e.setImmediate||e.setTimeout)(function(){throw t},0)},c="application/octet-stream",p=4e4,d=function(e){var t=function(){"string"==typeof e?n().revokeObjectURL(e):e.remove()};setTimeout(t,p)},u=function(e,t,n){t=[].concat(t);for(var a=t.length;a--;){var i=e["on"+t[a]];if("function"==typeof i)try{i.call(e,n||e)}catch(e){l(e)}}},f=function(e){return/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob([String.fromCharCode(65279),e],{type:e.type}):e},m=function(t,l,p){p||(t=f(t));var m,h=this,_=t.type,g=_===c,b=function(){u(h,"writestart progress write writeend".split(" "))},v=function(){if((r||g&&o)&&e.FileReader){var a=new FileReader;return a.onloadend=function(){var t=r?a.result:a.result.replace(/^data:[^;]*;/,"data:attachment/file;"),n=e.open(t,"_blank");n||(e.location.href=t),t=void 0,h.readyState=h.DONE,b()},a.readAsDataURL(t),void(h.readyState=h.INIT)}if(m||(m=n().createObjectURL(t)),g)e.location.href=m;else{var i=e.open(m,"_blank");i||(e.location.href=m)}h.readyState=h.DONE,b(),d(m)};return h.readyState=h.INIT,i?(m=n().createObjectURL(t),void setTimeout(function(){a.href=m,a.download=l,s(a),b(),d(m),h.readyState=h.DONE})):void v()},h=m.prototype,_=function(e,t,n){return new m(e,t||e.name||"download",n)};return"undefined"!=typeof navigator&&navigator.msSaveOrOpenBlob?function(e,t,n){return t=t||e.name||"download",n||(e=f(e)),navigator.msSaveOrOpenBlob(e,t)}:(h.abort=function(){},h.readyState=h.INIT=0,h.WRITING=1,h.DONE=2,h.error=h.onwritestart=h.onprogress=h.onwrite=h.onabort=h.onerror=h.onwriteend=null,_)}}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||this.content);/*! +!function(e,t){"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?module.exports=t():e.$p=t()}(this,function(){function MetaEngine(){this.__define({version:{value:"0.12.225",writable:!1},toString:{value:function(){return"Oknosoft data engine. v:"+this.version},writable:!1},utils:{value:new Utils},injected_data:{value:{},writable:!1},ajax:{value:new Ajax,writable:!1},msg:{value:new Messages,writable:!1},wsql:{value:new WSQL,writable:!1},eve:{value:new AppEvents,writable:!1},aes:{value:new Aes("metadata.js"),writable:!1},moment:{get:function(){return this.utils.moment}},_patch:{value:function(e,t){for(var n in t)"object"==typeof t[n]&&e[n]&&"object"==typeof e[n]?$p._patch(e[n],t[n]):e[n]=t[n];return e}},_find:{value:function(e,t,n){var a,i,s;if("object"!=typeof t)for(i in e){a=e[i];for(var o in a)if("function"!=typeof a[o]&&$p.utils.is_equal(a[o],t))return a}else for(i in e){a=e[i],s=!0;for(var o in t)if("function"!=typeof a[o]&&!$p.utils.is_equal(a[o],t[o])){s=!1;break}if(s)return a}}},_selection:{value:function(e,t){var n,a,i,s=!0;if(t)if("function"==typeof t)s=t.call(this,e);else for(n in t)if(a=t[n],i="object"==typeof a,"_"!=n.substr(0,1))if("function"==typeof a){if(s=a.call(this,e,n),!s)break}else if("or"==n&&Array.isArray(a)){if(s=a.some(function(t){var n=Object.keys(t)[0];return t[n].hasOwnProperty("like")?e[n]&&e[n].toLowerCase().indexOf(t[n].like.toLowerCase())!=-1:$p.utils.is_equal(e[n],t[n])}),!s)break}else if(i&&a.hasOwnProperty("like")){if(!e[n]||e[n].toLowerCase().indexOf(a.like.toLowerCase())==-1){s=!1;break}}else if(i&&a.hasOwnProperty("not")){if($p.utils.is_equal(e[n],a.not)){s=!1;break}}else if(i&&a.hasOwnProperty("in")){if(s=a.in.some(function(t){return $p.utils.is_equal(t,e[n])}),!s)break}else if(i&&a.hasOwnProperty("lt")){if(s=e[n]<a.lt,!s)break}else if(i&&a.hasOwnProperty("gt")){if(s=e[n]>a.gt,!s)break}else if(i&&a.hasOwnProperty("between")){var o=e[n];if("number"!=typeof o&&(o=$p.utils.fix_date(e[n])),s=o>=a.between[0]&&o<=a.between[1],!s)break}else if(!$p.utils.is_equal(e[n],a)){s=!1;break}return s}},_find_rows:{value:function(e,t,n){var a,i,s=[],o=0;t&&(t._top?(i=t._top,delete t._top):i=300);for(var r in e)if(a=e[r],$p._selection.call(this,a,t)){if(n){if(n.call(this,a)===!1)break}else s.push(a);if(i&&(o++,o>=i))break}return s}},on:{value:function(e,t){if("object"!=typeof e)return this.eve.attachEvent(e,t);for(var n in e)e[n]._evnts||(e[n]._evnts=[]),e[n]._evnts.push(this.eve.attachEvent(n,e[n]))}},off:{value:function(e){"function"==typeof e&&e._evnts?e._evnts.forEach(function(e){$p.eve.detachEvent(e)}):e?$p.eve.detachEvent(e):$p.eve.detachAllEvents()}},record_log:{value:function(e){$p.ireg&&$p.ireg.log&&$p.ireg.log.record(e),console.log(e)}},md:{value:new Meta},enm:{value:new function(){this.toString=function(){return $p.msg.meta_enn_mgr}}},cat:{value:new function(){this.toString=function(){return $p.msg.meta_cat_mgr}}},doc:{value:new function(){this.toString=function(){return $p.msg.meta_doc_mgr}}},ireg:{value:new function(){this.toString=function(){return $p.msg.meta_ireg_mgr}}},areg:{value:new function(){this.toString=function(){return $p.msg.meta_areg_mgr}}},accreg:{value:new function(){this.toString=function(){return $p.msg.meta_accreg_mgr}}},dp:{value:new function(){this.toString=function(){return $p.msg.meta_dp_mgr}}},rep:{value:new function(){this.toString=function(){return $p.msg.meta_reports_mgr}}},cacc:{value:new function(){this.toString=function(){return $p.msg.meta_charts_of_accounts_mgr}}},cch:{value:new function(){this.toString=function(){return $p.msg.meta_charts_of_characteristic_mgr}}},tsk:{value:new function(){this.toString=function(){return $p.msg.meta_task_mgr}}},bp:{value:new function(){this.toString=function(){return $p.msg.meta_bp_mgr}}},DataManager:{value:DataManager},RefDataManager:{value:RefDataManager},DataProcessorsManager:{value:DataProcessorsManager},EnumManager:{value:EnumManager},RegisterManager:{value:RegisterManager},InfoRegManager:{value:InfoRegManager},LogManager:{value:LogManager},MetaObjManager:{value:MetaObjManager},MetaFieldManager:{value:MetaFieldManager},SchemeSettingsManager:{value:SchemeSettingsManager},AccumRegManager:{value:AccumRegManager},CatManager:{value:CatManager},ChartOfCharacteristicManager:{value:ChartOfCharacteristicManager},ChartOfAccountManager:{value:ChartOfAccountManager},DocManager:{value:DocManager},TaskManager:{value:TaskManager},BusinessProcessManager:{value:BusinessProcessManager},DataObj:{value:DataObj},CatObj:{value:CatObj},DocObj:{value:DocObj},DataProcessorObj:{value:DataProcessorObj},TaskObj:{value:TaskObj},BusinessProcessObj:{value:BusinessProcessObj},EnumObj:{value:EnumObj},RegisterRow:{value:RegisterRow},TabularSection:{value:TabularSection},TabularSectionRow:{value:TabularSectionRow}})}function Utils(){this.moment="function"==typeof moment?moment:require("moment"),this.moment._masks={date:"DD.MM.YY",date_time:"DD.MM.YYYY HH:mm",ldt:"DD MMMM YYYY, HH:mm",iso:"YYYY-MM-DDTHH:mm:ss"},this.fix_date=function(e,t){if(e instanceof Date)return e;var n=this.moment(e,["DD-MM-YYYY","DD-MM-YYYY HH:mm","DD-MM-YYYY HH:mm:ss","DD-MM-YY HH:mm","YYYYDDMMHHmmss",this.moment.ISO_8601]);return n.isValid()?n.toDate():t?this.blank.date:e},this.fix_guid=function(e,t){if(e&&"string"==typeof e);else{if(e instanceof DataObj)return e.ref;if(e&&"object"==typeof e)if(e.presentation){if(e.ref)return e.ref;if(e.name)return e.name}else e="object"==typeof e.ref&&e.ref.hasOwnProperty("ref")?e.ref.ref:e.ref}return this.is_guid(e)||t===!1?e:t?this.generate_guid():this.blank.guid},this.fix_number=function(e,t){var n=parseFloat(e);return isNaN(n)?t?0:e:n},this.fix_boolean=function(e){return"string"==typeof e?!(!e||"false"==e.toLowerCase()):!!e},this.blank={date:this.fix_date("0001-01-01T00:00:00"),guid:"00000000-0000-0000-0000-000000000000",by_type:function(e){var t;return t=e.is_ref?this.guid:e.date_part?this.date:e.digits?0:(!e.types||"boolean"!=e.types[0])&&""}},this.fetch_type=function(e,t){var n=e;return t.is_ref?n=this.fix_guid(e):t.date_part?n=this.fix_date(e,!0):t.digits?n=this.fix_number(e,!0):"boolean"==t.types[0]&&(n=this.fix_boolean(e)),n},this.date_add_day=function(e,t,n){var a=new Date(e);return a.setDate(e.getDate()+t),n&&a.setHours(0,-a.getTimezoneOffset(),0,0),a},this.generate_guid=function(){var e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var n=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?n:7&n|8).toString(16)})},this.is_guid=function(e){return!("string"!=typeof e||e.length<36)&&(e.length>36&&(e=e.substr(0,36)),/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(e))},this.is_empty_guid=function(e){return!e||e===this.blank.guid},this.is_data_obj=function(e){return e&&e instanceof DataObj},this.is_data_mgr=function(e){return e&&e instanceof DataManager},this.is_equal=function(e,t){return e==t||typeof e!=typeof t&&this.fix_guid(e,!1)==this.fix_guid(t,!1)},this.blob_as_text=function(e,t){return new Promise(function(n,a){var i=new FileReader;i.onload=function(e){n(i.result)},i.onerror=function(e){a(e)},"data_url"==t?i.readAsDataURL(e):i.readAsText(e)})}}function Ajax(){function e(e,t,n,a,i){return new Promise(function(s,o){if("undefined"==typeof window&&a&&a.request)a.request({url:encodeURI(t),headers:{Authorization:a.auth}},function(e,t,n){e?o(e):200!=t.statusCode?o({message:t.statusMessage,description:n,status:t.statusCode}):s({response:n})});else{var r=new XMLHttpRequest;if(window.dhx4&&window.dhx4.isIE&&(t=encodeURI(t)),a){var l,c;"object"==typeof a&&a.username&&a.hasOwnProperty("password")?(l=a.username,c=a.password):$p.ajax.username&&$p.ajax.authorized?(l=$p.ajax.username,c=$p.aes.Ctr.decrypt($p.ajax.password)):(l=$p.wsql.get_user_param("user_name"),c=$p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd")),!l&&$p.job_prm&&$p.job_prm.guest_name&&(l=$p.job_prm.guest_name,c=$p.aes.Ctr.decrypt($p.job_prm.guest_pwd))),r.open(e,t,!0,l,c),r.withCredentials=!0,r.setRequestHeader("Authorization","Basic "+btoa(unescape(encodeURIComponent(l+":"+c))))}else r.open(e,t,!0);i&&i.call(this,r),"GET"!=e?this.hide_headers||a.hide_headers||(r.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),r.setRequestHeader("X-Requested-With","XMLHttpRequest")):n=null,r.onload=function(){200==r.status&&(r.response instanceof Blob||"<!DOCTYPE"!==r.response.substr(0,9))?(void 0==r.responseURL&&(r.responseURL=t),s(r)):o(r.response?{message:r.statusText,description:r.response,status:r.status}:Error(r.statusText))},r.onerror=function(){o(Error("Network Error"))},r.send(n)}})}this.username="",this.password="",this.root=!0,this.authorized=!1,this.get=function(t){return e.call(this,"GET",t)},this.post=function(t,n){return 1==arguments.length?n="":2==arguments.length&&"function"==typeof n?(onLoad=n,n=""):n=String(n),e.call(this,"POST",t,n)},this.get_ex=function(t,n,a){return e.call(this,"GET",t,null,n,a)},this.post_ex=function(t,n,a,i){return e.call(this,"POST",t,n,a,i)},this.put_ex=function(t,n,a,i){return e.call(this,"PUT",t,n,a,i)},this.patch_ex=function(t,n,a,i){return e.call(this,"PATCH",t,n,a,i)},this.delete_ex=function(t,n,a){return e.call(this,"DELETE",t,null,n,a)},this.get_and_show_blob=function(e,t,n){function a(t){return e=window.URL.createObjectURL(t.response),i=window.open(e,"wnd_print",s),i.onload=function(t){window.URL.revokeObjectURL(e)},i}var i,s="menubar=no,toolbar=no,location=no,status=no,directories=no,resizable=yes,scrollbars=yes";return!n||"string"==typeof n&&n.toLowerCase().indexOf("post")!=-1?this.post_ex(e,"object"==typeof t?JSON.stringify(t):t,!0,function(e){e.responseType="blob"}).then(a):this.get_ex(e,!0,function(e){e.responseType="blob"}).then(a)},this.get_and_save_blob=function(e,t,n){return this.post_ex(e,"object"==typeof t?JSON.stringify(t):t,!0,function(e){e.responseType="blob"}).then(function(e){saveAs(e.response,n)})},this.default_attr=function(e,t){e.url||(e.url=t),e.username||(e.username=this.username),e.password||(e.password=this.password),e.hide_headers=!0,$p.job_prm["1c"]&&(e.auth=$p.job_prm["1c"].auth,e.request=$p.job_prm["1c"].request)}}function WSQL(){var e,t=this,n={};this.__define({js_time_diff:{value:-new Date("0001-01-01").valueOf()},time_diff:{get:function(){var e=this.get_user_param("time_diff","number");return!e||isNaN(e)||e<621355716e5||e>62135622e6?this.js_time_diff:e}},set_user_param:{value:function(t,a){var i=a;"object"==typeof a?i=JSON.stringify(a):a===!1&&(i=""),e.setItem($p.job_prm.local_storage_prefix+t,i),n[t]=a}},get_user_param:{value:function(t,a){return!n.hasOwnProperty(t)&&e&&(n[t]=this.fetch_type(e.getItem($p.job_prm.local_storage_prefix+t),a)),n[t]}},promise:{value:function(e,n){return new Promise(function(a,i){t.alasql(e,n||[],function(e,t){t?i(t):a(e)})})}},save_options:{value:function(e,n){return t.set_user_param(e+"_"+n.name,n)}},restore_options:{value:function(e,n){var a=t.get_user_param(e+"_"+n.name,"object");for(var i in a)if("object"!=typeof a[i])n[i]=a[i];else{n[i]||(n[i]={});for(var s in a[i])n[i][s]=a[i][s]}return n}},fetch_type:{value:function(e,t){if("object"==t){try{e=JSON.parse(e)}catch(t){e={}}return e}return"number"==t?$p.utils.fix_number(e,!0):"date"==t?$p.utils.fix_date(e,!0):"boolean"==t?$p.utils.fix_boolean(e):e}},alasql:{value:"undefined"!=typeof alasql?alasql:require("alasql")},init_params:{value:function(){if(!$p.job_prm.local_storage_prefix&&!$p.job_prm.create_tables)return Promise.resolve();e="undefined"==typeof localStorage?"undefined"==typeof WorkerGlobalScope?new require("node-localstorage").LocalStorage("./localstorage"):{setItem:function(e,t){},getItem:function(e){}}:localStorage;var n,a=[{p:"user_name",v:"",t:"string"},{p:"user_pwd",v:"",t:"string"},{p:"browser_uid",v:$p.utils.generate_guid(),t:"string"},{p:"zone",v:$p.job_prm.hasOwnProperty("zone")?$p.job_prm.zone:1,t:$p.job_prm.zone_is_string?"string":"number"},{p:"enable_save_pwd",v:$p.job_prm.enable_save_pwd,t:"boolean"},{p:"autologin",v:"",t:"boolean"},{p:"skin",v:"dhx_web",t:"string"},{p:"rest_path",v:"",t:"string"}];$p.job_prm.additional_params&&(a=a.concat($p.job_prm.additional_params)),e.getItem($p.job_prm.local_storage_prefix+"zone")||(n=$p.job_prm.hasOwnProperty("zone")?$p.job_prm.zone:1),$p.job_prm.url_prm.hasOwnProperty("zone")&&(n=$p.job_prm.zone_is_string?$p.job_prm.url_prm.zone:$p.utils.fix_number($p.job_prm.url_prm.zone,!0)),void 0!==n&&t.set_user_param("zone",n),a.forEach(function(e){(void 0==t.get_user_param(e.p,e.t)||!t.get_user_param(e.p,e.t)&&e.p.indexOf("url")!=-1)&&t.set_user_param(e.p,$p.job_prm.hasOwnProperty(e.p)?$p.job_prm[e.p]:e.v)});var i={path:t.get_user_param("couch_path","string")||$p.job_prm.couch_path||"",zone:t.get_user_param("zone","number"),prefix:$p.job_prm.local_storage_prefix,suffix:t.get_user_param("couch_suffix","string")||"",user_node:$p.job_prm.user_node,noreplicate:$p.job_prm.noreplicate};i.path&&(t.__define("pouch",{value:new Pouch}),t.pouch.init(i)),this.create_tables&&(this.alasq(this.create_tables,[]),this.create_tables="")}},drop_tables:{value:function(e){function n(){s--,s<=0?setTimeout(e,10):a()}function a(){var e=o[s-1].tableid;"_"==e.substr(0,1)?n():t.alasql("drop table IF EXISTS "+e,[],n)}function i(e){o=e,(s=e.length)?a():n()}var s=0,o=[];t.alasql("SHOW TABLES",[],i)}}}),this.__define({aladb:{value:new this.alasql.Database("md")}})}function Col_struct(e,t,n,a,i,s){this.id=e,this.width=t,this.type=n,this.align=a,this.sort=i,this.caption=s}function InterfaceObjs(){function e(e,t,n){if(this.layout=e.attachLayout({pattern:"2U",cells:[{id:"a",text:"Разделы",collapsed_text:"Разделы",width:220},{id:"b",text:"Раздел",header:!1}],offsets:{top:0,right:0,bottom:0,left:0}}),this.tree=this.layout.cells("a").attachTreeView(),this.tree.attachEvent("onSelect",function(e,t){if(t){var a=$p.md.mgr_by_class_name(e);a instanceof DataProcessorsManager?a.form_rep(this.layout.cells("b"),n||{hide_header:!0}):a&&a.form_list(this.layout.cells("b"),n||{hide_header:!0})}}.bind(this)),!t){var a=$p.md.get_classes();t=[];for(var i in a)a[i].length&&t.push(i)}1==t.length?$p.md.get_classes()[t[0]].forEach(function(e){var n=t[0]+"."+e,a=$p.md.get(n);a.hide||(this.tree.addItem(n,a.list_presentation||a.synonym),this.tree.setItemIcons(n,{file:"icon_1c_"+t[0]}))}.bind(this)):t.forEach(function(e){this.tree.addItem(e,$p.msg["meta_"+e]),this.tree.setItemIcons(e,{file:"icon_1c_"+e,folder_opened:"icon_1c_"+e,folder_closed:"icon_1c_"+e}),$p.md.get_classes()[e].forEach(function(t){var n=e+"."+t,a=$p.md.get(n);a.hide||(this.tree.addItem(n,a.list_presentation||a.synonym,e),this.tree.setItemIcons(n,{file:"icon_1c_"+e}))}.bind(this))}.bind(this))}function t(e){e.attachHTMLString($p.injected_data["view_settings.html"]),this.cont=e.cell.querySelector(".dhx_cell_cont_tabbar"),this.cont.style.overflow="auto",this.form2=function(e){var t=new dhtmlXForm(e,[{type:"settings",labelWidth:80,position:"label-left"},{type:"label",labelWidth:320,label:"Адрес CouchDB",className:"label_options"},{type:"input",inputWidth:220,name:"couch_path",label:"Путь:",validate:"NotEmpty"},{type:"template",label:"",value:"",note:{text:"Можно указать как относительный, так и абсолютный URL публикации CouchDB",width:320}},{type:"label",labelWidth:320,label:"Адрес http сервиса 1С",className:"label_options"},{type:"input",inputWidth:220,name:"rest_path",label:"Путь",validate:"NotEmpty"},{type:"template",label:"",value:"",note:{text:"Можно указать как относительный, так и абсолютный URL публикации 1С OData",width:320}},{type:"label",labelWidth:320,label:"Значение разделителя данных",className:"label_options"},{type:"input",inputWidth:220,name:"zone",label:"Зона:",numberFormat:["0","",""],validate:"NotEmpty,ValidInteger"},{type:"template",label:"",value:"",note:{text:"Для неразделенной публикации, зона = 0",width:320}},{type:"label",labelWidth:320,label:"Суффикс базы пользователя",className:"label_options"},{type:"input",inputWidth:220,name:"couch_suffix",label:"Суффикс:"},{type:"template",label:"",value:"",note:{text:"Назначается абоненту при регистрации",width:320}},{type:"block",blockOffset:0,name:"block_buttons",list:[{type:"button",name:"save",value:"<i class='fa fa-floppy-o fa-lg'></i>",tooltip:"Применить настройки и перезагрузить программу"},{type:"newcolumn"},{type:"button",offsetLeft:20,name:"reset",value:"<i class='fa fa-refresh fa-lg'></i>",tooltip:"Стереть справочники и перезаполнить данными сервера"}]}]);return t.cont.style.fontSize="100%",["zone","couch_path","couch_suffix","rest_path"].forEach(function(e){"zone"==e?t.setItemValue(e,$p.wsql.get_user_param(e)):t.setItemValue(e,$p.wsql.get_user_param(e)||$p.job_prm[e])}),t.attachEvent("onChange",function(e,t,n){$p.wsql.set_user_param(e,"enable_save_pwd"==e?n||"":t)}),t.disableItem("couch_suffix"),$p.job_prm.rest_path||t.disableItem("rest_path"),t.attachEvent("onButtonClick",function(e){"save"==e?($p.wsql.pouch.log_out(),setTimeout(function(){$p.eve.redirect=!0,location.reload(!0)},1e3)):"reset"==e&&dhtmlx.confirm({title:"Сброс данных",text:"Стереть справочники и перезаполнить данными сервера?",cancel:$p.msg.cancel,callback:function(e){e&&$p.wsql.pouch.reset_local_data()}})}),t}(this.cont.querySelector("[name=form2]").firstChild),this.form1=function(e){var t=new dhtmlXForm(e,[{type:"settings",labelWidth:320,position:"label-left"},{type:"label",label:"Тип устройства",className:"label_options"},{type:"block",blockOffset:0,name:"block_device_type",list:[{type:"settings",labelAlign:"left",position:"label-right"},{type:"radio",name:"device_type",labelWidth:120,label:'<i class="fa fa-desktop"></i> Компьютер',value:"desktop"},{type:"newcolumn"},{type:"radio",name:"device_type",labelWidth:150,label:'<i class="fa fa-mobile fa-lg"></i> Телефон, планшет',value:"phone"}]},{type:"template",label:"",value:"",note:{text:"Класс устройства определяется автоматически, но пользователь может задать его явно",width:320}},{type:"label",label:"Сохранять пароль пользователя",className:"label_options"},{type:"checkbox",name:"enable_save_pwd",label:"Разрешить:",labelWidth:90,checked:$p.wsql.get_user_param("enable_save_pwd","boolean")},{type:"template",label:"",value:"",note:{text:"Не рекомендуется, если к компьютеру имеют доступ посторонние лица",width:320}},{type:"template",label:"",value:"",note:{text:"",width:320}},{type:"label",label:"Подключаемые модули",className:"label_options"},{type:"input",position:"label-top",inputWidth:320,name:"modifiers",label:"Модификаторы:",value:$p.wsql.get_user_param("modifiers"),rows:3,style:"height:80px;"},{type:"template",label:"",value:"",note:{text:"Список дополнительных модулей",width:320}}]);return t.cont.style.fontSize="100%",t.checkItem("device_type",$p.job_prm.device_type),t.attachEvent("onChange",function(e,t,n){$p.wsql.set_user_param(e,"enable_save_pwd"==e?n||"":t)}),t.disableItem("modifiers"),t.getInput("modifiers").onchange=function(){$p.wsql.set_user_param("modifiers",this.value)},t}(this.cont.querySelector("[name=form1]").firstChild)}var n=this;this.clear_svgs=function(e){for("string"==typeof e&&(e=document.getElementById(e));e.firstChild;)e.removeChild(e.firstChild)},this.get_offset=function(e){var t={left:0,top:0};if(e.offsetParent)do t.left+=e.offsetLeft,t.top+=e.offsetTop;while(e=e.offsetParent);return t},this.normalize_xml=function(e){if(!e)return"";var t={"&":"&",'"':""","'":"'","<":"<",">":">"};return e.replace(/[&"'<>]/g,function(e){return t[e]})},this.scale_svg=function(e,t,n){var a,i,s,o,r,l,c,p,d,u={},m="number"==typeof t?t:t.height,f="number"==typeof t?(1.5*t).round(0):t.width,h="number"==typeof t?1/0:t.zoom||1/0;r=e.indexOf(">"),c=e.substring(5,r),s=c.split(" "),o=e.substr(r+1),o=o.substr(0,o.length-6);for(a in s)e=s[a].split("="),"width,height,x,y".indexOf(e[0])!=-1&&(e[1]=Number(e[1].replace(/"/g,"")),u[e[0]]=e[1]);(l=c.indexOf("viewBox="))!=-1?(p=c.substring(l+9),d='viewBox="'+p.substring(0,p.indexOf('"'))+'"'):d='viewBox="'+(u.x||0)+" "+(u.y||0)+" "+(u.width-n)+" "+(u.height-n)+'"';var _=u.height,g=u.width;return i=(m-n)/_,u.height=m,u.width=(g*i).round(0),u.width>f&&(i=(f-n)/g,u.height=(_*i).round(0),u.width=f),i>h&&(i=h,u.height=(_*i).round(0),u.width=(g*i).round(0)),u.x=(u.x*i).round(0),u.y=(u.y*i).round(0),'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="'+u.width+'" height="'+u.height+'" x="'+u.x+'" y="'+u.y+'" xml:space="preserve" '+d+">"+o+"</svg>"},this.bind_help=function(e,t){function n(e){if(!e.help_path)return void $p.msg.show_msg({title:"Справка",type:"alert-info",text:$p.msg.not_implemented})}e instanceof dhtmlXCellObject||(!e.help_path&&t&&(e.help_path=t),e.button("help").show(),e.button("help").enable(),e.attachEvent("onHelp",n))},this.set_hash=function(e,t,a,i){var s={},o=$p.job_prm.parse_url();1==arguments.length&&"object"==typeof e&&(s=e,s.hasOwnProperty("obj")&&(e=s.obj,delete s.obj),s.hasOwnProperty("ref")&&(t=s.ref,delete s.ref),s.hasOwnProperty("frm")&&(a=s.frm,delete s.frm),s.hasOwnProperty("view")&&(i=s.view,delete s.view)),void 0===e&&(e=o.obj||""),void 0===t&&(t=o.ref||""),void 0===a&&(a=o.frm||""),void 0===i&&(i=o.view||"");var r="obj="+e+"&ref="+t+"&frm="+a+"&view="+i;for(var l in s)r+="&"+l+"="+s[l];location.hash.substr(1)==r?n.hash_route():location.hash=r},this.hash_route=function(e){var t,a=$p.job_prm.parse_url(),i=$p.eve.callEvent("hash_route",[a]);if(i===!1||n.before_route&&n.before_route(e)===!1||$p.ajax.authorized&&(a.ref&&"undefined"!=typeof _md?(t=_md.mgr_by_class_name(a.obj),t&&t[a.frm||"form_obj"](n.docs,a.ref)):a.view&&n.swith_view&&n.swith_view(a.view)),e)return n.cancel_bubble(e)},this.cancel_bubble=function(e){var t=e||event;return t&&t.stopPropagation&&t.stopPropagation(),t&&!t.cancelBubble&&(t.cancelBubble=!0),!1},this.Col_struct=Col_struct,this.init_sidebar=function(e,t,a){n.btn_auth_sync=new n.OBtnAuthSync,n.btns_nav=function(e){return n.btn_auth_sync.bind(new n.OTooolBar({wrapper:e,class_name:"md_otbnav",width:"260px",height:"28px",top:"3px",right:"3px",name:"right",buttons:t,onclick:function(e){return n.main.cells(e).setActive(!0),!1}}))},n.main=new dhtmlXSideBar({parent:document.body,icons_path:a||"dist/imgs/",width:180,header:!0,template:"tiles",autohide:!0,items:e,offsets:{top:0,right:0,bottom:0,left:0}}),n.main.attachEvent("onSelect",function(e){var t=$p.job_prm.parse_url();t.view!=e&&n.set_hash(t.obj,t.ref,t.frm,e),n["view_"+e](n.main.cells(e))}),n.main.progressOn();var i=$p.job_prm.parse_url();i.view&&n.main.getAllItems().indexOf(i.view)!=-1?setTimeout(n.hash_route):n.set_hash(i.obj,i.ref,i.frm,"doc")},this.All_meta_objs=e,this.Setting2col=t,this.do_reload=function(){function e(){dhtmlx.confirm({title:$p.msg.file_new_date_title,text:$p.msg.file_new_date,ok:"Перезагрузка",cancel:"Продолжить",callback:function(n){n?($p.wsql.pouch.log_out(),setTimeout(function(){$p.eve.redirect=!0,location.reload(!0)},1e3)):(t++,setTimeout(e,3e4*t))}})}var t=0;e()}}function Pouch(){var e,t,n,a,i=this,s={};i.__define({DB:{value:"undefined"==typeof PouchDB?require("pouchdb-core").plugin(require("pouchdb-adapter-memory")).plugin(require("pouchdb-adapter-http")).plugin(require("pouchdb-replication")).plugin(require("pouchdb-mapreduce")):PouchDB},init:{value:function(e){s._mixin(e),s.path&&0!=s.path.indexOf("http")&&"undefined"!=typeof location&&(s.path=location.protocol+"//"+location.host+s.path)}},local:{get:function(){if(!e){var t={auto_compaction:!0,revs_limit:2};e={ram:new i.DB(s.prefix+s.zone+"_ram",t),doc:new i.DB(s.prefix+s.zone+"_doc",t),meta:new i.DB(s.prefix+"meta",t),sync:{}}}return s.path&&!e._meta&&(e._meta=new i.DB(s.path+"meta",{auth:{username:"guest",password:"meta"},skip_setup:!0}),i.run_sync(e.meta,e._meta,"meta")),e}},remote:{get:function(){return!t&&n&&(t={ram:new i.DB(s.path+s.zone+"_ram",{auth:{username:n.username,password:n.password},skip_setup:!0}),doc:new i.DB(s.path+s.zone+"_doc"+s.suffix,{auth:{username:n.username,password:n.password},skip_setup:!0})}),t}},log_in:{value:function(e,t){return void 0==e&&void 0==t&&(e=$p.job_prm.guest_name,t=$p.aes.Ctr.decrypt($p.job_prm.guest_pwd)),n?n.username==e?Promise.resolve():Promise.reject():$p.ajax.get_ex(s.path+s.zone+"_ram",{username:e,password:t}).then(function(a){return n={username:e,password:t},setTimeout(function(){dhx4.callEvent("log_in",[e])}),{ram:i.run_sync(i.local.ram,i.remote.ram,"ram"),doc:i.run_sync(i.local.doc,i.remote.doc,"doc")}})}},log_out:{value:function(){if(n){if(e.sync.doc)try{e.sync.doc.cancel()}catch(e){}if(e.sync.ram)try{e.sync.ram.cancel()}catch(e){}n=null}t&&t.ram&&delete t.ram,t&&t.doc&&delete t.doc,t=null,dhx4.callEvent("log_out")}},reset_local_data:{value:function(){var e=i.local.ram.destroy.bind(i.local.ram),t=i.local.doc.destroy.bind(i.local.doc),n=function(){setTimeout(function(){$p.eve.redirect=!0,location.reload(!0)},1e3)};i.log_out(),setTimeout(function(){e().then(t).catch(t).then(n).catch(n)},1e3)}},load_data:{value:function(){var e={limit:800,include_docs:!0},t={total_rows:0,limit:e.limit,page:0,start:Date.now()};return new Promise(function(n,s){function o(){i.local.ram.allDocs(e,function(r,l){l?(t.page++,t.total_rows=l.total_rows,t.duration=Date.now()-t.start,$p.eve.callEvent("pouch_load_data_page",[t]),i.load_changes(l,e)?o():(n(),a=!0,$p.eve.callEvent("pouch_load_data_loaded",[t]),t.note="pouch_load_data_loaded",$p.record_log(t))):r&&(s(r),$p.eve.callEvent("pouch_load_data_error",[r]))})}i.local.ram.info().then(function(e){e.doc_count>=($p.job_prm.pouch_ram_doc_count||10)?($p.eve.callEvent("pouch_load_data_start",[t]),o()):($p.eve.callEvent("pouch_load_data_error",[e]),s(e))})})}},authorized:{get:function(){return n&&n.username}},data_loaded:{get:function(){return!!a}},run_sync:{value:function(t,n,s){var o,r;return t.info().then(function(e){return o=e,n.info()}).then(function(e){return"ram"!=s?e:n.get("data_version").then(function(t){return t.version!=$p.wsql.get_user_param("couch_ram_data_version")&&($p.wsql.get_user_param("couch_ram_data_version")&&(e=i.reset_local_data()),$p.wsql.set_user_param("couch_ram_data_version",t.version)),e}).catch(function(e){$p.record_log(e)}).then(function(){return e})}).then(function(l){if(l){"ram"==s&&o.doc_count<($p.job_prm.pouch_ram_doc_count||10)?(r={total_rows:l.doc_count,local_rows:o.doc_count,docs_written:0,limit:200,page:0,start:Date.now()},$p.eve.callEvent("pouch_load_data_start",[r])):"doc"==s&&setTimeout(function(){$p.eve.callEvent("pouch_doc_sync_start")});var c={live:!0,retry:!0,batch_size:300,batches_limit:8};return"meta"==s?c.filter="auth/meta":$p.job_prm.pouch_filter&&$p.job_prm.pouch_filter[s]&&(c.filter=$p.job_prm.pouch_filter[s]),"ram"==s||"meta"==s||$p.wsql.get_user_param("zone")==$p.job_prm.zone_demo?e.sync[s]=t.replicate.from(n,c):e.sync[s]=t.sync(n,c),e.sync[s].on("change",function(e){"ram"==s?(i.load_changes(e),o.doc_count<($p.job_prm.pouch_ram_doc_count||10)&&(r.page++,r.docs_written=e.docs_written,r.duration=Date.now()-r.start,$p.eve.callEvent("pouch_load_data_page",[r]),r.docs_written>=r.total_rows&&(a=!0,$p.eve.callEvent("pouch_load_data_loaded",[r]),r.note="pouch_load_data_loaded",$p.record_log(r)))):(e.update_only=!0,i.load_changes(e)),$p.eve.callEvent("pouch_change",[s,e])}).on("paused",function(e){e&&$p.eve.callEvent("pouch_paused",[s,e])}).on("active",function(e){$p.eve.callEvent("pouch_active",[s,e])}).on("denied",function(e){$p.eve.callEvent("pouch_denied",[s,e])}).on("complete",function(e){$p.eve.callEvent("pouch_complete",[s,e])}).on("error",function(e){$p.eve.callEvent("pouch_error",[s,e])}),e.sync[s]}})}},load_obj:{value:function(e){return e._manager.pouch_db.get(e._manager.class_name+"|"+e.ref).then(function(t){delete t._id,delete t._rev,e._mixin(t)._set_loaded()}).catch(function(e){if(404!=e.status)throw e}).then(function(t){return e})}},save_obj:{value:function(e,t){var n=e._obj._clone(),a=t.db||e._manager.pouch_db;return n._id=e._manager.class_name+"|"+e.ref,delete n.ref,t.attachments&&(n._attachments=t.attachments),(e.is_new()?Promise.resolve():a.get(n._id)).then(function(e){if(e){n._rev=e._rev;for(var t in e._attachments)n._attachments||(n._attachments={}),n._attachments[t]||(n._attachments[t]=e._attachments[t])}}).catch(function(e){if(404!=e.status)throw e}).then(function(){return a.put(n)}).then(function(){if(e.is_new()&&e._set_loaded(e.ref),n._attachments){e._attachments||(e._attachments={});for(var a in n._attachments)e._attachments[a]&&n._attachments[a].stub||(e._attachments[a]=n._attachments[a])}return n=null,t=null,e})}},load_changes:{value:function(e,t){var n,a,i,s,o={};if(t)n=e.rows;else if(e.direction){if("pull"!=e.direction)return;n=e.change.docs}else n=e.docs;if(n.length>0){t&&(t.startkey=n[n.length-1].key,t.skip=1),n.forEach(function(e){if(a=t?e.doc:e,!a)if(e.value&&e.value.deleted)a={_id:e.id,_deleted:!0};else if(e.error)return;s=a._id.split("|"),i=s[0].split("."),a.ref=s[1],delete a._id,delete a._rev,o[i[0]]||(o[i[0]]={}),o[i[0]][i[1]]||(o[i[0]][i[1]]=[]),o[i[0]][i[1]].push(a)});for(var r in o)for(i in o[r])$p[r]&&$p[r][i]&&$p[r][i].load_array(o[r][i],!e.update_only||"update_only");return o=e=n=a=null,!0}return!1}},backup_database:{value:function(e){}},restore_database:{value:function(e){}}})}function Messages(){this.toString=function(){return"Интернационализация сообщений"},"undefined"!=typeof window&&"dhtmlx"in window&&(this.show_msg=function(e,t){if(e){if("string"==typeof e){if($p.iface.synctxt)return void $p.iface.synctxt.show_message(e);e={type:"info",text:e}}t&&"function"==typeof t.setText&&t.setText(e.text),dhtmlx.message(e)}},this.check_soap_result=function(e){return e?"limit_query"==e.error?($p.iface.docs.progressOff(),$p.msg.show_msg({type:"alert-warning",text:$p.msg.limit_query.replace("%1",e.queries).replace("%2",e.queries_avalable),title:$p.msg.srv_overload}),!0):"network"==e.error||"empty"==e.error?($p.iface.docs.progressOff(),$p.msg.show_msg({type:"alert-warning",text:$p.msg.error_network,title:$p.msg.error_critical}),!0):e.error&&e.error_description?($p.iface.docs.progressOff(),e.error_description.indexOf("Недостаточно прав")!=-1&&(e.error_type="alert-warning",e.error_title=$p.msg.error_rights),$p.msg.show_msg({type:e.error_type||"alert-error",text:e.error_description,title:e.error_title||$p.msg.error_critical}),!0):e.error&&!e.messages?($p.iface.docs.progressOff(),$p.msg.show_msg({type:"alert-error",title:$p.msg.error_critical,text:$p.msg.unknown_error.replace("%1","unknown_error")}),!0):void 0:($p.msg.show_msg({type:"alert-error",text:$p.msg.empty_response,title:$p.msg.error_critical}),!0)},this.show_not_implemented=function(){$p.msg.show_msg({type:"alert-warning",text:$p.msg.not_implemented,title:$p.msg.main_title})})}function Meta(){function e(e){return e.info().then(function(){return e.get("meta")}).then(function(n){return $p._patch(t,n),n=null,e.get("meta_patch")}).then(function(e){return $p._patch(t,e),e=null,delete t._id,delete t._rev,t})}var t={enm:{accumulation_record_type:[{order:0,name:"debit",synonym:"Приход"},{order:1,name:"credit",synonym:"Расход"}],comparison_types:[{order:0,name:"gt",synonym:"Больше"},{order:1,name:"gte",synonym:"Больше или равно"},{order:2,name:"lt",synonym:"Меньше"},{order:3,name:"lte",synonym:"Меньше или равно "},{order:4,name:"eq",synonym:"Равно"},{order:5,name:"ne",synonym:"Не равно"},{order:6,name:"in",synonym:"В списке"},{order:7,name:"nin",synonym:"Не в списке"},{order:8,name:"lke",synonym:"Подобно "},{order:9,name:"nlk",synonym:"Не подобно"}]},cat:{meta_objs:{},meta_fields:{},scheme_settings:{name:"scheme_settings",splitted:!0,synonym:"Настройки отчетов и списков",illustration:"",obj_presentation:"",list_presentation:"",input_by_string:["name"],hierarchical:!1,has_owners:!1,group_hierarchy:!0,main_presentation_name:!0,code_length:0,fields:{obj:{synonym:"Объект",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:250}},user:{synonym:"Пользователь",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:50}},predefined_name:{synonym:"",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:256}}},tabular_sections:{ +available_fields:{name:"available_fields",synonym:"Доступные поля",tooltip:"Состав, порядок и ширина колонок",fields:{parent:{synonym:"Родитель",multiline_mode:!1,tooltip:"Для плоского списка, родитель пустой",type:{types:["string"],str_len:100}},use:{synonym:"Использование",multiline_mode:!1,tooltip:"",type:{types:["boolean"]}},field:{synonym:"Поле",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}},width:{synonym:"Ширина",multiline_mode:!1,tooltip:"",type:{types:["number"],digits:6,fraction_figits:0}},caption:{synonym:"Заголовок",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}}}},sort_fields:{name:"sort_fields",synonym:"Поля сортировки",tooltip:"",fields:{parent:{synonym:"Родитель",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}},field:{synonym:"Поле",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}}}},grouping_fields:{name:"grouping_fields",synonym:"Поля группировки",tooltip:"",fields:{parent:{synonym:"Родитель",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}},field:{synonym:"Поле",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}}}},selection:{name:"selection",synonym:"Отбор",tooltip:"",fields:{parent:{synonym:"Родитель",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}},use:{synonym:"Использование",multiline_mode:!1,tooltip:"",type:{types:["boolean"]}},left_value:{synonym:"Левое значение",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}},comparison_type:{synonym:"Вид сравнения",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}},right_value:{synonym:"Правое значение",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}}}},scheme:{name:"scheme",synonym:"Структура",tooltip:"",fields:{parent:{synonym:"Родитель",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:10}},kind:{synonym:"Вид раздела отчета",multiline_mode:!1,tooltip:"список, таблица, группировка строк, группировка колонок",type:{types:["string"],str_len:10}}}}},cachable:"doc"}},doc:{},ireg:{log:{name:"log",note:"",synonym:"Журнал событий",dimensions:{date:{synonym:"Дата",multiline_mode:!1,tooltip:"Время события",type:{types:["number"],digits:15,fraction_figits:0}},sequence:{synonym:"Порядок",multiline_mode:!1,tooltip:"Порядок следования",type:{types:["number"],digits:6,fraction_figits:0}}},resources:{class:{synonym:"Класс",multiline_mode:!1,tooltip:"Класс события",type:{types:["string"],str_len:100}},note:{synonym:"Комментарий",multiline_mode:!0,tooltip:"Текст события",type:{types:["string"],str_len:0}},obj:{synonym:"Объект",multiline_mode:!0,tooltip:"Объект, к которому относится событие",type:{types:["string"],str_len:0}}}}},areg:{},dp:{},rep:{},cch:{},cacc:{}};_md=this,_md.create_managers=function(){},_md.init=function(n){function a(){return!n||i||s?e(n||$p.wsql.pouch.local.meta).then(function(){return i?void _md.create_managers():t}).catch($p.record_log):($p._patch(t,n),n=null,_md.create_managers(),void 0)}var i=!n||$p.wsql.pouch&&n==$p.wsql.pouch.local.meta,s=n&&$p.wsql.pouch&&n==$p.wsql.pouch.local._meta;return $p.on("pouch_change",function(e,n){"meta"==e&&(t?$p.iface&&$p.iface.do_reload&&setTimeout(function(){$p.iface.do_reload()},3e3):a())}),a()},_md.get=function(e,n){var a=e.split(".");if(!n)return t[a[0]][a[1]];var i={multiline_mode:!1,note:"",synonym:"",tooltip:"",type:{is_ref:!1,types:["string"]}},s="doc,tsk,bp".indexOf(a[0])!=-1,o="cat,cch,cacc,tsk".indexOf(a[0])!=-1;return s&&"number_doc"==n?(i.synonym="Номер",i.tooltip="Номер документа",i.type.str_len=11):s&&"date"==n?(i.synonym="Дата",i.tooltip="Дата документа",i.type.date_part="date_time",i.type.types[0]="date"):s&&"posted"==n?(i.synonym="Проведен",i.type.types[0]="boolean"):o&&"id"==n?i.synonym="Код":o&&"name"==n?i.synonym="Наименование":"_deleted"==n?(i.synonym="Пометка удаления",i.type.types[0]="boolean"):"is_folder"==n?(i.synonym="Это группа",i.type.types[0]="boolean"):"ref"==n?(i.synonym="Ссылка",i.type.is_ref=!0,i.type.types[0]=e):i=n?t[a[0]][a[1]].fields[n]:t[a[0]][a[1]],i},_md.get_classes=function(){var e={};for(var n in t){e[n]=[];for(var a in t[n])e[n].push(a)}return e},_md.sql_type=function(e,t,n,a){var i;return i="type"==t&&"cch_properties"==e.table_name||"svg"==t&&"cat_production_params"==e.table_name?" JSON":n.is_ref||n.types.indexOf("guid")!=-1?a?n.types.every(function(e){return 0==e.indexOf("enm.")})?" character varying(100)":n.hasOwnProperty("str_len")?" character varying("+Math.max(36,n.str_len)+")":" uuid":" CHAR":n.hasOwnProperty("str_len")?a?n.str_len?" character varying("+n.str_len+")":" text":" CHAR":n.date_part?a&&"date"!=n.date_part?"date_time"==n.date_part?" timestamp with time zone":" time without time zone":" Date":n.hasOwnProperty("digits")?0==n.fraction_figits?a?n.digits<7?" integer":" bigint":" INT":a?" numeric("+n.digits+","+n.fraction_figits+")":" FLOAT":n.types.indexOf("boolean")!=-1?" BOOLEAN":n.types.indexOf("json")!=-1?" JSON":a?" character varying(255)":" CHAR"},_md.sql_composite=function(e,t,n,a){var i="";return e[t].type.types.length>1&&"type"!=t&&(n=n?n.substr(0,29)+"_T":t.substr(0,29)+"_T",i=a?', "'+n+'" character varying(255)':_md.sql_mask(n)+" CHAR"),i},_md.sql_mask=function(e,t){return", "+(t?"_t_.":"")+("`"+e+"`")},_md.mgr_by_class_name=function(e){if(e){var t=e.split(".");if(t[1]&&$p[t[0]])return $p[t[0]][t[1]]}},_md.value_mgr=function(e,t,n,a,i){function s(e){return e&&1==n.types.length&&(n._mgr=e),e}var o,r,l,c,p;if(n._mgr)return n._mgr;if(1==n.types.length){if(l=n.types[0].split("."),l.length>1&&$p[l[0]])return s($p[l[0]][l[1]])}else if(i&&i.type&&(l=i.type.split("."),l.length>1&&$p[l[0]]))return s($p[l[0]][l[1]]);if(o=e.property||e.param,"value"==t&&o){if($p.utils.is_data_obj(o))r=o;else{if(!$p.utils.is_guid(o))return;r=$p.cch.properties.get(o,!1)}if($p.utils.is_data_obj(r)){if(r.is_new())return $p.cat.property_values;if(c=[],r.type.types.forEach(function(e){l=e.split("."),l.length>1&&$p[l[0]][l[1]]&&c.push($p[l[0]][l[1]])}),1==c.length||e[t]==$p.utils.blank.guid)return s(c[0]);if(a)return c;if((o=e[t])instanceof DataObj)return o._manager;if($p.utils.is_guid(o)&&o!=$p.utils.blank.guid)for(var d in c)if(p=c[d],p.get(o,!1,!0))return p}}else{if(c=[],n.types.forEach(function(e){l=e.split("."),l.length>1&&$p[l[0]][l[1]]&&c.push($p[l[0]][l[1]])}),1==c.length||e[t]==$p.utils.blank.guid)return s(c[0]);if(a)return c;if((o=e[t])instanceof DataObj)return o._manager;if($p.utils.is_guid(o)&&o!=$p.utils.blank.guid)for(var d in c)if(p=c[d],p.get(o,!1,!0))return p}},_md.control_by_type=function(e,t){var n;return n="boolean"==typeof t&&e.types.indexOf("boolean")!=-1?"ch":"number"==typeof t&&e.digits?e.fraction_figits<5?"calck":"edn":t instanceof Date&&e.date_part?"dhxCalendar":e.is_ref?"ocombo":e.date_part?"dhxCalendar":e.digits?e.fraction_figits<5?"calck":"edn":"boolean"==e.types[0]?"ch":e.hasOwnProperty("str_len")&&(e.str_len>=100||0==e.str_len)?"txt":"ed"},_md.ts_captions=function(e,t,n){n||(n={});var a,i=_md.get(e).tabular_sections[t],s=_md.get(e).form,o=i.fields;if(s&&s.obj){if(!s.obj.tabular_sections[t])return;n._mixin(s.obj.tabular_sections[t])}else{"contact_information"===t&&(o={type:"",kind:"",presentation:""}),n.fields=["row"],n.headers="№",n.widths="40",n.min_widths="",n.aligns="",n.sortings="na",n.types="cntr";for(var r in o)a=i.fields[r],a.hide||(n.fields.push(r),n.headers+=","+(a.synonym?a.synonym.replace(/,/g," "):r),n.types+=","+_md.control_by_type(a.type),n.sortings+=",na")}return!0},_md.syns_js=function(e){var n={DeletionMark:"_deleted",Description:"name",DataVersion:"data_version",IsFolder:"is_folder",Number:"number_doc",Date:"date","Дата":"date",Posted:"posted",Code:"id",Parent_Key:"parent",Owner_Key:"owner",Owner:"owner",Ref_Key:"ref","Ссылка":"ref",LineNumber:"row"};return n[e]?n[e]:t.syns_js[t.syns_1с.indexOf(e)]||e},_md.syns_1с=function(e){var n={_deleted:"DeletionMark",name:"Description",is_folder:"IsFolder",number_doc:"Number",date:"Date",posted:"Posted",id:"Code",ref:"Ref_Key",parent:"Parent_Key",owner:"Owner_Key",row:"LineNumber"};return n[e]?n[e]:t.syns_1с[t.syns_js.indexOf(e)]||e},_md.printing_plates=function(e){if(e)for(var n in e.doc)t.doc[n].printing_plates=e.doc[n]},_md.class_name_from_1c=function(e){var t=e.split(".");return 1==t.length?"enm."+e:("Перечисление"==t[0]?e="enm.":"Справочник"==t[0]?e="cat.":"Документ"==t[0]?e="doc.":"РегистрСведений"==t[0]?e="ireg.":"РегистрНакопления"==t[0]?e="areg.":"РегистрБухгалтерии"==t[0]?e="accreg.":"ПланВидовХарактеристик"==t[0]?e="cch.":"ПланСчетов"==t[0]?e="cacc.":"Обработка"==t[0]?e="dp.":"Отчет"==t[0]&&(e="rep."),e+_md.syns_js(t[1]))},_md.class_name_to_1c=function(e){var t=e.split(".");return 1==t.length?"Перечисление."+e:("enm"==t[0]?e="Перечисление.":"cat"==t[0]?e="Справочник.":"doc"==t[0]?e="Документ.":"ireg"==t[0]?e="РегистрСведений.":"areg"==t[0]?e="РегистрНакопления.":"accreg"==t[0]?e="РегистрБухгалтерии.":"cch"==t[0]?e="ПланВидовХарактеристик.":"cacc"==t[0]?e="ПланСчетов.":"dp"==t[0]?e="Обработка.":"rep"==t[0]&&(e="Отчет."),e+_md.syns_1с(t[1]))},_md.create_tables=function(e,t){function n(){s--,0==s?e?e(l):alasql.utils.saveFile("create_tables.sql",l):a()}function a(){var e=o[s-1];l+=e.class[e.name].get_sql_struct(t)+"; ",n()}var i,s=0,o=[],r=_md.get_classes(),l=t&&t.postgres?"":"USE md; ";"enm,cch,cacc,cat,bp,tsk,doc,ireg,areg".split(",").forEach(function(e){for(i in r[e])o.push({class:$p[e],name:r[e][i]})}),s=o.length,a()}}function DataManager(e){var t=_md.get(e),n={after_create:[],after_load:[],before_save:[],after_save:[],value_change:[],add_row:[],del_row:[]};this.__define({cachable:{get:function(){return e.indexOf("enm.")!=-1?"ram":t.cachable?t.cachable:e.indexOf("doc.")!=-1||e.indexOf("dp.")!=-1||e.indexOf("rep.")!=-1?"doc":"ram"}},class_name:{value:e,writable:!1},alatable:{get:function(){return $p.wsql.aladb.tables[this.table_name]?$p.wsql.aladb.tables[this.table_name].data:[]}},metadata:{value:function(e){return e?t.fields[e]||t.tabular_sections[e]:t}},on:{value:function(e,t){if("object"==typeof e)for(var a in e)e.hasOwnProperty(a)&&n[a].push(e[a]);else n[e].push(t)}},off:{value:function(e,t){}},handle_event:{value:function(e,t,a){var i,s=[];return n[t].forEach(function(t){s!==!1&&(i=t.call(e,a),i===!1?s=i:i&&s.push(i))}),s===!1?s:s.length?1==s.length?s[0]:s.some(function(e){return"object"==typeof e&&e.then})?Promise.all(s):s:void 0}},by_ref:{value:{}}})}function RefDataManager(e){RefDataManager.superclass.constructor.call(this,e)}function DataProcessorsManager(e){DataProcessorsManager.superclass.constructor.call(this,e)}function EnumManager(e){EnumManager.superclass.constructor.call(this,e);var t=$p.md.get(e);for(var n in t)new EnumObj(t[n],this)}function RegisterManager(e){RegisterManager.superclass.constructor.call(this,e),this.push=function(e,t){t&&t!=e.ref?(delete this.by_ref[e.ref],this.by_ref[t]=e):this.by_ref[e.ref]=e},this.get=function(e,t,n){if(e?"string"==typeof e&&(e={ref:e}):e={},e.ref&&n)return t?Promise.resolve(this.by_ref[e.ref]):this.by_ref[e.ref];e.action="select";var a,i=$p.wsql.alasql(this.get_sql_struct(e),e._values);if(delete e.action,delete e._values,i.length)if(n)a=this.by_ref[this.get_ref(i[0])];else{a=[];for(var s in i)a.push(this.by_ref[this.get_ref(i[s])])}return t?Promise.resolve(a):a},this.unload_obj=function(e){delete this.by_ref[e],this.alatable.some(function(t,n,a){if(t.ref==e)return a.splice(n,1),!0})},this.load_array=function(e,t){for(var n,a,i=[],s=0;s<e.length;s++){if(n=this.get_ref(e[s]),a=this.by_ref[n],a||e[s]._deleted){if(a&&e[s]._deleted){a.unload();continue}(a.is_new()||t)&&(a._mixin(e[s]),a._set_loaded())}else a=new($p[this.obj_constructor()])(e[s],this),t&&a._set_loaded();i.push(a)}return i}}function InfoRegManager(e){InfoRegManager.superclass.constructor.call(this,e)}function AccumRegManager(e){AccumRegManager.superclass.constructor.call(this,e)}function CatManager(e){CatManager.superclass.constructor.call(this,e),this.metadata().hierarchical&&this.metadata().group_hierarchy&&$p[this.obj_constructor()].prototype.__define("is_folder",{get:function(){return this._obj.is_folder||!1},set:function(e){this._obj.is_folder=$p.utils.fix_boolean(e)},enumerable:!0,configurable:!0})}function ChartOfCharacteristicManager(e){ChartOfCharacteristicManager.superclass.constructor.call(this,e)}function ChartOfAccountManager(e){ChartOfAccountManager.superclass.constructor.call(this,e)}function DocManager(e){DocManager.superclass.constructor.call(this,e)}function TaskManager(e){TaskManager.superclass.constructor.call(this,e)}function BusinessProcessManager(e){BusinessProcessManager.superclass.constructor.call(this,e)}function LogManager(){LogManager.superclass.constructor.call(this,"ireg.log");var e;this.__define({record:{value:function(t){t instanceof Error?(console&&console.log(t),t={class:"error",note:t.toString()}):"object"!=typeof t||t.class||t.obj?"object"!=typeof t&&(t={note:t}):t={class:"obj",obj:t,note:t.note},t.date=Date.now()+$p.wsql.time_diff,e||(e=alasql.compile("select MAX(`sequence`) as `sequence` from `ireg_log` where `date` = ?"));var n=e([t.date]);n.length&&void 0!==n[0].sequence?t.sequence=parseInt(n[0].sequence)+1:t.sequence=0,t.class||(t.class="note"),$p.wsql.alasql("insert into `ireg_log` (`ref`, `date`, `sequence`, `class`, `note`, `obj`) values (?,?,?,?,?,?)",[t.date+"¶"+t.sequence,t.date,t.sequence,t.class,t.note,t.obj?JSON.stringify(t.obj):""])}},backup:{value:function(e,t){}},restore:{value:function(e,t){}},clear:{value:function(e,t){}},show:{value:function(e){}},get:{value:function(e,t,n){if("object"==typeof e&&(e=e.ref||""),!this.by_ref[e]){if(t===!1)return;var a=e.split("¶");$p.wsql.alasql("select * from `ireg_log` where date="+a[0]+" and sequence="+a[1]).forEach(function(e){new RegisterRow(e,this)}.bind(this))}return t?Promise.resolve(this.by_ref[e]):this.by_ref[e]}},get_sql_struct:{value:function(e){if(e&&"get_selection"==e.action){var t="select * from `ireg_log`";return e.date_from?t+=e.date_till?" where `date` >= ? and `date` <= ?":" where `date` >= ?":e.date_till&&(t+=" where `date` <= ?"),t}return LogManager.superclass.get_sql_struct.call(this,e)}},caption_flds:{value:function(e){var t='<column id="%1" width="%2" type="%3" align="%4" sort="%5">%6</column>',n=[],a="";if(n.push(new Col_struct("date","200","ro","left","server","Дата")),n.push(new Col_struct("class","100","ro","left","server","Класс")),n.push(new Col_struct("note","*","ro","left","server","Событие")),e.get_header){a="<head>";for(var i in n)a+=t.replace("%1",n[i].id).replace("%2",n[i].width).replace("%3",n[i].type).replace("%4",n[i].align).replace("%5",n[i].sort).replace("%6",n[i].caption);a+="</head>"}return{head:a,acols:n}}},data_to_grid:{value:function(e,t){var n="<?xml version='1.0' encoding='UTF-8'?><rows total_count='%1' pos='%2' set_parent='%3'>".replace("%1",e.length).replace("%2",t.start).replace("%3",t.set_parent||""),a=this.caption_flds(t);return n+=a.head,e.forEach(function(e){n+='<row id="'+e.ref+'"><cell>'+$p.moment(e.date-$p.wsql.time_diff).format("DD.MM.YYYY HH:mm:ss")+"."+e.sequence+"</cell><cell>"+(e.class||"")+"</cell><cell>"+(e.note||"")+"</cell></row>"}),n+"</rows>"}}})}function MetaObjManager(){MetaObjManager.superclass.constructor.call(this,"cat.meta_objs")}function MetaFieldManager(){MetaFieldManager.superclass.constructor.call(this,"cat.meta_fields")}function SchemeSettingsManager(){SchemeSettingsManager.superclass.constructor.call(this,"cat.scheme_settings")}function DataObj(e,t){var n,a={},i={},s={_is_new:!(this instanceof EnumObj)};return t instanceof DataProcessorsManager||t instanceof EnumManager||(n=t.get(e,!1,!0)),n?(e=null,n):(t instanceof EnumManager?i.ref=e.name:t instanceof RegisterManager?i.ref=t.get_ref(e):i.ref=$p.utils.fix_guid(e),this.__define({_obj:{value:i,configurable:!0},_ts_:{value:function(e){return a[e]||(a[e]=new TabularSection(e,this)),a[e]},configurable:!0},_manager:{value:t},_data:{value:s,configurable:!0}}),t.alatable&&t.push&&(t.alatable.push(i),t.push(this,i.ref)),void(e=null))}function CatObj(e,t){var n="";CatObj.superclass.constructor.call(this,e,t),this.__define("presentation",{get:function(){return this.name||this.id?this.name||this.id||this._metadata.obj_presentation||this._metadata.synonym:n},set:function(e){e&&(n=String(e))}}),e&&"object"==typeof e&&(e._not_set_loaded?(delete e._not_set_loaded,this._mixin(e)):(this._mixin(e),$p.utils.is_empty_guid(this.ref)||!e.id&&!e.name||this._set_loaded(this.ref))),e=null}function DocObj(e,t){var n="";DocObj.superclass.constructor.call(this,e,t),this.__define("presentation",{get:function(){return this.number_doc?(this._metadata.obj_presentation||this._metadata.synonym)+" №"+this.number_doc+" от "+$p.moment(this.date).format($p.moment._masks.ldt):n},set:function(e){e&&(n=String(e))}}),e&&"object"==typeof e&&this._mixin(e),!$p.utils.is_empty_guid(this.ref)&&e.number_doc&&this._set_loaded(this.ref),e=null}function doc_props_date_number(e){e.__define({number_doc:{get:function(){return this._obj.number_doc||""},set:function(e){this.__notify("number_doc"),this._obj.number_doc=e},enumerable:!0},date:{get:function(){return this._obj.date||$p.utils.blank.date},set:function(e){this.__notify("date"),this._obj.date=$p.utils.fix_date(e,!0)},enumerable:!0}})}function DataProcessorObj(e,t){DataProcessorObj.superclass.constructor.call(this,e,t);var n,a=t.metadata();for(n in a.fields)e[n]=$p.utils.fetch_type("",a.fields[n].type);for(n in a.tabular_sections)e[n]=[];this._mixin(e)}function TaskObj(e,t){TaskObj.superclass.constructor.call(this,e,t)}function BusinessProcessObj(e,t){BusinessProcessObj.superclass.constructor.call(this,e,t)}function EnumObj(e,t){EnumObj.superclass.constructor.call(this,e,t),e&&"object"==typeof e&&this._mixin(e)}function RegisterRow(e,t){RegisterRow.superclass.constructor.call(this,e,t),e&&"object"==typeof e&&this._mixin(e);for(var n in t.metadata().dimensions)if(!e.hasOwnProperty(n)&&e.ref){var a=e.ref.split("¶");Object.keys(t.metadata().dimensions).forEach(function(e,t){this[e]=a[t]}.bind(this));break}}function TabularSection(e,t){t._obj[e]||(t._obj[e]=[]),this.__define("_name",{value:e,enumerable:!1}),this.__define("_owner",{value:t,enumerable:!1}),this.__define("_obj",{value:t._obj[e],writable:!1,enumerable:!1})}function TabularSectionRow(e){var t={};this.__define("_owner",{value:e,enumerable:!1}),this.__define("_obj",{value:t,writable:!1,enumerable:!1})}function Rest(){this.filter_date=function(e,t,n){t||(t=new Date("2015-01-01"));var a=e+" gt datetime'"+$p.moment(t).format($p.moment._masks.iso)+"'";return n&&(a+=" and "+e+" lt datetime'"+$p.moment(n).format($p.moment._masks.iso)+"'"),a},this.to_data=function(e,t){var n,a,i,s,o,r,l={},c=t.metadata(),p=c.fields,d=c.tabular_sections;t instanceof RefDataManager?(e.hasOwnProperty("DeletionMark")&&(l._deleted=e.DeletionMark),e.hasOwnProperty("DataVersion"),e.hasOwnProperty("Ref_Key")&&(l.ref=e.Ref_Key)):p={}._mixin(c.dimensions)._mixin(c.resources)._mixin(c.attributes),t instanceof DocManager?(e.hasOwnProperty("Number")?l.number_doc=e.Number||e.number_doc:e.hasOwnProperty("number_doc")&&(l.number_doc=e.number_doc),e.hasOwnProperty("Date")?l.date=e.Date:e.hasOwnProperty("date")&&(l.date=e.date),e.hasOwnProperty("Posted")?l.posted=e.Posted:e.hasOwnProperty("posted")&&(l.posted=e.posted)):(c.main_presentation_name&&(e.hasOwnProperty("Description")?l.name=e.Description:e.hasOwnProperty("name")&&(l.name=e.name)),c.code_length&&(e.hasOwnProperty("Code")?l.id=e.Code:e.hasOwnProperty("id")&&(l.id=e.id)));for(a in p)if(e.hasOwnProperty(a))l[a]=e[a];else{if(o=_md.syns_1с(a),o.indexOf("_Key")==-1&&p[a].type.is_ref&&e[o+"_Key"]&&(o+="_Key"),!e.hasOwnProperty(o))continue;l[a]=e[o]}for(n in d)r="extra_fields"==n||e.hasOwnProperty(n)?n:_md.syns_1с(n),e.hasOwnProperty(r)&&(l[n]=[],e[r]&&(e[r].sort(function(e,t){return(e.LineNumber||e.row)>(t.LineNumber||t.row)}),e[r].forEach(function(e){s={};for(i in d[n].fields)o=e.hasOwnProperty(i)||"extra_fields"==n&&("property"==i||"value"==i)?i:_md.syns_1с(i),o.indexOf("_Key")==-1&&d[n].fields[i].type.is_ref&&e[o+"_Key"]&&(o+="_Key"),s[i]=e[o];l[n].push(s)})));return l},this.ajax_to_data=function(e,t){return $p.ajax.get_ex(e.url,e).then(function(e){return JSON.parse(e.response)}).then(function(e){var n=[];return e.value.forEach(function(e){n.push(_rest.to_data(e,t))}),n})},this.build_select=function(e,t){function n(e,a){"function"==typeof a?s+=a(t,e):(o=_md.syns_1с(e),r=_md.get(t.class_name,e),r&&(r=r.type,r.is_ref&&o.indexOf("_Key")==-1&&r.types.length&&r.types[0].indexOf("enm.")==-1&&(o+="_Key"),r.types.length&&(["boolean","number"].indexOf(typeof a)!=-1?s+=o+" eq "+a:r.is_ref&&"object"!=typeof a||a instanceof DataObj?s+=o+" eq guid'"+a+"'":"string"==typeof a?s+=o+" eq '"+a+"'":"object"==typeof a&&(a.hasOwnProperty("like")?s+=o+" like '%"+a.like+"%'":a.hasOwnProperty("not")?s+=" not ("+n(e,a.not)+") ":a.hasOwnProperty("in")&&(s+=o+" in ("+(r.is_ref?a.in.map(function(e){return"guid'"+e+"'"}).join(","):a.in.join(","))+") ")))))}function a(e){for(var t in e)if(s?s+=" and ":s="&$filter=","or"==t&&Array.isArray(e[t])){var a=!0;e[t].forEach(function(e){a?(s+=" ( ",a=!1):s+=" or ";var t=Object.keys(e)[0];n(t,e[t])}),s+=" ) "}else n(t,e[t])}var i,s,o,r,l="";e||(e={}),e.fields&&(e.fields.forEach(function(e){"ref"==e?o="Ref_Key":(o=_md.syns_1с(e),r=_md.get(t.class_name,e).type,r.is_ref&&o.indexOf("_Key")==-1&&r.types.length&&r.types[0].indexOf("enm.")==-1&&(o+="_Key")),i?i+=",":i="&$select=",i+=o}),l+=i),e.selection&&("function"==typeof e.selection||(Array.isArray(e.selection)?e.selection.forEach(a):a(e.selection)),s&&(l+=s)),$p.job_prm.rest&&t.rest_name.indexOf("Module_")==-1&&t.rest_name.indexOf("DataProcessor_")==-1&&t.rest_name.indexOf("Report_")==-1&&l.indexOf(" like ")==-1&&l.indexOf(" in ")==-1&&!t.metadata().irest?$p.ajax.default_attr(e,$p.job_prm.rest_url()):$p.ajax.default_attr(e,$p.job_prm.irest_url()),e.url+=t.rest_name+"?allowedOnly=true&$format=json&$top="+(e.top||300)+l},this.load_array=function(e,t){return _rest.build_select(e,t),_rest.ajax_to_data(e,t)},this.load_obj=function(e){var t={};return $p.ajax.default_attr(t,!e._metadata.irest&&$p.job_prm.rest?$p.job_prm.rest_url():$p.job_prm.irest_url()),t.url+=e._manager.rest_name+"(guid'"+e.ref+"')?$format=json",$p.ajax.get_ex(t.url,t).then(function(e){return JSON.parse(e.response)}).then(function(t){return e._mixin(_rest.to_data(t,e._manager))._set_loaded(),e}).catch(function(t){return 404==t.status?e:void $p.record_log(t)})},this.save_irest=function(e,t){var n=JSON.stringify(e),a=(void 0!=t.post?",post="+t.post:"")+(void 0!=t.operational?",operational="+t.operational:"");return $p.ajax.default_attr(t,$p.job_prm.irest_url()),t.url+=e._manager.rest_name+"(guid'"+e.ref+"'"+a+")",$p.ajax.post_ex(t.url,n,t).then(function(e){return JSON.parse(e.response)}).then(function(t){return e._mixin(t)})},this.save_rest=function(e,t){var n,a=e.to_atom();return $p.ajax.default_attr(t,$p.job_prm.rest_url()),n=t.url+e._manager.rest_name,t.url=n+"(guid'"+e.ref+"')?$format=json&$select=Ref_Key,DeletionMark",$p.ajax.get_ex(t.url,t).catch(function(e){return 404==e.status?{response:JSON.stringify({is_new:!0})}:Promise.reject(e)}).then(function(e){return JSON.parse(e.response)}).then(function(i){return i.is_new?$p.ajax.post_ex(n,a,t):$p.ajax.patch_ex(n+"(guid'"+e.ref+"')",a,t)}).then(function(t){var n=xmlToJSON.parseString(t.response,{mergeCDATA:!1,grokAttr:!0,grokText:!1,normalize:!0,xmlns:!1,namespaceKey:"_ns",textKey:"_text",valueKey:"_value",attrKey:"_attr",cdataKey:"_cdata",attrsAsObject:!1,stripAttrPrefix:!0,stripElemPrefix:!0,childrenAsArray:!1});if(n.entry&&n.entry.content&&n.entry.updated){var a,i=n.entry.content.properties,s={};for(var o in i)if(0!=o.indexOf("_"))if(a=i[o].element)if(s[o]=[],Array.isArray(a))for(var r in a){s[o][r]={};for(var l in a[r])0!=l.indexOf("_")&&(s[o][r][l]="false"!==a[r][l]._text&&a[r][l]._text)}else{s[o][0]={};for(var l in a)0!=l.indexOf("_")&&(s[o][0][l]="false"!==a[l]._text&&a[l]._text)}else s[o]="false"!==i[o]._text&&i[o]._text;return _rest.to_data(s,e._manager)}}).then(function(t){return e._mixin(t)})}}function eXcell_ocombo(e){if(e){var t=this;t.cell=e,t.grid=e.parentNode.grid,t.setValue=function(e){t.setCValue(e instanceof DataObj?e.presentation:e||"")},t.getValue=function(){return t.grid.get_cell_value()},t.shiftNext=function(){t.grid.editStop()},t.edit=function(){t.combo||(t.val=t.getValue(),t.cell.innerHTML="",t.combo=new OCombo({parent:t.cell}._mixin(t.grid.get_cell_field())),t.combo.getInput().focus())},t.detach=function(){if(t.combo){if(t.combo.getComboText){t.setValue(t.combo.getComboText()),t.combo.getSelectedValue()||t.combo.callEvent("onChange");var e=!$p.utils.is_equal(t.val,t.getValue());return t.combo.unload(),e}t.combo.unload&&t.combo.unload()}return!0}}}function eXcell_pwd(e){var t;e&&(this.cell=e,this.grid=e.parentNode.grid,eXcell_ed.call(this),t=this.edit,this.edit=function(){t.call(this),this.obj.type="password"},this.setValue=function(){this.setCValue("*********")},this.getValue=function(){return this.grid.get_cell_value()},this.detach=function(){if(this.grid.get_cell_field){var e=this.grid.get_cell_field();e.obj[e.field]=this.obj.value}return this.setValue(),t=null,this.val!=this.getValue()})}function ODropdownList(e){function t(t){s.innerHTML=e.values[s.getAttribute("current")],e.event_name&&!t&&dhx4.callEvent(e.event_name,[s.getAttribute("current")])}function n(){i.classList.remove("open")}var a,i,s,o=document.createElement("ul");e.container.innerHTML='<div class="dropdown_list">'+e.title+'<a href="#" class="dropdown_list"></a></div>',i=e.container.firstChild,s=i.querySelector("a"),s.setAttribute("current",Array.isArray(e.values)?"0":Object.keys(e.values)[0]),i.onclick=function(e){if(i.classList.contains("open")){if("LI"==e.target.tagName)for(var a in o.childNodes)if(o.childNodes[a]==e.target){s.setAttribute("current",e.target.getAttribute("current")),t();break}n()}else i.classList.add("open");return $p.iface.cancel_bubble(e)},i.appendChild(o),o.className="dropdown_menu",e.class_name&&(i.classList.add(e.class_name),o.classList.add(e.class_name));for(var r in e.values){a=document.createElement("li");var l=e.values[r].indexOf("<i");a.innerHTML=e.values[r].substr(l)+" "+e.values[r].substr(0,l),a.setAttribute("current",r),o.appendChild(a)}document.body.addEventListener("keydown",function(e){27==e.keyCode&&i.classList.remove("open")}),document.body.addEventListener("click",n),this.unload=function(){for(var t;t=i.lastChild;)i.removeChild(t);e.container.removeChild(i),a=o=i=s=e=null},t(!0)}function OCombo(e){function t(e){var t={_top:30};return m&&m.metadata().hierarchical&&m.metadata().group_hierarchy&&("elm"==u.choice_groups_elm?t.is_folder=!1:"grp"!=u.choice_groups_elm&&"parent"!=d||(t.is_folder=!0)),u.choice_links&&u.choice_links.forEach(function(e){e.name&&"selection"==e.name[0]&&(p instanceof TabularSectionRow?e.path.length<2?t[e.name[1]]="function"==typeof e.path[0]?e.path[0]:p._owner._owner[e.path[0]]:t[e.name[1]]=p[e.path[1]]:t[e.name[1]]="function"==typeof e.path[0]?e.path[0]:p[e.path[0]])}),u.choice_params&&u.choice_params.forEach(function(e){var n=Array.isArray(e.path)?{in:e.path}:e.path;t[e.name]?Array.isArray(t[e.name])?t[e.name].push(n):(t[e.name]=[t[e.name]],t[e.name].push(n)):t[e.name]=n}),u._option_list_local&&(t._local=!0),e&&(t.presentation={like:e}),t}function n(a){if("select"==this.name)m?m.form_selection(g,{initial_value:p[d].ref,selection:[t()]}):n.call({name:"type"});else if("add"==this.name)m&&m.create({},!0).then(function(t){t._set_loaded(t.ref),t.form_obj(e.pwnd)});else if("open"==this.name)p&&p[d]&&!p[d].empty()&&p[d].form_obj(e.pwnd);else if("type"==this.name){var i,s,o=[],r=p,l=d;u.type.types.forEach(function(e){i=_md.mgr_by_class_name(e),s=i.metadata(),o.push({presentation:s.synonym||s.name,mgr:i,selected:m===i})}),$p.iface.select_from_list(o).then(function(e){r[l]&&(r[l].empty&&r[l].empty()||r[l]._manager!=e.mgr)&&(m=e.mgr,p=r,d=l,u=p._metadata.fields[d],m.form_selection({on_select:function(e){p[d]=e,p=null,d=null,u=null}},{selection:[t()]})),m=null,i=null,s=null,r=null,l=null})}if(a)return $p.iface.cancel_bubble(a)}function a(){h=!1,setTimeout(function(){h||($p.iface.popup.p&&$p.iface.popup.p.onmouseover&&($p.iface.popup.p.onmouseover=null),$p.iface.popup.p&&$p.iface.popup.p.onmouseout&&($p.iface.popup.p.onmouseout=null),$p.iface.popup.clear(),$p.iface.popup.hide())},300)}function i(){if(!(m instanceof EnumManager)){h=!0;var t=document.createElement("div"),i=e.hide_frm?"":"<a href='#' name='select' title='Форма выбора {F4}'>Показать все</a><a href='#' name='open' style='margin-left: 9px;' title='Открыть форму элемента {Ctrl+Shift+F4}'><i class='fa fa-external-link fa-fw'></i></a>";if(!e.hide_frm){var s=$p.current_acl.get_acl(m.class_name);s.indexOf("i")!=-1&&(i+=" <a href='#' name='add' title='Создать новый элемент {F8}'><i class='fa fa-plus fa-fwfa-fw'></i></a>")}if(u.type.types.length>1&&(i+=" <a href='#' name='type' title='Выбрать тип значения {Alt+T}'><i class='fa fa-level-up fa-fw'></i></a>"),i){t.innerHTML=i;for(var o=0;o<t.children.length;o++)t.children[o].onclick=n;$p.iface.popup.clear(),$p.iface.popup.attachObject(t),$p.iface.popup.show(dhx4.absLeft(_.getButton())-77,dhx4.absTop(_.getButton()),_.getButton().offsetWidth,_.getButton().offsetHeight),$p.iface.popup.p.onmouseover=function(){h=!0},$p.iface.popup.p.onmouseout=a}}}function s(e){return setTimeout(i,10),e.preventDefault(),!1}function o(n){if(!(m instanceof EnumManager))return 115==n.keyCode?(n.ctrlKey&&n.shiftKey?p[d].empty()||p[d].form_obj(e.pwnd):n.ctrlKey||n.shiftKey||m&&m.form_selection(g,{initial_value:p[d].ref,selection:[t()]}),$p.iface.cancel_bubble(n)):void 0}function r(e){setTimeout(function(){_&&_.getInput&&_.getInput().select()},50)}function l(e){_&&_.getBase&&(_.getBase().parentElement?p instanceof TabularSectionRow||e.forEach(function(e){e.name==d&&c(p[d])}):setTimeout(_.unload))}function c(e){if(e&&e instanceof DataObj&&!e.empty()){if(_.getOption(e.ref)||_.addOption(e.ref,e.presentation),_.getSelectedValue()==e.ref)return;_.setComboValue(e.ref)}else _.getSelectedValue()||(_.setComboValue(""),_.setComboText(""))}var p,d,u,m,f,h,_=this,g={on_select:e.on_select||function(e){p[d]=e}};e.pwnd&&e.pwnd.setModal&&(g.setModal=e.pwnd.setModal.bind(e.pwnd)),OCombo.superclass.constructor.call(_,e),e.on_select?(_.getBase().style.border="none",_.getInput().style.left="-3px",e.is_tabular||(_.getButton().style.right="9px")):_.getBase().style.marginBottom="4px",e.left&&(_.getBase().style.left=left+"px"),this.attachEvent("onChange",function(){p&&d&&(p[d]=this.getSelectedValue())}),this.attachEvent("onBlur",function(){!this.getSelectedValue()&&this.getComboText()&&this.setComboText("")}),this.attachEvent("onDynXLS",function(n){m||(m=_md.value_mgr(p,d,u.type)),m&&(_.clearAll(),(e.get_option_list||m.get_option_list).call(m,null,t(n)).then(function(e){_.addOption&&(_.addOption(e),_.openSelect())}))}),_.getButton().addEventListener("mouseover",i),_.getButton().addEventListener("mouseout",a),_.getBase().addEventListener("click",$p.iface.cancel_bubble),_.getBase().addEventListener("contextmenu",s),_.getInput().addEventListener("keyup",o),_.getInput().addEventListener("focus",r),this.attach=function(e){p&&(p instanceof TabularSectionRow?Object.unobserve(p._owner._owner,l):Object.unobserve(p,l)),p=e.obj,d=e.field,f=e.property,e.metadata?u=e.metadata:f?(u=p._metadata.fields[d]._clone(),u.type=f.type):u=p._metadata.fields[d],_.clearAll(),m=_md.value_mgr(p,d,u.type),(m||e.get_option_list)&&(e.get_option_list||m.get_option_list).call(m,p[d],t()).then(function(e){_.addOption&&(_.addOption(e),c(p[d]))}),p instanceof TabularSectionRow?Object.observe(p._owner._owner,l,["row"]):Object.observe(p,l,["update"])};var b=this.unload;this.unload=function(){a(),_.getButton().removeEventListener("mouseover",i),_.getButton().removeEventListener("mouseout",a),_.getBase().removeEventListener("click",$p.iface.cancel_bubble),_.getBase().removeEventListener("contextmenu",s),_.getInput().removeEventListener("keyup",o), +_.getInput().removeEventListener("focus",r),p&&(p instanceof TabularSectionRow?Object.unobserve(p._owner._owner,l):Object.unobserve(p,l)),_.conf&&_.conf.tm_confirm_blur&&clearTimeout(_.conf.tm_confirm_blur),p=null,d=null,u=null,m=null,g=null;try{b.call(_)}catch(e){}},e.obj&&e.field&&this.attach(e),this.enableFilteringMode("between","dummy",!1,!1),this.__define({value:{get:function(){if(p)return p[d]}}})}function ODateRangePicker(e,t){var n=this._cont=document.createElement("div");e instanceof dhtmlXCellObject?e.appendObject(this._cont):e.appendChild(this._cont),this._cont.className="odaterangepicker",this._cont.innerHTML='<i class="fa fa-calendar"></i>  <span></span>  <i class="fa fa-caret-down"></i>',this.__define({set_text:{value:function(){$("span",n).html(this.date_from.format("DD MMM YY")+" - "+this.date_till.format("DD MMM YY"))}},on:{value:function(e,t){return $(n).on(e,t)}},date_from:{get:function(){return $(n).data("daterangepicker").startDate},set:function(e){$(n).data("daterangepicker").setStartDate(e),this.set_text()}},date_till:{get:function(){return $(n).data("daterangepicker").endDate},set:function(e){$(n).data("daterangepicker").setEndDate(e),this.set_text()}}}),$(n).daterangepicker({startDate:t.date_from?moment(t.date_from):moment().subtract(29,"days"),endDate:moment(t.date_till),showDropdowns:!0,alwaysShowCalendars:!0,opens:"left",ranges:{"Сегодня":[moment(),moment()],"Вчера":[moment().subtract(1,"days"),moment().subtract(1,"days")],"Последние 7 дней":[moment().subtract(6,"days"),moment()],"Последние 30 дней":[moment().subtract(29,"days"),moment()],"Этот месяц":[moment().startOf("month"),moment().endOf("month")],"Прошлый месяц":[moment().subtract(1,"month").startOf("month"),moment().subtract(1,"month").endOf("month")]}},this.set_text.bind(this)),this.set_text()}function _clear_all(){$p.iface.docs.__define({clear_all:{value:function(){this.detachToolbar(),this.detachStatusBar(),this.detachObject(!0)},enumerable:!1},"Очистить":{get:function(){return this.clear_all},enumerable:!1},"Контейнер":{get:function(){return this.cell.querySelector(".dhx_cell_cont_layout")},enumerable:!1}})}function OTooolBar(e){function t(e){for(var t=0;t<c.children.length;t++)c.children[t].classList.remove("selected");e&&!this.classList.contains("selected")&&this.classList.add("selected")}function n(){s=!1,setTimeout(function(){s||$p.iface.popup.hide()},300)}function a(){e.onclick&&e.onclick.call(l,this.name.replace(e.name+"_",""),e.name)}var i,s,o,r,l=this,c=document.createElement("div");e.image_path||(e.image_path=dhtmlx.image_path),e.hasOwnProperty("class_name")?c.className=e.class_name:c.className="md_otooolbar",l.cell=c,l.buttons={},this.add=function(t){function p(e){if(e||(e=d),e.subdiv&&!o&&!r){for(;e.subdiv.firstChild;)e.subdiv.removeChild(e.subdiv.firstChild);e.subdiv.parentNode.removeChild(e.subdiv),e.subdiv=null}}var d=$p.iface.add_button(c,e,t);d.onclick=a,d.onmouseover=function(){t.title&&!t.sub&&(s=!0,$p.iface.popup.clear(),$p.iface.popup.attachHTML(t.title),$p.iface.popup.show(dhx4.absLeft(d),dhx4.absTop(d),d.offsetWidth,d.offsetHeight),$p.iface.popup.p.onmouseover=function(){s=!0},$p.iface.popup.p.onmouseout=n,e.on_popup&&e.on_popup($p.iface.popup,d))},d.onmouseout=n,l.buttons[t.name]=d,t.sub&&(d.onmouseover=function(){for(var n=0;n<d.parentNode.children.length;n++)if(d.parentNode.children[n]!=d&&d.parentNode.children[n].subdiv){p(d.parentNode.children[n]);break}if(r=!0,!this.subdiv){this.subdiv=document.createElement("div"),this.subdiv.className="md_otooolbar",i=$p.iface.get_offset(d),"right"==t.sub.align?this.subdiv.style.left=i.left+d.offsetWidth-(parseInt(t.sub.width.replace(/\D+/g,""))||56)+"px":this.subdiv.style.left=i.left+"px",this.subdiv.style.top=i.top+c.offsetHeight+"px",this.subdiv.style.height=t.sub.height||"198px",this.subdiv.style.width=t.sub.width||"56px";for(var n in t.sub.buttons){var s=$p.iface.add_button(this.subdiv,e,t.sub.buttons[n]);s.onclick=a}e.wrapper.appendChild(this.subdiv),this.subdiv.onmouseover=function(){o=!0},this.subdiv.onmouseout=function(){o=!1,setTimeout(p,500)},t.title&&$p.iface.popup.show(dhx4.absLeft(this.subdiv),dhx4.absTop(this.subdiv),this.subdiv.offsetWidth,this.subdiv.offsetHeight)}},d.onmouseout=function(){r=!1,setTimeout(p,500)})},this.select=function(n){for(var a=0;a<c.children.length;a++){var i=c.children[a];if(i.name==e.name+"_"+n)return void t.call(i,!0)}},this.get_selected=function(){for(var e=0;e<c.children.length;e++){var t=c.children[e];if(t.classList.contains("selected"))return t.name}},this.unload=function(){for(;c.firstChild;)c.removeChild(c.firstChild);e.wrapper.removeChild(c)},e.wrapper.appendChild(c),c.style.width=e.width||"28px",c.style.height=e.height||"150px",c.style.position="absolute",e.top&&(c.style.top=e.top),e.left&&(c.style.left=e.left),e.bottom&&(c.style.bottom=e.bottom),e.right&&(c.style.right=e.right),e.paddingRight&&(c.style.paddingRight=e.paddingRight),e.paddingLeft&&(c.style.paddingLeft=e.paddingLeft),e.buttons&&e.buttons.forEach(function(e){l.add(e)})}function eXcell_addr(e){if(e){var t,n=this,a=function(e){return eXcell_proto.input_keydown(e,n)},i=function(e){var t={grid:n.grid}._mixin(n.grid.get_cell_field());return wnd_address(t),$p.iface.cancel_bubble(e)};n.cell=e,n.grid=n.cell.parentNode.grid,n.open_selection=i,n.setValue=function(e){n.setCValue(e)},n.getValue=function(){return n.grid.get_cell_value()},n.edit=function(){var e;n.val=n.getValue(),n.cell.innerHTML='<div class="ref_div21"><input type="text" class="dhx_combo_edit" style="height: 20px;"><div class="ref_field21"> </div></div>',t=n.cell.firstChild,e=t.childNodes[0],e.value=n.val,e.onclick=$p.iface.cancel_bubble,e.readOnly=!0,e.focus(),e.onkeydown=a,t.childNodes[1].onclick=i},n.detach=function(){return n.setValue(n.getValue()),!$p.utils.is_equal(n.val,n.getValue())}}}function wnd_address(e){function t(){var e={name:"wnd_addr",wnd:{id:"wnd_addr",top:130,left:200,width:800,height:560,modal:!0,center:!0,pwnd:g,allow_close:!0,allow_minmax:!0,on_close:f,caption:_.shipping_address}};g&&g.getHeight&&e.wnd.height>g.getHeight()&&(e.wnd.height=g.getHeight()),h=$p.iface.dat_blank(null,e.wnd),h.elmnts.layout=h.attachLayout("2E"),h.elmnts.cell_frm=h.elmnts.layout.cells("a"),h.elmnts.cell_frm.setHeight("110"),h.elmnts.cell_frm.hideHeader(),h.elmnts.cell_frm.fixSize(0,1),h.elmnts.pgrid=h.elmnts.cell_frm.attachPropertyGrid(),h.elmnts.pgrid.setDateFormat("%d.%m.%Y %H:%i"),h.elmnts.pgrid.init(),h.elmnts.pgrid.parse(_._manager.get_property_grid_xml({" ":[{id:"delivery_area",path:"o.delivery_area",synonym:"Район доставки",type:"ref",txt:v.delivery_area.presentation},{id:"region",path:"o.region",synonym:"Регион",type:"ro",txt:v.region},{id:"city",path:"o.city",synonym:"Населенный пункт",type:"ed",txt:v.city},{id:"street",path:"o.street",synonym:"Улица, дом, корпус, литера, квартира",type:"ed",txt:v.street}]},v),function(){h.elmnts.pgrid.enableAutoHeight(!0),h.elmnts.pgrid.setInitWidthsP("40,60"),h.elmnts.pgrid.setSizes(),h.elmnts.pgrid.attachEvent("onPropertyChanged",m)},"xml"),h.elmnts.pgrid.get_cell_field=function(){return{obj:v,field:"delivery_area",on_select:a,pwnd:h,metadata:{synonym:"Район",tooltip:"Район (зона, направление) доставки для группировки при планировании и оптимизации маршрута геокодером",choice_groups_elm:"elm",type:{types:["cat.delivery_areas"],is_ref:!0}}}},h.elmnts.toolbar=h.attachToolbar({icons_path:dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()}),h.elmnts.toolbar.loadStruct('<toolbar><item id="btn_select" type="button" title="Установить адрес" text="<b>Выбрать</b>" /></toolbar>',function(){this.attachEvent("onclick",n)}),h.elmnts.cell_map=h.elmnts.layout.cells("b"),h.elmnts.cell_map.hideHeader();var t={center:new google.maps.LatLng(v.latitude,v.longitude),zoom:v.street?15:12,mapTypeId:google.maps.MapTypeId.ROADMAP};h.elmnts.map=h.elmnts.cell_map.attachMap(t),v.marker=new google.maps.Marker({map:h.elmnts.map,draggable:!0,animation:google.maps.Animation.DROP,position:t.center}),google.maps.event.addListener(v.marker,"click",d),google.maps.event.addListener(v.marker,"dragend",u),s()}function n(e){"btn_select"==e&&(_.delivery_area=v.delivery_area,l(),_.coordinates=JSON.stringify([v.latitude,v.longitude])),h.close()}function a(e){if(void 0!==e){var t,n=b;b=$p.utils.is_data_obj(e)?e:$p.cat.delivery_areas.get(e,!1),t=n!=b,$p.utils.is_data_obj(b)||(b=$p.cat.delivery_areas.get()),h.elmnts.pgrid.cells().setValue(e.presentation),i(t)}}function i(e){if(!v.delivery_area.empty()&&e&&(v.street=""),v.delivery_area.region?(v.region=v.delivery_area.region,h.elmnts.pgrid.cells("region",1).setValue(v.region)):e&&(v.region=""),v.delivery_area.city?(v.city=v.delivery_area.city,h.elmnts.pgrid.cells("city",1).setValue(v.city)):e&&(v.city=""),v.delivery_area.latitude&&v.delivery_area.longitude){var t=new google.maps.LatLng(v.delivery_area.latitude,v.delivery_area.longitude);h.elmnts.map.setCenter(t),v.marker.setPosition(t)}s()}function s(){h.elmnts.pgrid.cells("region",1).setValue(v.region),h.elmnts.pgrid.cells("city",1).setValue(v.city),h.elmnts.pgrid.cells("street",1).setValue(v.street)}function o(){var e=v.street?15:12;h.elmnts.map.getZoom()!=e&&h.elmnts.map.setZoom(e),p(function(e,t){if(t==google.maps.GeocoderStatus.OK){var n=e[0].geometry.location;h.elmnts.map.setCenter(n),v.marker.setPosition(n),v.latitude=n.lat(),v.longitude=n.lng(),v.postal_code=$p.ipinfo.components({},e[0].address_components).postal_code||""}})}function r(){return(v.street?v.street.replace(/,/g," ")+", ":"")+(v.city?v.city+", ":"")+(v.region?v.region+", ":"")+v.country+(v.postal_code?", "+v.postal_code:"")}function l(){_.shipping_address=r();var e='<КонтактнаяИнформация \t\t\t\txmlns="http://www.v8.1c.ru/ssl/contactinfo" \t\t\t\txmlns:xs="http://www.w3.org/2001/XMLSchema" \t\t\t\txmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" \t\t\t\tПредставление="%1"> \t\t\t\t\t<Комментарий/> \t\t\t\t\t<Состав xsi:type="Адрес" Страна="РОССИЯ"> \t\t\t\t\t\t<Состав xsi:type="АдресРФ">'.replace("%1",_.shipping_address);if(v.region&&(e+="\n<СубъектРФ>"+v.region+"</СубъектРФ>"),v.city&&(e+=v.city.indexOf("г.")!=-1||v.city.indexOf("г ")!=-1||v.city.indexOf(" г")!=-1?"\n<Город>"+v.city+"</Город>":"\n<НаселПункт>"+v.city+"</НаселПункт>"),v.street){var t,n,a,i,s,o=v.street.replace(/,/g," ");for(var l in $p.fias){if(1==$p.fias[l].type)for(var c in $p.fias[l].syn)if((n=o.indexOf($p.fias[l].syn[c]))!=-1){i=l,t=o.substr(n+$p.fias[l].syn[c].length).trim(),o=o.substr(0,n).trim();break}if(i)break}if(i||(i="1010",(n=o.indexOf(" "))!=-1&&(t=o.substr(n),o=o.substr(0,n))),e+="\n<Улица>"+o.trim()+"</Улица>",t){a=t.toLowerCase(),t="";for(var l in $p.fias){if(3==$p.fias[l].type)for(var c in $p.fias[l].syn)if((n=a.indexOf($p.fias[l].syn[c]))!=-1){s=l,t=a.substr(n+$p.fias[l].syn[c].length),a=a.substr(0,n);break}if(s)break}s||(s="2010",(n=a.indexOf(" "))!=-1&&(t=a.substr(n),a=a.substr(0,n))),e+='\n<ДопАдрЭл><Номер Тип="'+i+'" Значение="'+a.trim()+'"/></ДопАдрЭл>'}t&&(e+='\n<ДопАдрЭл><Номер Тип="'+s+'" Значение="'+t.trim()+'"/></ДопАдрЭл>')}v.postal_code&&(e+='<ДопАдрЭл ТипАдрЭл="10100000" Значение="'+v.postal_code+'"/>'),e+="</Состав> \t\t\t\t\t</Состав></КонтактнаяИнформация>",_.address_fields=e}function c(){function e(e){if(e.attributes&&2==e.attributes.length){var t={};return t[e.attributes[0].value]=e.attributes[1].value,t}}if(_.address_fields){v.xml=(new DOMParser).parseFromString(_.address_fields,"text/xml");var t,n={},a={building_room:""},i=[],s="СубъектРФ,Округ,СвРайМО,СвРайМО,ВнутригРайон,НаселПункт,Улица,Город,ДопАдрЭл,Адрес_по_документу,Местоположение".split(",");for(var o in s)n[s[o]]=v.xml.getElementsByTagName(s[o]);for(var o in n)for(var r in n[o])if("length"!=r&&n[o].hasOwnProperty(r))if(t=e(n[o][r]))a[o]||(a[o]=[]),a[o].push(t);else if(n[o][r].childNodes.length)for(var l in n[o][r].childNodes)"length"!=l&&n[o][r].childNodes.hasOwnProperty(l)&&((t=e(n[o][r].childNodes[l]))?(a[o]||(a[o]=[]),a[o].push(t)):n[o][r].childNodes[l].nodeValue&&(a[o]?a[o]+=" "+n[o][r].childNodes[l].nodeValue:a[o]=n[o][r].childNodes[l].nodeValue));for(var o in a["ДопАдрЭл"]){for(var r in $p.fias)4==r.length&&a["ДопАдрЭл"][o][r]&&(i[$p.fias[r].type]=$p.fias[r].name+" "+a["ДопАдрЭл"][o][r]);a["ДопАдрЭл"][o][101e5]&&(v.postal_code=a["ДопАдрЭл"][o][101e5])}v.address_fields=a,v.region=a["СубъектРФ"]||a["Округ"]||"",v.city=a["Город"]||a["НаселПункт"]||"",v.street=a["Улица"]||"";for(var o in i)v.street+=" "+i[o]}return new Promise(function(e,t){if($p.ipinfo||($p.ipinfo=new IPInfo),window.google&&window.google.maps)e();else{$p.load_script("//maps.google.com/maps/api/js?callback=$p.ipinfo.location_callback","script",function(){});var n=$p.eve.attachEvent("geo_google_ready",function(){a&&clearTimeout(a),n&&($p.eve.detachEvent(n),n=null,e())}),a=setTimeout(function(){n&&($p.eve.detachEvent(n),n=null),$p.msg.show_msg({type:"alert-warning",text:$p.msg.error_geocoding+" Google",title:$p.msg.main_title}),e()},1e4)}}).then(function(){v.coordinates.length?(v.latitude=v.coordinates[0],v.longitude=v.coordinates[1]):_.shipping_address?p(function(e,t){t==google.maps.GeocoderStatus.OK&&(v.latitude=e[0].geometry.location.lat(),v.longitude=e[0].geometry.location.lng())}):$p.ipinfo.latitude&&$p.ipinfo.longitude?(v.latitude=$p.ipinfo.latitude,v.longitude=$p.ipinfo.longitude):(v.latitude=55.635924,v.longitude=37.6066379,$p.msg.show_msg($p.msg.empty_geocoding))})}function p(e){var t=r();$p.ipinfo.ggeocoder.geocode({address:t},e)}function d(){null!=v.marker.getAnimation()?v.marker.setAnimation(null):(v.marker.setAnimation(google.maps.Animation.BOUNCE),setTimeout(function(){v.marker.setAnimation(null)},1500))}function u(e){$p.ipinfo.ggeocoder.geocode({latLng:e.latLng},function(t,n){if(n==google.maps.GeocoderStatus.OK&&t[0]){var a=t[0];h.setText(a.formatted_address),$p.ipinfo.components(v,a.address_components),s();var i=v.street?15:12;h.elmnts.map.getZoom()!=i&&(h.elmnts.map.setZoom(i),h.elmnts.map.setCenter(e.latLng)),v.latitude=e.latLng.lat(),v.longitude=e.latLng.lng()}})}function m(e,t,n){e&&(v.delivery_area.empty()?(t=n,$p.msg.show_msg({type:"alert",text:$p.msg.delivery_area_empty,title:$p.msg.addr_title}),setTimeout(function(){h.elmnts.pgrid.selectRowById("delivery_area")},50)):"delivery_area"==e?a(t):(v[h.elmnts.pgrid.getSelectedRowId()]=t,o()))}function f(t){return e.grid.editStop(),!t.error}var h,_=e.obj,g=e.pwnd,b=_.delivery_area,v={coordinates:_.coordinates?JSON.parse(_.coordinates):[],country:"Россия",region:"",city:"",street:"",postal_code:"",marker:{}};return v.__define("delivery_area",{get:function(){return b},set:function(e){a(e)}}),c().then(t),h}function AppEvents(){if(this.__define({init:{value:function(){$p.__define("job_prm",{value:new JobPrm,writable:!1}),$p.wsql.init_params()}},do_eventable:{value:function(e){function t(e,t){e=String(e).toLowerCase(),this._evnts.data[e]||(this._evnts.data[e]={});var n=$p.utils.generate_guid();return this._evnts.data[e][n]=t,n}function n(e){if(!e)return a.call(this);for(var t in this._evnts.data){var n=0;for(var i in this._evnts.data[t])i==e?(this._evnts.data[t][i]=null,delete this._evnts.data[t][i]):n++;0==n&&(this._evnts.data[t]=null,delete this._evnts.data[t])}}function a(){for(var e in this._evnts.data){for(var t in this._evnts.data[e])this._evnts.data[e][t]=null,delete this._evnts.data[e][t];this._evnts.data[e]=null,delete this._evnts.data[e]}}function i(e,t){if(e=String(e).toLowerCase(),null==this._evnts.data[e])return!0;var n=!0;for(var a in this._evnts.data[e])n=this._evnts.data[e][a].apply(this,t)&&n;return n}function s(){for(var e in this._evnts.evnts){var t=this._evnts.evnts[e].length;if(t){for(var n=0;n<t;n++)this.emit(e,this._evnts.evnts[e][n]);this._evnts.evnts[e].length=0}}this._evnts.timer=0}e.__define({_evnts:{value:{data:{},timer:0,evnts:{}}},on:{value:t},attachEvent:{value:t},off:{value:n},detachEvent:{value:n},detachAllEvents:{value:a},checkEvent:{value:function(e){return e=String(e).toLowerCase(),null!=this._evnts.data[e]}},callEvent:{value:i},emit:{value:i},emit_async:{value:function(e,t){this._evnts.evnts[e]||(this._evnts.evnts[e]=[]),this._evnts.evnts[e].push(t),this._evnts.timer&&clearTimeout(this._evnts.timer),this._evnts.timer=setTimeout(s.bind(this),4)}}})}}}),"undefined"!=typeof window&&window.dhx4){for(var e in dhx4)this[e]=dhx4[e],delete dhx4[e];window.dhx4=this}else"undefined"==typeof WorkerGlobalScope&&this.do_eventable(this)}function JobPrm(){function e(){return $p.wsql.get_user_param("rest_path")||$p.job_prm.rest_path||"/a/zd/%1/odata/standard.odata/"}function t(){function e(e){var t,n={},a=[];if("#"!==e.substr(0,1)&&"?"!==e.substr(0,1)||(e=e.substr(1)),e.length>2){t=decodeURI(e).split("&");for(var i in t)if(a=t[i].split("="),"m"==a[0])try{n[a[0]]=JSON.parse(a[1])}catch(e){n[a[0]]={}}else n[a[0]]=a[1]||""}return n}return e(location.search)._mixin(e(location.hash))}this.__define({parse_url:{value:t},offline:{value:!1,writable:!0},local_storage_prefix:{value:"",writable:!0},create_tables:{value:!0,writable:!0},url_prm:{value:"undefined"!=typeof window?t():{}},rest_url:{value:function(){var t=e(),n=$p.wsql.get_user_param("zone",$p.job_prm.zone_is_string?"string":"number");return n?t.replace("%1",n):t.replace("%1/","")}},irest_url:{value:function(){var t=e(),n=$p.wsql.get_user_param("zone",$p.job_prm.zone_is_string?"string":"number");return t=t.replace("odata/standard.odata","hs/rest"),n?t.replace("%1",n):t.replace("%1/","")}}}),$p.eve.callEvent("settings",[this]);for(var n in this)"url_prm"!==n&&"function"!=typeof this[n]&&this.url_prm.hasOwnProperty[n]&&(this[n]=this.url_prm[n])}function Modifiers(){var e=[];this.push=function(t){e.push(t)},this.detache=function(t){var n=e.indexOf(t);n!=-1&&e.splice(n,1)},this.clear=function(){e.length=0},this.execute=function(t){var n,a;return e.forEach(function(e){a="function"==typeof e?e(t):$p.injected_data[e](t),n!==!1&&(n=a)}),n},this.execute_external=function(e){var t=$p.wsql.get_user_param("modifiers");return t=t?t.split("\n").map(function(e){return e?new Promise(function(t,n){$p.load_script(e,"script",t)}):Promise.resolve()}):[],Promise.all(t).then(function(){this.execute(e)}.bind(this))}}function IPInfo(){function e(){this.geocode=function(e){return Promise.resolve(!1)}}var t,n,a,i="";this.__define({ipgeo:{value:function(){return $p.ajax.get("//api.sypexgeo.net/").then(function(e){return JSON.parse(e.response)}).catch($p.record_log)}},yageocoder:{get:function(){return t||(t=new e),t},enumerable:!1,configurable:!1},ggeocoder:{get:function(){return n},enumerable:!1,configurable:!1},addr:{get:function(){return i}},parts:{get:function(){return a}},components:{value:function(e,t){var n,a,i,s="",o="",r="";for(n in t){a=t[n];for(i in a.types)switch(a.types[i]){case"route":a.short_name.indexOf("Unnamed")==-1&&(s=a.short_name+(s?" "+s:""),o=a.long_name.replace("улица","").trim());break;case"administrative_area_level_1":e.region=a.long_name;break;case"administrative_area_level_2":e.city=a.short_name,e.city_long=a.long_name;break;case"locality":r=(r?r+" ":"")+a.short_name;break;case"street_number":s=(s?s+" ":"")+a.short_name;break;case"postal_code":e.postal_code=a.short_name}}return e.region&&e.region==e.city_long?e.city.indexOf(r)==-1?e.city=r:e.city="":r&&e.city.indexOf(r)==-1&&e.region.indexOf(r)==-1&&(s=r+", "+s),e.street&&e.street.indexOf(o)!=-1||(e.street=s),e}},location_callback:{value:function(){n=new google.maps.Geocoder,$p.eve.callEvent("geo_google_ready"),navigator.geolocation&&navigator.geolocation.getCurrentPosition(function(e){$p.ipinfo.latitude=e.coords.latitude,$p.ipinfo.longitude=e.coords.longitude;var t=new google.maps.LatLng($p.ipinfo.latitude,$p.ipinfo.longitude);n.geocode({latLng:t},function(e,t){t==google.maps.GeocoderStatus.OK&&(a=!e[1]||e[0].address_components.length>=e[1].address_components.length?e[0]:e[1],i=a.formatted_address,$p.eve.callEvent("geo_current_position",[$p.ipinfo.components({},a.address_components)]))})},$p.record_log,{timeout:3e4})}}})}function SpreadsheetDocument(e){this._attr={orientation:"portrait",title:"",content:document.createElement("DIV")},e&&"string"==typeof e?this.content=e:"object"==typeof e&&this._mixin(e),e=null}function HandsontableDocument(e,t){var n=function(){this._then&&this._then(this)}.bind(this);this._online=t&&t.allow_offline||navigator.onLine&&$p.wsql.pouch.authorized,e instanceof dhtmlXCellObject?(this._cont=document.createElement("div"),e.detachObject(!0),e.attachObject(this._cont)):this._cont=e,this._cont.classList.add("handsontable_wrapper"),this._online?this._cont.innerHTML=t.autorun?$p.msg.report_prepare:$p.msg.report_need_prepare:this._cont.innerHTML=$p.msg.report_need_online,this.then=function(e){return this._then=e,this},this.requery=function(e){this.hot&&this.hot.destroy(),e instanceof Error?this._cont.innerHTML=$p.msg.report_error+(e.name?" <b>"+e.name+"</b>":"")+(e.message?" "+e.message:""):(this._cont.innerHTML="",this.hot=new Handsontable(this._cont,e))},"function"!=typeof Handsontable&&this._online?$p.load_script("https://cdnjs.cloudflare.com/ajax/libs/pikaday/1.4.0/pikaday.min.js","script").then(function(){return $p.load_script("https://cdnjs.cloudflare.com/ajax/libs/numbro/1.9.2/numbro.min.js","script")}).then(function(){return $p.load_script("https://cdn.jsdelivr.net/g/zeroclipboard,handsontable@0.26(handsontable.min.js)","script")}).then(function(){return Promise.all([$p.load_script("https://cdn.jsdelivr.net/handsontable/0.26/handsontable.min.css","link"),$p.load_script("https://cdnjs.cloudflare.com/ajax/libs/numbro/1.9.2/languages/ru-RU.min.js","script")])}).then(n):setTimeout(n)}function Aes(e){"use strict";function t(e){return encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode("0x"+t)})}function n(e){try{return decodeURIComponent(escape(e))}catch(t){return e}}function a(e){if("undefined"!=typeof btoa)return btoa(e);if("undefined"!=typeof Buffer)return new Buffer(e,"binary").toString("base64");throw new Error("No Base64 Encode")}function i(e){if("undefined"!=typeof atob)return atob(e);if("undefined"!=typeof Buffer)return new Buffer(e,"base64").toString("binary");throw new Error("No Base64 Decode")}var s=this;s.cipher=function(e,t){for(var n=4,a=t.length/n-1,i=[[],[],[],[]],o=0;o<4*n;o++)i[o%4][Math.floor(o/4)]=e[o];i=s.addRoundKey(i,t,0,n);for(var r=1;r<a;r++)i=s.subBytes(i,n),i=s.shiftRows(i,n),i=s.mixColumns(i,n),i=s.addRoundKey(i,t,r,n);i=s.subBytes(i,n),i=s.shiftRows(i,n),i=s.addRoundKey(i,t,a,n);for(var l=new Array(4*n),o=0;o<4*n;o++)l[o]=i[o%4][Math.floor(o/4)];return l},s.keyExpansion=function(e){for(var t=4,n=e.length/4,a=n+6,i=new Array(t*(a+1)),o=new Array(4),r=0;r<n;r++){var l=[e[4*r],e[4*r+1],e[4*r+2],e[4*r+3]];i[r]=l}for(var r=n;r<t*(a+1);r++){i[r]=new Array(4);for(var c=0;c<4;c++)o[c]=i[r-1][c];if(r%n==0){o=s.subWord(s.rotWord(o));for(var c=0;c<4;c++)o[c]^=s.rCon[r/n][c]}else n>6&&r%n==4&&(o=s.subWord(o));for(var c=0;c<4;c++)i[r][c]=i[r-n][c]^o[c]}return i},s.subBytes=function(e,t){for(var n=0;n<4;n++)for(var a=0;a<t;a++)e[n][a]=s.sBox[e[n][a]];return e},s.shiftRows=function(e,t){for(var n=new Array(4),a=1;a<4;a++){for(var i=0;i<4;i++)n[i]=e[a][(i+a)%t];for(var i=0;i<4;i++)e[a][i]=n[i]}return e},s.mixColumns=function(e,t){for(var n=0;n<4;n++){for(var a=new Array(4),i=new Array(4),s=0;s<4;s++)a[s]=e[s][n],i[s]=128&e[s][n]?e[s][n]<<1^283:e[s][n]<<1;e[0][n]=i[0]^a[1]^i[1]^a[2]^a[3],e[1][n]=a[0]^i[1]^a[2]^i[2]^a[3],e[2][n]=a[0]^a[1]^i[2]^a[3]^i[3],e[3][n]=a[0]^i[0]^a[1]^a[2]^i[3]}return e},s.addRoundKey=function(e,t,n,a){for(var i=0;i<4;i++)for(var s=0;s<a;s++)e[i][s]^=t[4*n+s][i];return e},s.subWord=function(e){for(var t=0;t<4;t++)e[t]=s.sBox[e[t]];return e},s.rotWord=function(e){for(var t=e[0],n=0;n<3;n++)e[n]=e[n+1];return e[3]=t,e},s.sBox=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],s.rCon=[[0,0,0,0],[1,0,0,0],[2,0,0,0],[4,0,0,0],[8,0,0,0],[16,0,0,0],[32,0,0,0],[64,0,0,0],[128,0,0,0],[27,0,0,0],[54,0,0,0]],s.Ctr={},s.Ctr.encrypt=function(n,i,o){var r=16;128!=o&&192!=o&&256!=o&&(o=128),n=t(n),i=t(i||e);for(var l=o/8,c=new Array(l),p=0;p<l;p++)c[p]=p<i.length?i.charCodeAt(p):0;var d=s.cipher(c,s.keyExpansion(c));d=d.concat(d.slice(0,l-16));for(var u=new Array(r),m=(new Date).getTime(),f=m%1e3,h=Math.floor(m/1e3),_=Math.floor(65535*Math.random()),p=0;p<2;p++)u[p]=f>>>8*p&255;for(var p=0;p<2;p++)u[p+2]=_>>>8*p&255;for(var p=0;p<4;p++)u[p+4]=h>>>8*p&255;for(var g="",p=0;p<8;p++)g+=String.fromCharCode(u[p]);for(var b=s.keyExpansion(d),v=Math.ceil(n.length/r),x="",y=0;y<v;y++){for(var w=0;w<4;w++)u[15-w]=y>>>8*w&255;for(var w=0;w<4;w++)u[15-w-4]=y/4294967296>>>8*w;for(var k=s.cipher(u,b),$=y<v-1?r:(n.length-1)%r+1,j=new Array($),p=0;p<$;p++)j[p]=k[p]^n.charCodeAt(y*r+p),j[p]=String.fromCharCode(j[p]);x+=j.join(""),"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&y%1e3==0&&self.postMessage({progress:y/v})}return x=a(g+x)},s.Ctr.decrypt=function(a,o,r){var l=16;128!=r&&192!=r&&256!=r&&(r=128),a=i(a),o=t(o||e);for(var c=r/8,p=new Array(c),d=0;d<c;d++)p[d]=d<o.length?o.charCodeAt(d):0;var u=s.cipher(p,s.keyExpansion(p));u=u.concat(u.slice(0,c-16));for(var m=new Array(8),f=a.slice(0,8),d=0;d<8;d++)m[d]=f.charCodeAt(d);for(var h=s.keyExpansion(u),_=Math.ceil((a.length-8)/l),g=new Array(_),b=0;b<_;b++)g[b]=a.slice(8+b*l,8+b*l+l);a=g;for(var v="",b=0;b<_;b++){for(var x=0;x<4;x++)m[15-x]=b>>>8*x&255;for(var x=0;x<4;x++)m[15-x-4]=(b+1)/4294967296-1>>>8*x&255;for(var y=s.cipher(m,h),w=new Array(a[b].length),d=0;d<a[b].length;d++)w[d]=y[d]^a[b].charCodeAt(d),w[d]=String.fromCharCode(w[d]);v+=w.join(""),"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&b%1e3==0&&self.postMessage({progress:b/_})}return v=n(v)}}!function(e,t){"object"==typeof exports&&"undefined"!=typeof module&&"function"==typeof require?t(require("../moment")):"function"==typeof define&&define.amd?define(["../moment"],t):t(e.moment)}(this,function(e){"use strict";function t(e,t){var n=e.split("_");return t%10===1&&t%100!==11?n[0]:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?n[1]:n[2]}function n(e,n,a){var i={mm:n?"минута_минуты_минут":"минуту_минуты_минут",hh:"час_часа_часов",dd:"день_дня_дней",MM:"месяц_месяца_месяцев",yy:"год_года_лет"};return"m"===a?n?"минута":"минуту":e+" "+t(i[a],+e)}var a=[/^янв/i,/^фев/i,/^мар/i,/^апр/i,/^ма[йя]/i,/^июн/i,/^июл/i,/^авг/i,/^сен/i,/^окт/i,/^ноя/i,/^дек/i],i=e.defineLocale("ru",{months:{format:"января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря".split("_"),standalone:"январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_")},monthsShort:{format:"янв._февр._мар._апр._мая_июня_июля_авг._сент._окт._нояб._дек.".split("_"),standalone:"янв._февр._март_апр._май_июнь_июль_авг._сент._окт._нояб._дек.".split("_")},weekdays:{standalone:"воскресенье_понедельник_вторник_среда_четверг_пятница_суббота".split("_"),format:"воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу".split("_"),isFormat:/\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/},weekdaysShort:"вс_пн_вт_ср_чт_пт_сб".split("_"),weekdaysMin:"вс_пн_вт_ср_чт_пт_сб".split("_"),monthsParse:a,longMonthsParse:a,shortMonthsParse:a,monthsRegex:/^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i,monthsShortRegex:/^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i,monthsStrictRegex:/^(январ[яь]|феврал[яь]|марта?|апрел[яь]|ма[яй]|июн[яь]|июл[яь]|августа?|сентябр[яь]|октябр[яь]|ноябр[яь]|декабр[яь])/i,monthsShortStrictRegex:/^(янв\.|февр?\.|мар[т.]|апр\.|ма[яй]|июн[ья.]|июл[ья.]|авг\.|сент?\.|окт\.|нояб?\.|дек\.)/i,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY г.",LLL:"D MMMM YYYY г., HH:mm",LLLL:"dddd, D MMMM YYYY г., HH:mm"},calendar:{sameDay:"[Сегодня в] LT",nextDay:"[Завтра в] LT",lastDay:"[Вчера в] LT",nextWeek:function(e){if(e.week()===this.week())return 2===this.day()?"[Во] dddd [в] LT":"[В] dddd [в] LT";switch(this.day()){case 0:return"[В следующее] dddd [в] LT";case 1:case 2:case 4:return"[В следующий] dddd [в] LT";case 3:case 5:case 6:return"[В следующую] dddd [в] LT"}},lastWeek:function(e){if(e.week()===this.week())return 2===this.day()?"[Во] dddd [в] LT":"[В] dddd [в] LT";switch(this.day()){case 0:return"[В прошлое] dddd [в] LT";case 1:case 2:case 4:return"[В прошлый] dddd [в] LT";case 3:case 5:case 6:return"[В прошлую] dddd [в] LT"}},sameElse:"L"},relativeTime:{future:"через %s",past:"%s назад",s:"несколько секунд",m:n,mm:n,h:"час",hh:n,d:"день",dd:n,M:"месяц",MM:n,y:"год",yy:n},meridiemParse:/ночи|утра|дня|вечера/i,isPM:function(e){return/^(дня|вечера)$/.test(e)},meridiem:function(e,t,n){return e<4?"ночи":e<12?"утра":e<17?"дня":"вечера"},ordinalParse:/\d{1,2}-(й|го|я)/,ordinal:function(e,t){switch(t){case"M":case"d":case"DDD":return e+"-й";case"D":return e+"-го";case"w":case"W":return e+"-я";default:return e}},week:{dow:1,doy:7}});return i}),Object.defineProperties(Object.prototype,{__define:{value:function(e,t){return t?Object.defineProperty(this,e,t):Object.defineProperties(this,e),this}},_extend:{value:function(e){var t=function(){};t.prototype=e.prototype,this.prototype=new t,this.prototype.constructor=this,this.__define("superclass",{value:e.prototype,enumerable:!1})}},_mixin:{value:function(e,t,n){var a,i,s={};if(t&&t.length)for(a=0;a<t.length;a++)i=t[a],n&&n.indexOf(i)!=-1||"undefined"!=typeof s[i]&&s[i]==e[i]||(this[i]=e[i]);else for(i in e)n&&n.indexOf(i)!=-1||"undefined"!=typeof s[i]&&s[i]==e[i]||(this[i]=e[i]);return this}},_clone:{value:function(){if(!this||"object"!=typeof this)return this;var e,t,n="function"==typeof this.pop?[]:{};for(e in this)this.hasOwnProperty(e)&&(t=this[e],t?"function"==typeof t||t instanceof DataObj||t instanceof DataManager||t instanceof Date?n[e]=t:"object"==typeof t?n[e]=t._clone():n[e]=t:n[e]=t);return n}}}),Number.prototype.round||(Number.prototype.round=function(e){var t=Math.pow(10,e);return Math.round(this*t)/t}),Number.prototype.pad||(Number.prototype.pad=function(e){for(var t=String(this);t.length<(e||2);)t="0"+t;return t}),Object.observe||Object.unobserve||Object.getNotifier||Object.prototype.__define({observe:{value:function(e,t){e._observers||e.__define({_observers:{value:[],enumerable:!1},_notis:{value:[],enumerable:!1}}),e._observers.push(t)},enumerable:!1},unobserve:{value:function(e,t){if(e._observers){t||(e._observers.length=0);for(var n=0;n<e._observers.length;n++)if(e._observers[n]===t){e._observers.splice(n,1);break}}},enumerable:!1},getNotifier:{value:function(e){var t;return{notify:function(n){e._observers&&n&&(n.object||(n.object=e),e._notis.push(n),n=null,t&&clearTimeout(t),t=setTimeout(function(){e._notis.length&&(e._observers.forEach(function(t){t(e._notis)}),e._notis.length=0),t=!1},4))}}},enumerable:!1}});var $p=new MetaEngine;$p.__define({iface:{value:new InterfaceObjs,writable:!1},current_user:{get:function(){return $p.cat&&$p.cat.users?$p.cat.users.by_id($p.wsql.get_user_param("user_name")):$p.utils.blank.guid; +}},current_acl:{get:function(){var e,t;return $p.cat&&$p.cat.users_acl&&($p.cat.users_acl.find_rows({owner:$p.current_user},function(t){return e=t,!1}),t=$p.CatUsers_acl.prototype),t||(t={}),e||(this.utils.blank.users_acl?e=this.utils.blank.users_acl:(e=this.utils.blank.users_acl=Object.create(t),e.__define({acl_objs:{value:{_obj:[],each:function(){},find_rows:function(){}}}}))),t.hasOwnProperty("role_available")||t.__define({role_available:{value:function(e){return this.acl_objs._obj.some(function(t){return t.type==e})}},get_acl:{value:function(e){var t=e.split(".");return this._acl&&this._acl[t[0]]&&this._acl[t[0]][t[1]]?this._acl[t[0]][t[1]]:"e"}}}),e}},load_script:{value:function(e,t,n){return new Promise(function(a,i){var s=document.createElement(t);"script"==t?(s.type="text/javascript",s.src=e,s.async=!0,s.addEventListener("load",n?function(){n(),a()}:a,!1)):(s.type="text/css",s.rel="stylesheet",s.href=e),document.head.appendChild(s),"script"!=t&&a()})}}}),"undefined"!=typeof window&&window.dhx4&&(dhx4.dateFormat.ru="%d.%m.%Y",dhx4.dateLang="ru",dhx4.dateStrings={ru:{monthFullName:["Январь","Февраль","Март","Апрель","Maй","Июнь","Июль","Август","Сентябрь","Oктябрь","Ноябрь","Декабрь"],monthShortName:["Янв","Фев","Maр","Aпр","Maй","Июн","Июл","Aвг","Сен","Окт","Ноя","Дек"],dayFullName:["Воскресенье","Понедельник","Вторник","Среда","Четверг","Пятница","Суббота"],dayShortName:["Вс","Пн","Вт","Ср","Чт","Пт","Сб"]}}),$p.fias=function(){},function(e){e.toString=function(){return"Коды адресного классификатора"},e.types=["владение","здание","помещение"],e[1010]={name:"дом",type:1,order:1,fid:2,syn:[" д."," д "," дом"]},e[1020]={name:"владение",type:1,order:2,fid:1,syn:[" вл."," вл "," влад."," влад "," владен."," владен "," владение"]},e[1030]={name:"домовладение",type:1,order:3,fid:3},e[1050]={name:"корпус",type:2,order:1,syn:[" к."," к "," корп."," корп ","корпус"]},e[1060]={name:"строение",type:2,order:2,fid:1,syn:[" стр."," стр "," строен."," строен ","строение"]},e[1080]={name:"литера",type:2,order:3,fid:3,syn:[" л."," л "," лит."," лит ","литера"]},e[1070]={name:"сооружение",type:2,order:4,fid:2,syn:[" соор."," соор "," сооруж."," сооруж ","сооружение"]},e[1040]={name:"участок",type:2,order:5,syn:[" уч."," уч ","участок"]},e[2010]={name:"квартира",type:3,order:1,syn:["кв.","кв ","кварт.","кварт ","квартира","-"]},e[2030]={name:"офис",type:3,order:2,syn:["оф.","оф ","офис","-"]},e[2040]={name:"бокс",type:3,order:3},e[2020]={name:"помещение",type:3,order:4},e[2050]={name:"комната",type:3,order:5,syn:["комн.","комн ","комната"]},e[101e5]={name:"Почтовый индекс"},e[102e5]={name:"Адресная точка"},e[103e5]={name:"Садовое товарищество"},e[104e5]={name:"Элемент улично-дорожной сети, планировочной структуры дополнительного адресного элемента"},e[105e5]={name:"Промышленная зона"},e[106e5]={name:"Гаражно-строительный кооператив"},e[107e5]={name:"Территория"}}($p.fias),function(e){e.store_url_od="https://chrome.google.com/webstore/detail/hcncallbdlondnoadgjomnhifopfaage",e.argument_is_not_ref="Аргумент не является ссылкой",e.addr_title="Ввод адреса",e.cache_update_title="Обновление кеша браузера",e.cache_update="Выполняется загрузка измененных файлов<br/>и их кеширование в хранилище браузера",e.cancel="Отмена",e.delivery_area_empty="Укажите район доставки",e.empty_login_password="Не указаны имя пользователя или пароль",e.empty_response="Пустой ответ сервера",e.empty_geocoding="Пустой ответ геокодера. Вероятно, отслеживание адреса запрещено в настройках браузера",e.error_geocoding="Ошибка геокодера",e.error_auth="Авторизация пользователя не выполнена",e.error_critical="Критическая ошибка",e.error_metadata="Ошибка загрузки метаданных конфигурации",e.error_network="Ошибка сети или сервера - запрос отклонен",e.error_rights="Ограничение доступа",e.error_low_acl="Недостаточно прав для выполнения операции",e.file_size="Запрещена загрузка файлов<br/>размером более ",e.file_confirm_delete="Подтвердите удаление файла ",e.file_new_date="Файлы на сервере обновлены<br /> Рекомендуется закрыть браузер и войти<br />повторно для применения обновления",e.file_new_date_title="Версия файлов",e.init_catalogues="Загрузка справочников с сервера",e.init_catalogues_meta=": Метаданные объектов",e.init_catalogues_tables=": Реструктуризация таблиц",e.init_catalogues_nom=": Базовые типы + номенклатура",e.init_catalogues_sys=": Технологические справочники",e.init_login="Укажите имя пользователя и пароль",e.requery="Повторите попытку через 1-2 минуты",e.limit_query="Превышено число обращений к серверу<br/>Запросов за минуту:%1<br/>Лимит запросов:%2<br/>"+e.requery,e.long_operation="Длительная операция",e.logged_in="Авторизован под именем: ",e.log_out_title="Отключиться от сервера?",e.log_out_break="<br/>Завершить синхронизацию?",e.sync_title="Обмен с сервером",e.sync_complite="Синхронизация завершена",e.main_title="Окнософт: заказ дилера ",e.mark_delete_confirm="Пометить объект %1 на удаление?",e.mark_undelete_confirm="Снять пометку удаления с объекта %1?",e.meta={cat:"Справочник",doc:"Документ",cch:"План видов характеристик",cacc:"Планы счетов",tsk:"Задача",ireg:"Регистр сведений",areg:"Регистр накопления",bp:"Бизнес процесс",ts_row:"Строка табличной части",dp:"Обработка",rep:"Отчет"},e.meta_cat="Справочники",e.meta_doc="Документы",e.meta_cch="Планы видов характеристик",e.meta_cacc="Планы счетов",e.meta_tsk="Задачи",e.meta_ireg="Регистры сведений",e.meta_areg="Регистры накопления",e.meta_mgr="Менеджер",e.meta_cat_mgr="Менеджер справочников",e.meta_doc_mgr="Менеджер документов",e.meta_enn_mgr="Менеджер перечислений",e.meta_ireg_mgr="Менеджер регистров сведений",e.meta_areg_mgr="Менеджер регистров накопления",e.meta_accreg_mgr="Менеджер регистров бухгалтерии",e.meta_dp_mgr="Менеджер обработок",e.meta_task_mgr="Менеджер задач",e.meta_bp_mgr="Менеджер бизнес-процессов",e.meta_reports_mgr="Менеджер отчетов",e.meta_charts_of_accounts_mgr="Менеджер планов счетов",e.meta_charts_of_characteristic_mgr="Менеджер планов видов характеристик",e.meta_extender="Модификаторы объектов и менеджеров",e.modified_close="Объект изменен<br/>Закрыть без сохранения?",e.mandatory_title="Обязательный реквизит",e.mandatory_field="Укажите значение реквизита '%1'",e.no_metadata="Не найдены метаданные объекта '%1'",e.no_selected_row="Не выбрана строка табличной части '%1'",e.no_dhtmlx="Библиотека dhtmlx не загружена",e.not_implemented="Не реализовано в текущей версии",e.offline_request="Запрос к серверу в автономном режиме",e.onbeforeunload="Окнософт: легкий клиент. Закрыть программу?",e.order_sent_title="Подтвердите отправку заказа",e.order_sent_message="Отправленный заказ нельзя изменить.<br/>После проверки менеджером<br/>он будет запущен в работу",e.report_error="<i class='fa fa-exclamation-circle fa-2x fa-fw'></i> Ошибка",e.report_prepare="<i class='fa fa-spinner fa-spin fa-2x fa-fw'></i> Подготовка отчета",e.report_need_prepare="<i class='fa fa-info fa-2x fa-fw'></i> Нажмите 'Сформировать' для получения отчета",e.report_need_online="<i class='fa fa-plug fa-2x fa-fw'></i> Нет подключения. Отчет недоступен в автономном режиме",e.request_title="Запрос регистрации",e.request_message="Заявка зарегистрирована. После обработки менеджером будет сформировано ответное письмо",e.select_from_list="Выбор из списка",e.select_grp="Укажите группу, а не элемент",e.select_elm="Укажите элемент, а не группу",e.select_file_import="Укажите файл для импорта",e.srv_overload="Сервер перегружен",e.sub_row_change_disabled="Текущая строка подчинена продукции.<br/>Строку нельзя изменить-удалить в документе<br/>только через построитель",e.sync_script="Обновление скриптов приложения:",e.sync_data="Синхронизация с сервером выполняется:<br />* при первом старте программы<br /> * при обновлении метаданных<br /> * при изменении цен или технологических справочников",e.sync_break="Прервать синхронизацию",e.sync_no_data="Файл не содержит подходящих элементов для загрузки",e.tabular_will_cleared="Табличная часть '%1' будет очищена. Продолжить?",e.unsupported_browser_title="Браузер не поддерживается",e.unsupported_browser="Несовместимая версия браузера<br/>Рекомендуется Google Chrome",e.supported_browsers="Рекомендуется Chrome, Safari или Opera",e.unsupported_mode_title="Режим не поддерживается",e.unsupported_mode="Программа не установлена<br/> в <a href='"+e.store_url_od+"'>приложениях Google Chrome</a>",e.unknown_error="Неизвестная ошибка в функции '%1'",e.value="Значение"}($p.msg),DataManager.prototype.__define({family_name:{get:function(){return $p.msg["meta_"+this.class_name.split(".")[0]+"_mgr"].replace($p.msg.meta_mgr+" ","")}},table_name:{get:function(){return this.class_name.replace(".","_")}},find_rows:{value:function(e,t){return $p._find_rows.call(this,this.by_ref,e,t)}},extra_fields:{value:function(e){var t=$p.cat.destinations||$p.cch.destinations,n=_md.class_name_to_1c(this.class_name).replace(".","_"),a=[];return t&&t.find_rows({predefined_name:n},function(e){var t=e.extra_fields||e.ДополнительныеРеквизиты;return t&&t.each(function(e){e._deleted||e.ПометкаУдаления||a.push(e.property||e.Свойство)}),!1}),a}},extra_properties:{value:function(e){return[]}},obj_constructor:{value:function(e){var t=this.class_name.split("."),n=t[0].charAt(0).toUpperCase()+t[0].substr(1)+t[1].charAt(0).toUpperCase()+t[1].substr(1);return e?n+e.charAt(0).toUpperCase()+e.substr(1)+"Row":n}}}),DataManager.prototype.sync_grid=function(e,t){function n(){if("function"==typeof e.custom_selection)return e.custom_selection(e);if("ram"==i.cachable){if("get_tree"==e.action)return $p.wsql.promise(i.get_sql_struct(e),[]).then($p.iface.data_to_tree);if("get_selection"==e.action)return $p.wsql.promise(i.get_sql_struct(e),[]).then(function(t){return $p.iface.data_to_grid.call(i,t,e)})}else if(0==i.cachable.indexOf("doc")){if("get_tree"==e.action)return i.pouch_tree(e);if("get_selection"==e.action)return i.pouch_selection(e)}else{if("get_tree"==e.action)return i.rest_tree(e);if("get_selection"==e.action)return i.rest_selection(e)}}function a(e){return new Promise(function(n,a){"string"==typeof e?("{"==e.substr(0,1)&&(e=JSON.parse(e)),t&&t.parse?(t.xmlFileUrl="exec",t.parse(e,function(){n(e)},"xml")):n(e)):t instanceof dhtmlXTreeView&&t.loadStruct?t.loadStruct(e,function(){n(e)}):n(e)})}var i=this;return n().then(a).catch($p.record_log)},DataManager.prototype.get_option_list=function(e,t){function n(t){return $p.utils.is_equal(t.value,e)&&(t.selected=!0),t}var a,i,s,o=this,r=[];if(t.presentation&&(a=o.metadata().input_by_string)&&(i=t.presentation.like,delete t.presentation,t.or=[],a.forEach(function(e){s={},s[e]={like:i},t.or.push(s)})),"ram"==o.cachable||t&&t._local)return o.find_rows(t,function(e){r.push(n({text:e.presentation,value:e.ref}))}),Promise.resolve(r);if("e1cib"!=o.cachable)return o.pouch_find_rows(t).then(function(e){return e.forEach(function(e){r.push(n({text:e.presentation,value:e.ref}))}),r});var l={selection:t,top:t._top},c=o instanceof DocManager||o instanceof BusinessProcessManager;return delete t._top,c?l.fields=["ref","date","number_doc"]:o.metadata().main_presentation_name?l.fields=["ref","name"]:l.fields=["ref","id"],_rest.load_array(l,o).then(function(e){return e.forEach(function(e){r.push(n({text:c?e.number_doc+" от "+$p.moment(e.date).format($p.moment._masks.ldt):e.name||e.id,value:e.ref}))}),r})},DataManager.prototype.tabular_captions=function(e,t){},DataManager.prototype.get_property_grid_xml=function(e,t,n){var a,i,s,o,r,l,c,p=this,d="<rows>",u=function(){if(!e)if(s=p.metadata(),s.form&&s.form.obj&&s.form.obj.head)e=s.form.obj.head;else{if(e={" ":[]},t instanceof CatObj?(s.code_length&&e[" "].push("id"),s.main_presentation_name&&e[" "].push("name")):t instanceof DocObj&&(e[" "].push("number_doc"),e[" "].push("date")),!t.is_folder)for(a in s.fields)"predefined_name"==a||s.fields[a].hide||e[" "].push(a);s.tabular_sections&&s.tabular_sections.extra_fields&&(e["Дополнительные реквизиты"]=[])}},m=function(e,t){l=$p.utils.is_data_obj(e)?e.presentation:e,t.type.is_ref||(t.type.date_part?l=$p.moment(l).format($p.moment._masks[t.type.date_part]):"boolean"==t.type.types[0]&&(l=l?"1":"0"))},f=function(e){r=_md.control_by_type(s.type,e),m(e,s)},h=function(e,a){if(a){var i=e.property||e.param||e.Параметр||e.Свойство,u=void 0!=e.value?e.value:e.Значение;i.empty()?(c=a+"|empty",r="ro",l="",s={synonym:"?"}):(s={synonym:i.presentation,type:i.type},c=a+"|"+i.ref,f(u),"edn"==r&&(r="calck"),i.mandatory&&(r+='" class="cell_mandatory'))}else if("object"==typeof e)c=e.id,s=n&&n.metadata&&n.metadata[c],s?e.synonym&&(s.synonym=e.synonym):s={synonym:e.synonym},r=e.type,l="",e.hasOwnProperty("txt")?l=e.txt:void 0!==(o=t[c])&&m(o,s.type?s:_md.get(p.class_name,c));else if(n&&n.metadata&&void 0!==(s=n.metadata[e]))c=e,f(o=t[e]);else{if(void 0===(o=t[e]))return;s=_md.get(p.class_name,c=e),f(o)}d+='<row id="'+c+'"><cell>'+(s.synonym||s.name)+'</cell><cell type="'+r+'">'+l+"</cell></row>"};u();for(a in e){" "!=a&&(d+='<row open="1"><cell>'+a+"</cell>");for(i in e[a])h(e[a][i]);if(n&&a==n.title&&t[n.ts]){var _,g=p.extra_fields(t),b="property,param,Свойство,Параметр".split(","),v=t[n.ts]._owner._metadata.tabular_sections[t[n.ts]._name].fields;b.some(function(e){if(v[e])return _=e,!0})&&(t[n.ts].forEach(function(e){var t=g.indexOf(e[_]);t!=-1&&g.splice(t,1)}),g.forEach(function(e){var a=t[n.ts].add();a[_]=e})),t[n.ts].find_rows(n.selection,function(e){h(e,n.ts)})}" "!=a&&(d+="</row>")}return d+="</rows>"},DataManager.prototype.print=function(e,t,n){function a(e){n&&n.progressOff&&n.progressOff(),e&&e.focus()}if(n&&n.progressOn&&n.progressOn(),setTimeout(a,3e3),this._printing_plates[t]instanceof DataObj&&(t=this._printing_plates[t]),t instanceof DataObj&&t.execute)return e instanceof DataObj?t.execute(e).then(a):this.get(e,!0,!0).then(t.execute.bind(t)).then(a);var i={};return $p.ajax.default_attr(i,$p.job_prm.irest_url()),i.url+=this.rest_name+"(guid'"+$p.utils.fix_guid(e)+"')/Print(model="+t+", browser_uid="+$p.wsql.get_user_param("browser_uid")+")",$p.ajax.get_and_show_blob(i.url,i,"get").then(a)},DataManager.prototype.printing_plates=function(){var e={},t=this;return t._printing_plates||(t.metadata().printing_plates?t._printing_plates=t.metadata().printing_plates:("ram"==t.metadata().cachable||t.metadata().cachable&&0==t.metadata().cachable.indexOf("doc"))&&(t._printing_plates={})),!t._printing_plates&&$p.ajax.authorized?($p.ajax.default_attr(e,$p.job_prm.irest_url()),e.url+=t.rest_name+"/Print()",$p.ajax.get_ex(e.url,e).then(function(e){return t._printing_plates=JSON.parse(e.response),t._printing_plates}).catch(function(){}).then(function(e){return e||(t._printing_plates={})})):Promise.resolve(t._printing_plates)},RefDataManager._extend(DataManager),RefDataManager.prototype.__define({push:{value:function(e,t){t&&t!=e.ref?(delete this.by_ref[e.ref],this.by_ref[t]=e):this.by_ref[e.ref]=e}},each:{value:function(e){for(var t in this.by_ref)if(t&&t!=$p.utils.blank.guid&&1==e.call(this,this.by_ref[t]))break}},forEach:{value:function(e){return this.each.call(this,e)}},get:{value:function(e,t,n){var a=this.by_ref[e]||this.by_ref[e=$p.utils.fix_guid(e)];if(!a){if(n&&!t)return;a=new($p[this.obj_constructor()])(e,this,(!0))}return t===!1?a:void 0===t&&e===$p.utils.blank.guid?a:a.is_new()?a.load():t?Promise.resolve(a):a}},create:{value:function(e,t,n){e&&"object"==typeof e||(e={}),e.ref&&$p.utils.is_guid(e.ref)&&!$p.utils.is_empty_guid(e.ref)||(e.ref=$p.utils.generate_guid());var a=this.by_ref[e.ref];if(!a)if(a=new($p[this.obj_constructor()])(e,this),!t&&e.ref&&e.presentation&&2==Object.keys(e).length);else{a instanceof DocObj&&a.date==$p.utils.blank.date&&(a.date=new Date);var i=this.handle_event(a,"after_create");if(this instanceof DocManager||this instanceof TaskManager||this instanceof BusinessProcessManager?a.number_doc||a.new_number_doc():!a.id&&a._metadata.code_length&&a.new_number_doc(),i===!1)return Promise.resolve(a);if("object"==typeof i&&i.then)return i;if("e1cib"==this.cachable&&t){var s={};return $p.ajax.default_attr(s,$p.job_prm.irest_url()),s.url+=this.rest_name+"/Create()",$p.ajax.get_ex(s.url,s).then(function(e){return a._mixin(JSON.parse(e.response),void 0,["ref"])})}}return n?a:Promise.resolve(a)}},unload_obj:{value:function(e){delete this.by_ref[e],this.alatable.some(function(t,n,a){if(t.ref==e)return a.splice(n,1),!0})}},find:{value:function(e,t){return $p._find(this.by_ref,e,t)}},load_array:{value:function(e,t){for(var n,a,i=[],s=0;s<e.length;s++){if(n=$p.utils.fix_guid(e[s]),a=this.by_ref[n])(a.is_new()||t)&&(a._mixin(e[s]),a._set_loaded());else{if("update_only"==t)continue;a=new($p[this.obj_constructor()])(e[s],this),t&&a._set_loaded()}i.push(a)}return i}},first_folder:{value:function(e){for(var t in this.by_ref){var n=this.by_ref[t];if(n.is_folder&&(!e||$p.utils.is_equal(e,n.owner)))return n}return this.get()}},get_sql_struct:{value:function(e){function t(){function t(){var e=[],t="_t_.ref, _t_.`_deleted`";return r.form&&r.form.selection?r.form.selection.fields.forEach(function(t){e.push(t)}):o instanceof DocManager?(e.push("posted"),e.push("date"),e.push("number_doc")):(r.hierarchical&&r.group_hierarchy?e.push("is_folder"):e.push("0 as is_folder"),o instanceof ChartOfAccountManager?(e.push("id"),e.push("name as presentation")):r.main_presentation_name?e.push("name as presentation"):r.code_length?e.push("id as presentation"):e.push("'...' as presentation"),r.has_owners&&e.push("owner"),r.code_length&&e.push("id")),e.forEach(function(e){t+=e.indexOf(" as ")!=-1?", "+e:_md.sql_mask(e,!0)}),t}function n(){var e,t="";if(r.form&&r.form.selection)for(var n in r.form.selection.fields)r.form.selection.fields[n].indexOf(" as ")!=-1&&r.form.selection.fields[n].indexOf("_t_.")==-1&&(e=r.form.selection.fields[n].split(" as "),e[0]=e[0].split("."),e[0].length>1&&(t&&(t+="\n"),t+="left outer join "+e[0][0]+" on "+e[0][0]+".ref = _t_."+e[1]));return t}function a(){var t;return t=o instanceof ChartOfAccountManager?" WHERE ("+(u?0:1):r.hierarchical?r.has_owners?" WHERE ("+(c||u?1:0)+" OR _t_.parent = '"+p+"') AND ("+(l==$p.utils.blank.guid?1:0)+" OR _t_.owner = '"+l+"') AND ("+(u?0:1):" WHERE ("+(c||u?1:0)+" OR _t_.parent = '"+p+"') AND ("+(u?0:1):r.has_owners?" WHERE ("+(l==$p.utils.blank.guid?1:0)+" OR _t_.owner = '"+l+"') AND ("+(u?0:1):" WHERE ("+(u?0:1),o.sql_selection_where_flds?t+=o.sql_selection_where_flds(u):o instanceof DocManager?t+=" OR _t_.number_doc LIKE '"+u+"'":((r.main_presentation_name||o instanceof ChartOfAccountManager)&&(t+=" OR _t_.name LIKE '"+u+"'"),r.code_length&&(t+=" OR _t_.id LIKE '"+u+"'")),t+=") AND (_t_.ref != '"+$p.utils.blank.guid+"')",e.selection&&("function"==typeof e.selection||e.selection.forEach(function(e){for(var n in e)if("function"==typeof e[n])t+="\n AND "+e[n](o,n)+" ";else if(r.fields.hasOwnProperty(n)||"ref"===n)if(e[n]===!0)t+="\n AND _t_."+n+" ";else if(e[n]===!1)t+="\n AND (not _t_."+n+") ";else if("object"==typeof e[n])if($p.utils.is_data_obj(e[n])||$p.utils.is_guid(e[n]))t+="\n AND (_t_."+n+" = '"+e[n]+"') ";else{var a,i=Object.keys(e[n]),s=e[n][i[0]],l=r.fields[n];l&&l.type.is_ref&&(a=_md.value_mgr({},n,l.type,!0,s)),t+="not"==i[0]?"\n AND (not _t_."+n+" = '"+s+"') ":"in"==i[0]?"\n AND (_t_."+n+" in ("+e[n].in.reduce(function(e,t){return e&&(e+=","),e+="number"==typeof t?t.toString():"'"+t+"'"},"")+")) ":"\n AND (_t_."+n+" = '"+s+"') "}else t+="string"==typeof e[n]?"\n AND (_t_."+n+" = '"+e[n]+"') ":"\n AND (_t_."+n+" = "+e[n]+") ";else"is_folder"==n&&r.hierarchical&&r.group_hierarchy})),t}function i(){return o instanceof ChartOfAccountManager?"ORDER BY id":r.hierarchical?r.group_hierarchy?"ORDER BY _t_.is_folder desc, is_initial_value, presentation":"ORDER BY _t_.parent desc, is_initial_value, presentation":"ORDER BY is_initial_value, presentation"}function s(){function t(t){t&&(m=e.set_parent=t.parent.ref,p=m,c=!1),u&&u.indexOf("%")==-1&&(u="%"+u+"%")}r.has_owners&&(l=e.owner,e.selection&&"function"!=typeof e.selection&&e.selection.forEach(function(e){e.owner&&(l="object"==typeof e.owner?e.owner.valueOf():e.owner,delete e.owner)}),l||(l=$p.utils.blank.guid)),d!=$p.utils.blank.guid&&c&&r.hierarchical?t(o.get(d,!1)):t()}var l,c=!e.parent,p=e.parent||$p.utils.blank.guid,d=e.initial_value||$p.utils.blank.guid,u=e.filter||"",m=$p.utils.blank.guid;s();var f;return f=o.sql_selection_list_flds?o.sql_selection_list_flds(d):("SELECT %2, case when _t_.ref = '"+d+"' then 0 else 1 end as is_initial_value FROM `"+o.table_name+"` AS _t_ %j %3 %4 LIMIT 300").replace("%2",t()).replace("%j",n()),f.replace("%3",a()).replace("%4",i())}function n(){var t="CREATE TABLE IF NOT EXISTS ";if(e&&e.postgres){t+=o.table_name+" (ref uuid PRIMARY KEY NOT NULL, _deleted boolean",o instanceof DocManager?t+=", posted boolean, date timestamp with time zone, number_doc character(11)":(r.code_length&&(t+=", id character("+r.code_length+")"),t+=", name character varying(50), is_folder boolean");for(i in r.fields)i.length>30?r.fields[i].short_name?s=r.fields[i].short_name:(c++,s=i[0]+c+i.substr(i.length-27)):s=i,t+=", "+s+_md.sql_type(o,i,r.fields[i].type,!0)+_md.sql_composite(r.fields,i,s,!0);for(i in r.tabular_sections)t+=", ts_"+i+" JSON"}else{t+="`"+o.table_name+"` (ref CHAR PRIMARY KEY NOT NULL, `_deleted` BOOLEAN",t+=o instanceof DocManager?", posted boolean, date Date, number_doc CHAR":", id CHAR, name CHAR, is_folder BOOLEAN";for(i in r.fields)t+=_md.sql_mask(i)+_md.sql_type(o,i,r.fields[i].type)+_md.sql_composite(r.fields,i);for(i in r.tabular_sections)t+=", `ts_"+i+"` JSON"}return t+=")"}function a(){var e=["ref","_deleted"],t="INSERT INTO `"+o.table_name+"` (ref, `_deleted`",n="(?";"cat"==o.class_name.substr(0,3)?(t+=", id, name, is_folder",e.push("id"),e.push("name"),e.push("is_folder")):"doc"==o.class_name.substr(0,3)&&(t+=", posted, date, number_doc",e.push("posted"),e.push("date"),e.push("number_doc"));for(i in r.fields)t+=_md.sql_mask(i),e.push(i);for(i in r.tabular_sections)t+=", `ts_"+i+"`",e.push("ts_"+i);for(t+=") VALUES ",i=1;i<e.length;i++)n+=", ?";return n+=")",t+=n,{sql:t,fields:e,values:n}}var i,s,o=this,r=o.metadata(),l={},c=0,p=e&&e.action?e.action:"create_table";return"create_table"==p?l=n():["insert","update","replace"].indexOf(p)!=-1?l[o.table_name]=a():"select"==p?l="SELECT * FROM `"+o.table_name+"` WHERE ref = ?":"select_all"==p?l="SELECT * FROM `"+o.table_name+"`":"delete"==p?l="DELETE FROM `"+o.table_name+"` WHERE ref = ?":"drop"==p?l="DROP TABLE IF EXISTS `"+o.table_name+"`":"get_tree"==p?l=!e.filter||e.filter.is_folder?"SELECT ref, parent, name as presentation FROM `"+o.table_name+"` WHERE is_folder order by parent, name":"SELECT ref, parent, name as presentation FROM `"+o.table_name+"` order by parent, name":"get_selection"==p&&(l=t()),l}},caption_flds:{value:function(e){var t=e.metadata||this.metadata(),n='<column id="%1" width="%2" type="%3" align="%4" sort="%5">%6</column>',a=[],i="";if(t.form&&t.form.selection?a=t.form.selection.cols:this instanceof DocManager?(a.push(new Col_struct("date","160","ro","left","server","Дата")),a.push(new Col_struct("number_doc","140","ro","left","server","Номер")),t.fields.note&&a.push(new Col_struct("note","*","ro","left","server",t.fields.note.synonym)),t.fields.responsible&&a.push(new Col_struct("responsible","*","ro","left","server",t.fields.responsible.synonym))):this instanceof ChartOfAccountManager?(a.push(new Col_struct("id","140","ro","left","server","Код")),a.push(new Col_struct("presentation","*","ro","left","server","Наименование"))):a.push(new Col_struct("presentation","*","ro","left","server","Наименование")),e.get_header&&a.length){i="<head>";for(var s in a)i+=n.replace("%1",a[s].id).replace("%2",a[s].width).replace("%3",a[s].type).replace("%4",a[s].align).replace("%5",a[s].sort).replace("%6",a[s].caption);i+="</head>"}return{head:i,acols:a}}},load_cached_server_array:{value:function(e,t){var n,a=[],i=this,s=t?{class_name:i.class_name,rest_name:t}:i,o=!t;if(e.forEach(function(e){n=i.get(e.ref||e,!1,!0),(!n||o&&n.is_new())&&a.push(e.ref||e)}),a.length){var r={url:"",selection:{ref:{in:a}}};return o&&(r.fields=["ref"]),$p.rest.build_select(r,s),$p.ajax.get_ex(r.url,r).then(function(t){var n=JSON.parse(t.response);if(o)n=n.value;else{n=n.data;for(var a in n)!n[a].ref&&n[a].id&&(n[a].ref=n[a].id),n[a].Код&&(n[a].id=n[a].Код,delete n[a].Код),n[a]._not_set_loaded=!0}return i.load_array(n),e})}return Promise.resolve(e)}},predefined:{value:function(e){return this._predefined||(this._predefined={}),this._predefined[e]||(this._predefined[e]=this.get(),this.find_rows({predefined_name:e},function(t){return this._predefined[e]=t,!1})),this._predefined[e]}}}),DataProcessorsManager._extend(DataManager),DataProcessorsManager.prototype.__define({create:{value:function(){return new($p[this.obj_constructor()])({},this)}},unload_obj:{value:function(){}}}),EnumManager._extend(RefDataManager),EnumManager.prototype.__define({get:{value:function(e){if(e instanceof EnumObj)return e;e&&e!=$p.utils.blank.guid||(e="_");var t=this[e];return t||(t=new EnumObj({name:e},this)),t}},push:{value:function(e,t){this.__define(t,{value:e})}},each:{value:function(e){this.alatable.forEach(function(t){t.ref&&"_"!=t.ref&&t.ref!=$p.utils.blank.guid&&e.call(this[t.ref])}.bind(this))}}}),EnumManager.prototype.get_sql_struct=function(e){var t="CREATE TABLE IF NOT EXISTS ",n=e&&e.action?e.action:"create_table";return e&&e.postgres?"create_table"==n?t+=this.table_name+" (ref character varying(255) PRIMARY KEY NOT NULL, sequence INT, synonym character varying(255))":["insert","update","replace"].indexOf(n)!=-1?(t={},t[this.table_name]={sql:"INSERT INTO "+this.table_name+" (ref, sequence, synonym) VALUES ($1, $2, $3)",fields:["ref","sequence","synonym"],values:"($1, $2, $3)"}):"delete"==n&&(t="DELETE FROM "+this.table_name+" WHERE ref = $1"):"create_table"==n?t+="`"+this.table_name+"` (ref CHAR PRIMARY KEY NOT NULL, sequence INT, synonym CHAR)":["insert","update","replace"].indexOf(n)!=-1?(t={},t[this.table_name]={sql:"INSERT INTO `"+this.table_name+"` (ref, sequence, synonym) VALUES (?, ?, ?)",fields:["ref","sequence","synonym"],values:"(?, ?, ?)"}):"delete"==n&&(t="DELETE FROM `"+this.table_name+"` WHERE ref = ?"),t},EnumManager.prototype.get_option_list=function(e,t){function n(t){return $p.utils.is_equal(t.value,e)&&(t.selected=!0),t}var a,i=[],s="";if(t)for(var o in t)"_"!=o.substr(0,1)&&("ref"==o?a=t[o].hasOwnProperty("in")?t[o].in:t[o]:s=t[o]);return"object"==typeof s&&(s=s.like?s.like:""),s=s.toLowerCase(),this.alatable.forEach(function(e){if(!s||e.synonym&&e.synonym.toLowerCase().indexOf(s)!=-1){if(a)if(Array.isArray(a)){if(!a.some(function(t){return t.name==e.ref||t.ref==e.ref||t==e.ref}))return}else if(a.name!=e.ref&&a.ref!=e.ref&&a!=e.ref)return;i.push(n({text:e.synonym||"",value:e.ref}))}}),Promise.resolve(i)},RegisterManager._extend(DataManager),RegisterManager.prototype.__define({get_sql_struct:{value:function(e){function t(){function t(){var e=[],t="_t_.ref";if(r.form&&r.form.selection)r.form.selection.fields.forEach(function(t){e.push(t)});else for(var n in r.dimensions)e.push(n);return e.forEach(function(e){t+=e.indexOf(" as ")!=-1?", "+e:_md.sql_mask(e,!0)}),t}function n(){var e,t="";if(r.form&&r.form.selection)for(var n in r.form.selection.fields)r.form.selection.fields[n].indexOf(" as ")!=-1&&r.form.selection.fields[n].indexOf("_t_.")==-1&&(e=r.form.selection.fields[n].split(" as "),e[0]=e[0].split("."),e[0].length>1&&(t&&(t+="\n"),t+="left outer join "+e[0][0]+" on "+e[0][0]+".ref = _t_."+e[1]));return t}function a(){var t=" WHERE ("+(s?0:1);return o.sql_selection_where_flds&&(t+=o.sql_selection_where_flds(s)),t+=")",e.selection&&("function"==typeof e.selection||e.selection.forEach(function(e){for(var n in e)if("function"==typeof e[n])t+="\n AND "+e[n](o,n)+" ";else if(r.fields.hasOwnProperty(n))if(e[n]===!0)t+="\n AND _t_."+n+" ";else if(e[n]===!1)t+="\n AND (not _t_."+n+") ";else if("object"==typeof e[n])if($p.utils.is_data_obj(e[n]))t+="\n AND (_t_."+n+" = '"+e[n]+"') ";else{var a,i=Object.keys(e[n]),s=e[n][i[0]],l=r.fields[n];l&&l.type.is_ref&&(a=_md.value_mgr({},n,l.type,!0,s)),t+="not"==i[0]?"\n AND (not _t_."+n+" = '"+s+"') ":"\n AND (_t_."+n+" = '"+s+"') "}else t+="string"==typeof e[n]?"\n AND (_t_."+n+" = '"+e[n]+"') ":"\n AND (_t_."+n+" = "+e[n]+") ";else"is_folder"==n&&r.hierarchical&&r.group_hierarchy})),t}function i(){return""}var s=e.filter||"";s&&s.indexOf("%")==-1&&(s="%"+s+"%");var l;return l=o.sql_selection_list_flds?o.sql_selection_list_flds():("SELECT %2 FROM `"+o.table_name+"` AS _t_ %j %3 %4 LIMIT 300").replace("%2",t()).replace("%j",n()),l.replace("%3",a()).replace("%4",i())}function n(){var t="CREATE TABLE IF NOT EXISTS ",n=!0;if(e&&e.postgres){t+=o.table_name+" (",r.splitted&&(t+="zone integer",n=!1);for(s in r.dimensions)n?(t+=s,n=!1):t+=", "+s,t+=_md.sql_type(o,s,r.dimensions[s].type,!0)+_md.sql_composite(r.dimensions,s,"",!0);for(s in r.resources)t+=", "+s+_md.sql_type(o,s,r.resources[s].type,!0)+_md.sql_composite(r.resources,s,"",!0);for(s in r.attributes)t+=", "+s+_md.sql_type(o,s,r.attributes[s].type,!0)+_md.sql_composite(r.attributes,s,"",!0);t+=", PRIMARY KEY (",n=!0,r.splitted&&(t+="zone",n=!1);for(s in r.dimensions)n?(t+=s,n=!1):t+=", "+s}else{t+="`"+o.table_name+"` (ref CHAR PRIMARY KEY NOT NULL, `_deleted` BOOLEAN";for(s in r.dimensions)t+=_md.sql_mask(s)+_md.sql_type(o,s,r.dimensions[s].type);for(s in r.resources)t+=_md.sql_mask(s)+_md.sql_type(o,s,r.resources[s].type);for(s in r.attributes)t+=_md.sql_mask(s)+_md.sql_type(o,s,r.attributes[s].type)}return t+=")"}function a(){var e="INSERT OR REPLACE INTO `"+o.table_name+"` (",t=[],n=!0;for(s in r.dimensions)n?(e+=s,n=!1):e+=", "+s,t.push(s);for(s in r.resources)e+=", "+s,t.push(s);for(s in r.attributes)e+=", "+s,t.push(s);for(e+=") VALUES (?",s=1;s<t.length;s++)e+=", ?";return e+=")",{sql:e,fields:t}}function i(){var t="SELECT * FROM `"+o.table_name+"` WHERE ",n=!0;e._values=[];for(var a in r.dimensions)n?n=!1:t+=" and ",t+="`"+a+"`=?",e._values.push(e[a]);return n&&(t+="1"),t}var s,o=this,r=o.metadata(),l={},c=e&&e.action?e.action:"create_table";return"create_table"==c?l=n():c in{insert:"",update:"",replace:""}?l[o.table_name]=a():"select"==c?l=i():"select_all"==c?l=i():"delete"==c?l="DELETE FROM `"+o.table_name+"` WHERE ref = ?":"drop"==c?l="DROP TABLE IF EXISTS `"+o.table_name+"`":"get_selection"==c&&(l=t()),l}},get_ref:{value:function(e){if(e instanceof RegisterRow&&(e=e._obj),e.ref)return e.ref;var t="",n=this.metadata().dimensions;for(var a in n)t+=t?"¶":"",t+=n[a].type.is_ref?$p.utils.fix_guid(e[a]):!e[a]&&n[a].type.digits?"0":n[a].date_part?$p.moment(e[a]||$p.utils.blank.date).format($p.moment.defaultFormatUtc):void 0!=e[a]?String(e[a]):"$";return t}},caption_flds:{value:function(e){var t=e.metadata||this.metadata(),n='<column id="%1" width="%2" type="%3" align="%4" sort="%5">%6</column>',a=[],i="";if(t.form&&t.form.selection)a=t.form.selection.cols;else for(var s in t.dimensions)a.push(new Col_struct(s,"*","ro","left","server",t.dimensions[s].synonym));if(e.get_header&&a.length){i="<head>";for(var o in a)i+=n.replace("%1",a[o].id).replace("%2",a[o].width).replace("%3",a[o].type).replace("%4",a[o].align).replace("%5",a[o].sort).replace("%6",a[o].caption);i+="</head>"}return{head:i,acols:a}}},create:{value:function(e){e&&"object"==typeof e||(e={});var t=this.by_ref[e.ref];if(!t){t=new($p[this.obj_constructor()])(e,this);var n=this.handle_event(t,"after_create");if(n===!1)return Promise.resolve(t);if("object"==typeof n&&n.then)return n}return Promise.resolve(t)}}}),InfoRegManager._extend(RegisterManager),InfoRegManager.prototype.slice_first=function(e){},InfoRegManager.prototype.slice_last=function(e){},AccumRegManager._extend(RegisterManager),CatManager._extend(RefDataManager),CatManager.prototype.by_name=function(e){var t;return this.find_rows({name:e},function(e){return t=e,!1}),t||(t=this.get()),t},CatManager.prototype.by_id=function(e){var t;return this.find_rows({id:e},function(e){return t=e,!1}),t||(t=this.get()),t},CatManager.prototype.path=function(e){ +var t,n=[];if(t=e instanceof DataObj?e:this.get(e,!1,!0),t&&n.push({ref:t.ref,presentation:t.presentation}),t&&this.metadata().hierarchical)for(;;){if(t=t.parent,t.empty())break;n.push({ref:t.ref,presentation:t.presentation})}return n},ChartOfCharacteristicManager._extend(CatManager),ChartOfAccountManager._extend(CatManager),DocManager._extend(RefDataManager),TaskManager._extend(CatManager),BusinessProcessManager._extend(CatManager),LogManager._extend(InfoRegManager),MetaObjManager._extend(CatManager),MetaFieldManager._extend(CatManager),SchemeSettingsManager._extend(CatManager),DataObj.prototype._getter=function(e){var t,n=this._metadata.fields[e].type,a=this._obj?this._obj[e]:"";return"type"==e&&"object"==typeof a?a:"ref"==e?a:n.is_ref?n.digits&&"number"==typeof a?a:n.hasOwnProperty("str_len")&&!$p.utils.is_guid(a)?a:(t=_md.value_mgr(this._obj,e,n))?$p.utils.is_data_mgr(t)?t.get(a,!1):$p.utils.fetch_type(a,t):a?(console.log([e,n,this._obj]),null):void 0:n.date_part?$p.utils.fix_date(this._obj[e],!0):n.digits?$p.utils.fix_number(this._obj[e],!n.hasOwnProperty("str_len")):"boolean"==n.types[0]?$p.utils.fix_boolean(this._obj[e]):this._obj[e]||""},DataObj.prototype.__setter=function(e,t){var n,a=this._metadata.fields[e].type;"type"==e&&t.types?this._obj[e]=t:"ref"==e?this._obj[e]=$p.utils.fix_guid(t):a.is_ref?a.digits&&"number"==typeof t||a.hasOwnProperty("str_len")&&"string"==typeof t&&!$p.utils.is_guid(t)?this._obj[e]=t:(this._obj[e]=$p.utils.fix_guid(t),n=_md.value_mgr(this._obj,e,a,!1,t),n?n instanceof EnumManager?"string"==typeof t?this._obj[e]=t:t?"object"==typeof t&&(this._obj[e]=t.ref||t.name||""):this._obj[e]="":t&&t.presentation?(!t.type||t instanceof DataObj||delete t.type,n.create(t)):$p.utils.is_data_mgr(n)||(this._obj[e]=$p.utils.fetch_type(t,n)):"object"!=typeof t&&(this._obj[e]=t)):a.date_part?this._obj[e]=$p.utils.fix_date(t,!0):a.digits?this._obj[e]=$p.utils.fix_number(t,!a.hasOwnProperty("str_len")):"boolean"==a.types[0]?this._obj[e]=$p.utils.fix_boolean(t):this._obj[e]=t},DataObj.prototype.__notify=function(e){this._data._silent||Object.getNotifier(this).notify({type:"update",name:e,oldValue:this._obj[e]})},DataObj.prototype._setter=function(e,t){this._obj[e]!=t&&(this.__notify(e),this.__setter(e,t),this._data._modified=!0)},DataObj.prototype._getter_ts=function(e){return this._ts_(e)},DataObj.prototype._setter_ts=function(e,t){var n=this._ts_(e);n instanceof TabularSection&&Array.isArray(t)&&n.load(t)},DataObj.prototype.__define({valueOf:{value:function(){return this.ref}},toJSON:{value:function(){return this._obj}},toString:{value:function(){return this.presentation}},_metadata:{get:function(){return this._manager.metadata()}},_deleted:{get:function(){return!!this._obj._deleted}},_modified:{get:function(){return!!this._data&&!!this._data._modified}},is_new:{value:function(){return this._data._is_new}},_set_loaded:{value:function(e){return this._manager.push(this,e),this._data._modified=!1,this._data._is_new=!1,this}},mark_deleted:{value:function(e){return this._obj._deleted=!!e,this.save(),this.__notify("_deleted"),this}},ref:{get:function(){return this._obj.ref},set:function(e){this._obj.ref=$p.utils.fix_guid(e)},enumerable:!0,configurable:!0},empty:{value:function(){return $p.utils.is_empty_guid(this._obj.ref)}},load:{value:function(){var e=function(){return e=null,this._data._modified=!1,this}.bind(this);return this.ref==$p.utils.blank.guid?(this instanceof CatObj?this.id="000000000":this.number_doc="000000000",Promise.resolve(this)):this._manager.cachable&&"e1cib"!=this._manager.cachable?$p.wsql.pouch.load_obj(this).then(e):_rest.load_obj(this).then(e)}},unload:{value:function(){var e,t=this._obj;this._manager.unload_obj(this.ref),this._observers&&(this._observers.length=0),this._notis&&(this._notis.length=0);for(e in this._metadata.tabular_sections)this[e].clear(!0);for(e in this)this.hasOwnProperty(e)&&delete this[e];for(e in t)delete t[e];["_ts_","_obj","_data"].forEach(function(e){delete this[e]}.bind(this)),e=t=null}},save:{value:function(e,t,n){if(this instanceof DocObj&&"boolean"==typeof e){var a=this.posted;this.posted=e}var i,s=this._manager.handle_event(this,"before_save"),o=function(){return s===!1?this instanceof DocObj&&"boolean"==typeof a&&this.posted!=a&&(this.posted=a):this._data._modified=!1,i=null,s=null,o=null,this}.bind(this);if(s===!1)return Promise.reject(o());if(s instanceof Promise||"object"==typeof s&&s.then)return s.then(o);if(this._metadata.hierarchical&&!this._obj.parent&&(this._obj.parent=$p.utils.blank.guid),this instanceof DocObj||this instanceof TaskObj||this instanceof BusinessProcessObj?($p.utils.blank.date==this.date&&(this.date=new Date),this.number_doc||this.new_number_doc()):this.id||this.new_number_doc(),$p.msg&&$p.msg.show_msg)for(var r in this._metadata.fields)if(this._metadata.fields[r].mandatory&&!this._obj[r])return $p.msg.show_msg({title:$p.msg.mandatory_title,type:"alert-error",text:$p.msg.mandatory_field.replace("%1",this._metadata.fields[r].synonym)}),s=!1,Promise.reject(o());return i=this._manager.cachable&&"e1cib"!=this._manager.cachable?$p.wsql.pouch.save_obj:_rest.save_irest,i(this,{post:e,operational:t,attachments:n}).then(function(e){return e._manager.handle_event(e,"after_save")}).then(o)}},get_attachment:{value:function(e){return this._manager.get_attachment(this.ref,e)}},save_attachment:{value:function(e,t,n){return this._manager.save_attachment(this.ref,e,t,n).then(function(t){return this._attachments||(this._attachments={}),this._attachments[e]&&t.stub||(this._attachments[e]=t),t}.bind(this))}},delete_attachment:{value:function(e){return this._manager.delete_attachment(this.ref,e).then(function(t){return this._attachments&&delete this._attachments[e],t}.bind(this))}},_silent:{value:function(e){"boolean"==typeof e?this._data._silent=e:(this._data._silent=!0,setTimeout(function(){this._data._silent=!1}.bind(this)))}},print:{value:function(e,t){return this._manager.print(this,e,t)}}}),CatObj._extend(DataObj),CatObj.prototype.__define("id",{get:function(){return this._obj.id||""},set:function(e){this.__notify("id"),this._obj.id=e},enumerable:!0}),CatObj.prototype.__define("name",{get:function(){return this._obj.name||""},set:function(e){this.__notify("name"),this._obj.name=String(e)},enumerable:!0}),DocObj._extend(DataObj),DocObj.prototype.__define({posted:{get:function(){return this._obj.posted||!1},set:function(e){this.__notify("posted"),this._obj.posted=$p.utils.fix_boolean(e)},enumerable:!0}}),doc_props_date_number(DocObj.prototype),DataProcessorObj._extend(DataObj),TaskObj._extend(CatObj),doc_props_date_number(TaskObj.prototype),BusinessProcessObj._extend(CatObj),doc_props_date_number(BusinessProcessObj.prototype),EnumObj._extend(DataObj),EnumObj.prototype.__define({order:{get:function(){return this._obj.sequence},set:function(e){this._obj.sequence=parseInt(e)},enumerable:!0},name:{get:function(){return this._obj.ref},set:function(e){this._obj.ref=String(e)},enumerable:!0},synonym:{get:function(){return this._obj.synonym||""},set:function(e){this._obj.synonym=String(e)},enumerable:!0},presentation:{get:function(){return this.synonym||this.name}},empty:{value:function(){return!this.ref||"_"==this.ref}}}),RegisterRow._extend(DataObj),RegisterRow.prototype.__define({_metadata:{get:function(){var e=this._manager.metadata();return e.fields||(e.fields={}._mixin(e.dimensions)._mixin(e.resources)._mixin(e.attributes)),e}},ref:{get:function(){return this._manager.get_ref(this)},enumerable:!0},presentation:{get:function(){return this._metadata.obj_presentation||this._metadata.synonym}}}),TabularSection.prototype.toString=function(){return"Табличная часть "+this._owner._manager.class_name+"."+this._name},TabularSection.prototype.get=function(e){return this._obj[e]?this._obj[e]._row:null},TabularSection.prototype.count=function(){return this._obj.length},TabularSection.prototype.clear=function(e){for(var t in this._obj)delete this._obj[t];return this._obj.length=0,e||this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name}),this},TabularSection.prototype.del=function(e,t){var n,a=this._obj;if("undefined"!=typeof e){if("number"==typeof e)n=e;else if(a[e.row-1]._row===e)n=e.row-1;else for(var i in a)if(a[i]._row===e){n=Number(i),delete a[i]._row;break}void 0!=n&&(a.splice(n,1),a.forEach(function(e,t){e.row=t+1}),t||this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name}),this._owner._data._modified=!0)}},TabularSection.prototype.find=function(e,t){var n=$p._find(this._obj,e,t);if(n)return n._row},TabularSection.prototype.find_rows=function(e,t){var n=this,a=t?function(e){return t.call(n,e._row)}:null;return $p._find_rows.call(n,n._obj,e,a)},TabularSection.prototype.swap=function(e,t){var n=this._obj[e];this._obj[e]=this._obj[t],this._obj[t]=n,this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name})},TabularSection.prototype.add=function(e,t){var n=new($p[this._owner._manager.obj_constructor(this._name)])(this);e||(e={});for(var a in n._metadata.fields)n[a]=e[a]||"";return n._obj.row=this._obj.push(n._obj),n._obj.__define("_row",{value:n,enumerable:!1}),t||this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name}),e=null,this._owner._data._modified=!0,n},TabularSection.prototype.each=function(e){var t=this;t._obj.forEach(function(n){return e.call(t,n._row)})},TabularSection.prototype.forEach=TabularSection.prototype.each,TabularSection.prototype.group_by=function(e,t){try{var n=this.aggregate(e,t,"SUM",!0);return this.clear(!0).load(n)}catch(e){}},TabularSection.prototype.sort=function(e){"string"==typeof e&&(e=e.split(","));var t="select * from ? order by ",n=!0;e.forEach(function(e){e=e.trim().replace(/\s{1,}/g," ").split(" "),n?n=!1:t+=", ",t+="`"+e[0]+"`",e[1]&&(t+=" "+e[1])});try{return n=$p.wsql.alasql(t,[this._obj]),this.clear(!0).load(n)}catch(e){$p.record_log(e)}},TabularSection.prototype.aggregate=function(e,t,n,a){if("string"==typeof e&&(e=e.split(",")),"string"==typeof t&&(t=t.split(",")),n||(n="sum"),!e.length&&1==t.length&&"sum"==n)return this._obj.reduce(function(e,n,a,i){return e+n[t[0]]},0);var i,s=!0;t.forEach(function(e){i?i+=", "+n+"(`"+e+"`) `"+e+"`":i="select "+n+"(`"+e+"`) `"+e+"`"}),e.forEach(function(e){i?i+=", `"+e+"`":i="select `"+e+"`"}),i+=" from ? ",e.forEach(function(e){s?(i+="group by ",s=!1):i+=", ",i+="`"+e+"`"});try{return s=$p.wsql.alasql(i,[this._obj]),a||(s=1==t.length?s.length?s[0][t[0]]:0:s.length?s[0]:{}),s}catch(e){$p.record_log(e)}},TabularSection.prototype.load=function(e){var t,n=this;return n.clear(!0),e instanceof TabularSection?t=e._obj:Array.isArray(e)&&(t=e),t&&t.forEach(function(e){n.add(e,!0)}),this._owner._data._silent||Object.getNotifier(n._owner).notify({type:"rows",tabular:n._name}),n},TabularSection.prototype.sync_grid=function(e,t){for(var n={rows:[]},a=[],i=0;i<e.getColumnCount();i++)a.push(e.getColumnId(i));if(e.clearAll(),this.find_rows(t,function(e){var t=[];a.forEach(function(n){$p.utils.is_data_obj(e[n])?t.push(e[n].presentation):t.push(e[n])}),n.rows.push({id:e.row,data:t})}),e.objBox)try{e.parse(n,"json"),e.callEvent("onGridReconstructed",[])}catch(e){}},TabularSection.prototype.toJSON=function(){return this._obj},TabularSectionRow.prototype.__define("_metadata",{get:function(){return this._owner._owner._metadata.tabular_sections[this._owner._name]},enumerable:!1}),TabularSectionRow.prototype.__define("row",{get:function(){return this._obj.row||0},enumerable:!0}),TabularSectionRow.prototype.__define("_clone",{value:function(){return new($p[this._owner._owner._manager.obj_constructor(this._owner._name)])(this._owner)._mixin(this._obj)},enumerable:!1}),TabularSectionRow.prototype._getter=DataObj.prototype._getter,TabularSectionRow.prototype._setter=function(e,t){if(this._obj[e]!=t&&(t||this._obj[e]!=$p.utils.blank.guid)){if(this._owner._owner._data._silent||Object.getNotifier(this._owner._owner).notify({type:"row",row:this,tabular:this._owner._name,name:e,oldValue:this._obj[e]}),this._metadata.fields[e].choice_type){var n;n=2==this._metadata.fields[e].choice_type.path.length?this[this._metadata.fields[e].choice_type.path[1]]:this._owner._owner[this._metadata.fields[e].choice_type.path[0]],n&&n.type&&(t=$p.utils.fetch_type(t,n.type))}DataObj.prototype.__setter.call(this,e,t),this._owner._owner._data._modified=!0}};var _rest=$p.rest=new Rest;DataManager.prototype.__define("rest_name",{get:function(){var e=this.class_name.split("."),t={cat:"Catalog",doc:"Document",ireg:"InformationRegister",areg:"AccumulationRegister",cch:"ChartOfCharacteristicTypes",cacc:"ChartOfAccounts",tsk:"Task",bp:"BusinessProcess"};return t[e[0]]+"_"+_md.syns_1с(e[1])},enumerable:!1}),DataManager.prototype.rest_tree=function(e){var t,n,a=this,i=a.metadata(),s=[];return $p.ajax.default_attr(e,!i.irest&&$p.job_prm.rest?$p.job_prm.rest_url():$p.job_prm.irest_url()),e.url+=this.rest_name+"?allowedOnly=true&$format=json&$top=1000&$select=Ref_Key,DeletionMark,Parent_Key,Description&$filter=IsFolder eq true",$p.ajax.get_ex(e.url,e).then(function(e){return JSON.parse(e.response)}).then(function(e){for(var a=0;a<e.value.length;a++)n=e.value[a],t={ref:n.Ref_Key,_deleted:n.DeletionMark,parent:n.Parent_Key,presentation:n.Description},s.push(t);return $p.iface.data_to_tree(s)})},DataManager.prototype.rest_selection=function(e){if("get_tree"==e.action)return this.rest_tree(e);var t,n,a,i,s,o,r=this,l=r.metadata(),c=[],p=[];return s=function(){var e="$select=Ref_Key,DeletionMark";return l.form&&l.form.selection?l.form.selection.fields.forEach(function(e){c.push(e)}):r instanceof DocManager?(c.push("posted"),c.push("date"),c.push("number_doc")):r instanceof TaskManager?(c.push("name as presentation"),c.push("date"),c.push("number_doc"),c.push("completed")):r instanceof BusinessProcessManager?(c.push("date"),c.push("number_doc"),c.push("started"),c.push("finished")):(l.hierarchical&&l.group_hierarchy?c.push("is_folder"):c.push("0 as is_folder"),l.main_presentation_name?c.push("name as presentation"):l.code_length?c.push("id as presentation"):c.push("'...' as presentation"),l.has_owners&&c.push("owner"),l.code_length&&c.push("id")),c.forEach(function(t){var n;if(t.indexOf(" as ")!=-1)if(n=t.split(" as ")[0].split("."),1==n.length)t=n[0];else{if("_t_"!=n[0])return;t=n[1]}"0"!=t&&(a=_md.syns_1с(t),_md.get(r.class_name,t).type.is_ref&&a.indexOf("_Key")==-1&&_md.get(r.class_name,t).type.types.length&&_md.get(r.class_name,t).type.types[0].indexOf("enm.")==-1&&(a+="_Key"),e+=","+a)}),c.push("ref"),c.push("_deleted"),e}(),$p.ajax.default_attr(e,!l.irest&&$p.job_prm.rest?$p.job_prm.rest_url():$p.job_prm.irest_url()),e.url+=(l.irest&&l.irest.selection?l.irest.selection:this.rest_name)+"?allowedOnly=true&$format=json&$top=1000&"+s,_md.get(r.class_name,"date")&&(e.date_from||e.date_till)&&(e.url+="&$filter="+_rest.filter_date("Date",e.date_from,e.date_till),o=!0),l.hierarchical&&e.parent&&(e.url+=o?" and ":"&$filter=",e.url+="Parent_Key eq guid'"+e.parent+"'",o=!0),l.has_owners&&e.owner&&(e.url+=o?" and ":"&$filter=",e.url+="Owner_Key eq guid'"+e.owner+"'",o=!0),e.filter&&(e.url+=o?" and ":"&$filter=",e.url+="$filter eq '"+e.filter+"'",o=!0),$p.ajax.get_ex(e.url,e).then(function(e){return JSON.parse(e.response)}).then(function(s){for(var o=0;o<s.value.length;o++)n=s.value[o],t={},c.forEach(function(e){var s;if("ref"==e)return void(t[e]=n.Ref_Key);if(e.indexOf(" as ")!=-1?(s=e.split(" as ")[1],e=e.split(" as ")[0].split("."),e=e[e.length-1]):s=e,a=_md.syns_1с(e),i=_md.get(r.class_name,e))if(a.indexOf("_Key")==-1&&i.type.is_ref&&i.type.types.length&&i.type.types[0].indexOf("enm.")==-1&&(a+="_Key"),i.type.date_part)t[s]=$p.moment(n[a]).format($p.moment._masks[i.type.date_part]);else if(i.type.is_ref)if(n[a]&&n[a]!=$p.utils.blank.guid){var o=_md.value_mgr(t,e,i.type,!1,n[a]);o?t[s]=o.get(n[a]).presentation:t[s]=""}else t[s]="";else t[s]=n[a]}),p.push(t);return $p.iface.data_to_grid.call(r,p,e)})},InfoRegManager.prototype.rest_slice_last=function(e){e.period||(e.period=$p.utils.date_add_day(new Date,1));var t=this,n=t.metadata(),a="Period=datetime'"+$p.moment(e.period).format($p.moment._masks.iso)+"'",i="";for(var s in n.dimensions)if(void 0!==e[s]){var o=_md.syns_1с(s),r=n.dimensions[s];o.indexOf("_Key")==-1&&r.type.is_ref&&r.type.types.length&&r.type.types[0].indexOf("enm.")==-1?(o+="_Key",i&&(i+=" and "),i+=o+" eq guid'"+e[s].ref+"'"):(i&&(i+=" and "),i+=r.type.digits?o+" eq "+$p.utils.fix_number(e[s]):r.type.date_part?o+" eq datetime'"+$p.moment(e[s]).format($p.moment._masks.iso)+"'":o+" eq '"+e[s]+"'")}return i&&(a+=",Condition='"+i+"'"),$p.ajax.default_attr(e,$p.job_prm.rest_url()),e.url+=this.rest_name+"/SliceLast(%sl)?allowedOnly=true&$format=json&$top=1000".replace("%sl",a),_rest.ajax_to_data(e,t).then(function(e){return t.load_array(e)})},DataObj.prototype.to_atom=function(e){function t(e){var t=e._metadata.fields,i=e instanceof TabularSectionRow?"\n\t<d:":"\n<d:";for(n in t){if(a=t[n],r=_md.syns_1с(n),l=e[n],l instanceof EnumObj)l=l.empty()?"":l.name;else if(l instanceof DataObj)r.indexOf("_Key")==-1&&(r+="_Key"),l=l.ref;else if(a.type.date_part)l=l.getFullYear()<1e3?"0001-01-01T00:00:00Z":$p.moment(l).format($p.moment.defaultFormatUtc);else if(void 0==l)continue;p+=i+r+">"+l+"</d:"+r+">"}}var n,a,i,s,o,r,l,c='<entry><category term="StandardODATA.%n" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"/>\t\t\t\t\n<title type="text"/><updated>%d</updated><author/><summary/><content type="application/xml">\t\t\t\t\n<m:properties xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">\t\t\t%p\t\t\t\n</m:properties></content></entry>'.replace("%n",this._manager.rest_name).replace("%d",$p.moment().format($p.moment.defaultFormatUtc)),p="\n<d:Ref_Key>"+this.ref+"</d:Ref_Key>\n<d:DeletionMark>"+this._deleted+"</d:DeletionMark>";this instanceof DocObj?(p+="\n<d:Date>"+$p.moment(this.date).format($p.moment.defaultFormatUtc)+"</d:Date>",p+="\n<d:Number>"+this.number_doc+"</d:Number>"):(this._metadata.main_presentation_name&&(p+="\n<d:Description>"+this.name+"</d:Description>"),this._metadata.code_length&&(p+="\n<d:Code>"+this.id+"</d:Code>"),this._metadata.hierarchical&&this._metadata.group_hierarchy&&(p+="\n<d:IsFolder>"+this.is_folder+"</d:IsFolder>")),t(this);for(i in this._metadata.tabular_sections)o=this._metadata.tabular_sections[i],r="StandardODATA."+this._manager.rest_name+"_"+_md.syns_1с(i)+"_RowType",s=this[i],s.count()?(p+="\n<d:"+_md.syns_1с(i)+' m:type="Collection('+r+')">',s.each(function(e){p+='\n\t<d:element m:type="'+r+'">',p+="\n\t<d:LineNumber>"+e.row+"</d:LineNumber>",t(e),p+="\n\t</d:element>"}),p+="\n</d:"+_md.syns_1с(i)+">"):p+="\n<d:"+_md.syns_1с(i)+' m:type="Collection('+r+')" />';return c.replace("%p",p)},DataManager.prototype.__define({pouch_load_array:{value:function(e,t){var n={limit:e.length+1,include_docs:!0,keys:e.map(function(e){return this.class_name+"|"+e}.bind(this))};return t&&(n.attachments=!0,n.binary=!0),this.pouch_db.allDocs(n).then(function(e){return $p.wsql.pouch.load_changes(e,{})})}},pouch_load_view:{value:function(e){var t,n=this,a=[],i={limit:1e3,include_docs:!0,startkey:n.class_name+"|",endkey:n.class_name+"|￿"};return new Promise(function(s,o){function r(l,c){c?c.rows.length?(i.startkey=c.rows[c.rows.length-1].key,i.skip=1,c.rows.forEach(function(e){t=e.doc,key=t._id.split("|"),t.ref=key[1],a.push(t)}),n.load_array(a),a.length=0,n.pouch_db.query(e,i,r)):s():l&&o(l)}n.pouch_db.query(e,i,r)})}},pouch_db:{get:function(){return this.cachable.indexOf("_remote")!=-1?$p.wsql.pouch.remote[this.cachable.replace("_remote","")]:$p.wsql.pouch.local[this.cachable]||$p.wsql.pouch.remote[this.cachable]}},pouch_find_rows:{value:function(e){var t,n,a,i,s,o,r=this,l=[],c=0,p=0,d=0,u={limit:100,include_docs:!0,startkey:r.class_name+"|",endkey:r.class_name+"|￿"};return e&&(e._top?(s=e._top,delete e._top):s=300,e._raw&&(n=e._raw,delete e._raw),e._total_count&&(i=e._total_count,delete e._total_count),e._view&&(a=e._view,delete e._view),e._key&&("des"==e._key._order_by?(u.startkey=e._key.endkey||e._key+"￿",u.endkey=e._key.startkey||e._key,u.descending=!0):(u.startkey=e._key.startkey||e._key,u.endkey=e._key.endkey||e._key+"￿")),"number"==typeof e._skip&&(p=e._skip,delete e._skip),e._attachments&&(u.attachments=!0,u.binary=!0,delete e._attachments)),i&&(o=!0,i=0,Object.keys(e).length<=1&&e._key&&e._key.hasOwnProperty("_search"))?(u.include_docs=!1,u.limit=1e5,r.pouch_db.query(a,u).then(function(t){return t.rows.forEach(function(t){if(!e._key._search||t.key[t.key.length-1].toLowerCase().indexOf(e._key._search)!=-1){if(i++,p&&(d++,d<p))return;if(s&&(c++,c>s))return;l.push(t.id)}}),delete u.startkey,delete u.endkey,u.descending&&delete u.descending,u.keys=l,u.include_docs=!0,r.pouch_db.allDocs(u)}).then(function(e){return{rows:e.rows.map(function(e){var t=e.doc;return t.ref=t._id.split("|")[1],n||(delete t._id,delete t._rev),t}),_total_count:i}})):new Promise(function(m,f){function h(a,h){h?h.rows.length?(u.startkey=h.rows[h.rows.length-1].key,u.skip=1,h.rows.forEach(function(a){t=a.doc,key=t._id.split("|"),t.ref=key[1],n||(delete t._id,delete t._rev),$p._selection.call(r,t,e)&&(o&&i++,p&&(d++,d<p)||s&&(c++,c>s)||l.push(t))}),s&&c>s&&!o?m(n?l:r.load_array(l)):_()):m(o?{rows:n?l:r.load_array(l),_total_count:i}:n?l:r.load_array(l)):a&&f(a)}function _(){a?r.pouch_db.query(a,u,h):r.pouch_db.allDocs(u,h)}_()})}},pouch_selection:{value:function(e){var t,n,a,i=this,s=e.metadata||i.metadata(),o=["ref","_deleted"],r={_raw:!0,_total_count:!0,_top:e.count||30,_skip:e.start||0},l=[];if(s.form&&s.form.selection?s.form.selection.fields.forEach(function(e){o.push(e)}):i instanceof DocManager?(o.push("posted"),o.push("date"),o.push("number_doc")):i instanceof TaskManager?(o.push("name as presentation"),o.push("date"),o.push("number_doc"),o.push("completed")):i instanceof BusinessProcessManager?(o.push("date"),o.push("number_doc"),o.push("started"),o.push("finished")):(s.hierarchical&&s.group_hierarchy?o.push("is_folder"):o.push("0 as is_folder"),s.main_presentation_name?o.push("name as presentation"):s.code_length?o.push("id as presentation"):o.push("'...' as presentation"),s.has_owners&&o.push("owner"),s.code_length&&o.push("id")),_md.get(i.class_name,"date")&&(e.date_from||e.date_till)&&(e.date_from||(e.date_from=new Date("2015-01-01")),e.date_till||(e.date_till=$p.utils.date_add_day(new Date,1)),r.date={between:[e.date_from,e.date_till]}),s.hierarchical&&e.parent&&(r.parent=e.parent),e.selection)if(Array.isArray(e.selection))e.selection.forEach(function(e){for(a in e)"_"==a[0]&&"_view"!=a&&"_key"!=a||(r[a]=e[a])});else for(a in e.selection)"_"==a[0]&&"_view"!=a&&"_key"!=a||(r[a]=e.selection[a]);return r._key&&r._key._drop_date&&r.date&&delete r.date,!e.filter||r._key&&r._key._search||(1==s.input_by_string.length?r[s.input_by_string]={like:e.filter}:(r.or=[],s.input_by_string.forEach(function(t){var n={};n[t]={like:e.filter},r.or.push(n)}))),r._key&&r._key._order_by&&(r._key._order_by=e.direction),i.pouch_find_rows(r).then(function(s){return s.hasOwnProperty("_total_count")&&s.hasOwnProperty("rows")&&(e._total_count=s._total_count,s=s.rows),s.forEach(function(e){t={},o.forEach(function(s){if("ref"==s)return void(t[s]=e[s]);if(s.indexOf(" as ")!=-1?(a=s.split(" as ")[1],s=s.split(" as ")[0].split("."),s=s[s.length-1]):a=s,n=_md.get(i.class_name,s))if(n.type.date_part)t[a]=$p.moment(e[s]).format($p.moment._masks[n.type.date_part]);else if(n.type.is_ref)if(e[s]&&e[s]!=$p.utils.blank.guid){var o=_md.value_mgr(t,s,n.type,!1,e[s]);o?t[a]=o.get(e[s]).presentation:t[a]=""}else t[a]="";else"number"==typeof e[s]&&n.type.fraction_figits?t[a]=e[s].toFixed(n.type.fraction_figits):t[a]=e[s]}),l.push(t)}),$p.iface.data_to_grid.call(i,l,e)}).catch($p.record_log)}},pouch_tree:{value:function(e){return this.pouch_find_rows({is_folder:!0,_raw:!0,_top:e.count||300,_skip:e.start||0}).then(function(e){return e.sort(function(e,t){return e.parent==$p.utils.blank.guid&&t.parent!=$p.utils.blank.guid?-1:t.parent==$p.utils.blank.guid&&e.parent!=$p.utils.blank.guid?1:e.name<t.name?-1:e.name>t.name?1:0}),e.map(function(e){return{ref:e.ref,parent:e.parent,presentation:e.name}})}).then($p.iface.data_to_tree)}},save_attachment:{value:function(e,t,n,a){a||(a={type:"text/plain"}),n instanceof Blob||a.indexOf("text")!=-1||(n=new Blob([n],{type:a}));var i,s=this.pouch_db;return e=this.class_name+"|"+$p.utils.fix_guid(e),s.get(e).then(function(e){e&&(i=e._rev)}).catch(function(e){if(404!=e.status)throw e}).then(function(){return s.putAttachment(e,t,i,n,a)})}},get_attachment:{value:function(e,t){return this.pouch_db.getAttachment(this.class_name+"|"+$p.utils.fix_guid(e),t)}},delete_attachment:{value:function(e,t){var n,a=this.pouch_db;return e=this.class_name+"|"+$p.utils.fix_guid(e),a.get(e).then(function(e){e&&(n=e._rev)}).catch(function(e){if(404!=e.status)throw e}).then(function(){return a.removeAttachment(e,t,n)})}}}),DataObj.prototype.__define({new_number_doc:{value:function(e){if(this._metadata.code_length){e||(e=($p.current_acl&&$p.current_acl.prefix||"")+(this.organization&&this.organization.prefix?this.organization.prefix:$p.wsql.get_user_param("zone")+"-"));var t=this,n="",a=this.date instanceof Date?this.date.getFullYear():0,i=this._metadata.code_length-e.length;return"ram"==this._manager.cachable?Promise.resolve(this.new_cat_id(e)):t._manager.pouch_db.query("doc/number_doc",{limit:1,include_docs:!1,startkey:[t._manager.class_name,a,e+"￿"],endkey:[t._manager.class_name,a,e],descending:!0}).then(function(a){if(a.rows.length){for(var s=a.rows[0].key[2],o=s.length-1;o>0&&!isNaN(parseInt(s[o]));o--)n=s[o]+n;n=(parseInt(n||0)+1).toFixed(0)}else n="1";for(;n.length<i;)n="0"+n;return t instanceof DocObj||t instanceof TaskObj||t instanceof BusinessProcessObj?t.number_doc=e+n:t.id=e+n,t})}}},new_cat_id:{value:function(e){e||(e=($p.current_acl&&$p.current_acl.prefix||"")+(this.organization&&this.organization.prefix?this.organization.prefix:$p.wsql.get_user_param("zone")+"-"));var t=this._metadata.code_length-e.length,n=this instanceof DocObj||this instanceof TaskObj||this instanceof BusinessProcessObj?"number_doc":"id",a="",i=$p.wsql.alasql("select top 1 "+n+" as id from ? where "+n+" like '"+e+"%' order by "+n+" desc",[this._manager.alatable]);if(i.length){for(var s=i[0].id||"",o=s.length-1;o>0&&!isNaN(parseInt(s[o]));o--)a=s[o]+a;a=(parseInt(a||0)+1).toFixed(0)}else a="1";for(;a.length<t;)a="0"+a;return this[n]=e+a,this}}}),$p.iface.OBtnAuthSync=function(){function e(){$p.wsql.pouch.authorized?dhtmlx.confirm({title:$p.msg.log_out_title,text:$p.msg.logged_in+$p.wsql.pouch.authorized+$p.msg.log_out_break,cancel:$p.msg.cancel,callback:function(e){e&&$p.wsql.pouch.log_out()}}):$p.iface.frm_auth({modal_dialog:!0})}function t(e){e&&a?clearTimeout(a):i.forEach(function(t){e?t.buttons.sync.innerHTML='<i class="fa fa-refresh fa-spin md-fa-lg"></i>':$p.wsql.pouch.authorized?t.buttons.sync.innerHTML='<i class="fa fa-refresh md-fa-lg"></i>':t.buttons.sync.innerHTML='<i class="fa fa-ban md-fa-lg"></i>'}),a=e?setTimeout(t,3e3):0}function n(){i.forEach(function(e){$p.wsql.pouch.authorized?(e.buttons.auth.title="Отключиться от сервера",e.buttons.auth.innerHTML='<span class="span_user">'+$p.wsql.pouch.authorized+"</span>",e.buttons.sync.title="Синхронизация выполняется...",e.buttons.sync.innerHTML='<i class="fa fa-refresh md-fa-lg"></i>'):(e.buttons.auth.title="Войти на сервер и включить синхронизацию данных",e.buttons.auth.innerHTML=' <i class="fa fa-sign-in md-fa-lg"></i><span class="span_user">Вход...</span>',e.buttons.sync.title="Синхронизация не выполняется - пользователь не авторизован на сервере",e.buttons.sync.innerHTML='<i class="fa fa-ban md-fa-lg"></i>')})}var a,i=[];this.bind=function(t){return t.buttons.auth.onclick=e,t.buttons.sync.onclick=null,i.push(t),setTimeout(n),t},$p.on({pouch_load_data_start:function(e){$p.iface.sync||$p.iface.wnd_sync(),$p.iface.sync.create($p.eve.stepper),$p.eve.stepper.frm_sync.setItemValue("text_bottom","Читаем справочники"),e.hasOwnProperty("local_rows")&&e.local_rows<10?($p.eve.stepper.wnd_sync.setText("Первый запуск - подготовка данных"),$p.eve.stepper.frm_sync.setItemValue("text_processed","Загрузка начального образа")):($p.eve.stepper.wnd_sync.setText("Загрузка данных из IndexedDB"),$p.eve.stepper.frm_sync.setItemValue("text_processed","Извлечение начального образа")),t(!0)},pouch_load_data_page:function(e){if(t(!0),$p.eve.stepper.wnd_sync){var n=e.docs_written||e.page*e.limit;$p.eve.stepper.frm_sync.setItemValue("text_current","Обработано элементов: "+n+" из "+e.total_rows),$p.eve.stepper.frm_sync.setItemValue("text_bottom","Текущий запрос: "+e.page+" ("+(100*n/e.total_rows).toFixed(0)+"%)")}},pouch_change:function(e,n){t(!0)},pouch_load_data_loaded:function(e){$p.eve.stepper.wnd_sync&&(e.docs_written?$p.iface.sync.close():$p.iface.sync.close())},pouch_load_data_error:function(e){t(),$p.eve.stepper.wnd_sync&&$p.iface.sync.close()},log_in:function(e){n()},log_out:function(){n()}})};var eXcell_proto=new eXcell;eXcell_proto.input_keydown=function(e,t){function n(e){t.source.on_select&&t.source.on_select.call(t.source,e)}if(8===e.keyCode||46===e.keyCode)t.setValue(""),t.grid.editStop(),t.source.on_select&&t.source.on_select.call(t.source,"");else if(9===e.keyCode||13===e.keyCode)t.grid.editStop();else if(115===e.keyCode)t.cell.firstChild.childNodes[1].onclick(e);else if(113===e.keyCode)if(t.source.tabular_section){if(t.mgr=_md.value_mgr(t.source.row,t.source.col,t.source.row._metadata.fields[t.source.col].type),t.mgr){var a=t.source.row[t.source.col];t.mgr.form_obj(t.source.wnd,{o:a,on_select:n})}}else if(1==t.fpath.length&&(t.mgr=_md.value_mgr(t.source.o._obj,t.fpath[0],t.source.o._metadata.fields[t.fpath[0]].type),t.mgr)){var a=t.source.o[t.fpath[0]];t.mgr.form_obj(t.source.wnd,{o:a,on_select:n})}return $p.iface.cancel_bubble(e)},eXcell_ocombo.prototype=eXcell_proto,window.eXcell_ocombo=eXcell_ocombo,window.eXcell_ref=eXcell_ocombo,window.eXcell_refc=eXcell_ocombo,eXcell_pwd.prototype=eXcell_proto,window.eXcell_pwd=eXcell_pwd,dhtmlXCalendarObject.prototype._dateToStr=function(e,t){return e instanceof Date&&e.getFullYear()<1e3?"":window.dhx4.date2str(e,t||this._dateFormat,this._dateStrings())},eXcell_dhxCalendar.prototype.edit=function(){var e=this.grid.getPosition(this.cell);this.grid._grid_calendarA._show(!1,!1),this.grid._grid_calendarA.setPosition(e[0],e[1]+this.cell.offsetHeight),this.grid._grid_calendarA._last_operation_calendar=!1,this.grid.callEvent("onCalendarShow",[this.grid._grid_calendarA,this.cell.parentNode.idd,this.cell._cellIndex]),this.cell._cediton=!0,this.val=this.cell.val,this.val instanceof Date&&this.val.getFullYear()<1e3&&(this.val=new Date),this._val=this.cell.innerHTML;var t=this.grid._grid_calendarA.draw;this.grid._grid_calendarA.draw=function(){},this.grid._grid_calendarA.setDateFormat(this.grid._dtmask||"%d.%m.%Y"),this.grid._grid_calendarA.setDate(this.val||new Date),this.grid._grid_calendarA.draw=t},eXcell_dhxCalendar.prototype.setCValue=function(e,t){this.cell.innerHTML=e instanceof Date?this.grid._grid_calendarA._dateToStr(e):e,this.grid._grid_calendarA.getFormatedDate(this.grid._dtmask||"%d/%m/%Y",e).toString(),this.grid.callEvent("onCellChanged",[this.cell.parentNode.idd,this.cell._cellIndex,arguments.length>1?t:e])},function(){function e(e,t,n,a){if(n.indexOf("odata/standard.odata")!=-1||n.indexOf("/hs/rest")!=-1){var i,s;$p.ajax.authorized?(i=$p.ajax.username,s=$p.aes.Ctr.decrypt($p.ajax.password)):$p.job_prm.guest_name?(i=$p.job_prm.guest_name,s=$p.aes.Ctr.decrypt($p.job_prm.guest_pwd)):(i=$p.wsql.get_user_param("user_name"),s=$p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd"))),e.open(t,n,a,i,s),e.withCredentials=!0,e.setRequestHeader("Authorization","Basic "+btoa(unescape(encodeURIComponent(i+":"+s)))); +}else e.open(t,n,a)}dhx4.ajax._call=function(t,n,a,i,s,o,r){var l=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),c=null!=navigator.userAgent.match(/AppleWebKit/)&&null!=navigator.userAgent.match(/Qt/)&&null!=navigator.userAgent.match(/Safari/);if(1==i&&(l.onreadystatechange=function(){if(4==l.readyState||1==c&&3==l.readyState){if((200!=l.status||""==l.responseText)&&!dhx4.callEvent("onAjaxError",[{xmlDoc:l,filePath:n,async:i}]))return;window.setTimeout(function(){"function"==typeof s&&s.apply(window,[{xmlDoc:l,filePath:n,async:i}]),null!=o&&("undefined"!=typeof o.postData?dhx4.ajax.postLong(o.url,o.postData,s):dhx4.ajax.getLong(o.url,s)),s=null,l=null},1)}}),"GET"==t&&(n+=this._dhxr(n)),l.open(t,n,i),e(l,t,n,i),null!=r)for(var p in r)l.setRequestHeader(p,r[p]);else"POST"==t||"PUT"==t||"DELETE"==t?l.setRequestHeader("Content-Type","application/x-www-form-urlencoded"):"GET"==t&&(a=null);return l.setRequestHeader("X-Requested-With","XMLHttpRequest"),l.send(a),1!=i&&(4==l.readyState||1==c&&3==l.readyState)&&(200==l.status&&""!=l.responseText||dhx4.callEvent("onAjaxError",[{xmlDoc:l,filePath:n,async:i}])),{xmlDoc:l,filePath:n,async:i}},dhtmlx.ajax.prototype.send=function(t,n,a){var i=this.getXHR();if("function"==typeof a&&(a=[a]),"object"==typeof n){var s=[];for(var o in n){var r=n[o];null!==r&&r!==dhtmlx.undefined||(r=""),s.push(o+"="+encodeURIComponent(r))}n=s.join("&")}n&&!this.post&&(t=t+(t.indexOf("?")!=-1?"&":"?")+n,n=null),e(i,this.post?"POST":"GET",t,!this._sync),this.post&&i.setRequestHeader("Content-type","application/x-www-form-urlencoded");var l=this;return i.onreadystatechange=function(){if(!i.readyState||4==i.readyState){if(a&&l)for(var e=0;e<a.length;e++)a[e]&&a[e].call(l.master||l,i.responseText,i.responseXML,i);l.master=null,a=l=null}},i.send(n||null),i}}(),dhtmlXCellObject.prototype.is_visible=function(){var e=this.cell.getBoundingClientRect();return e.right>0&&e.bottom>0},$p.iface.data_to_grid=function(e,t){function n(e){var t;return t=e.hasOwnProperty("posted")?e.posted?"cell_doc_posted":"cell_doc":e.is_folder?"cell_ref_folder":"cell_ref_elm",e._deleted&&(t+="_deleted"),t}function a(e){return e instanceof Date?e.getHours()||e.getMinutes()?$p.moment(e).format($p.moment._masks.date_time):$p.moment(e).format($p.moment._masks.date):"number"==typeof e?e:$p.iface.normalize_xml(e||"")}if(this.data_to_grid)return this.data_to_grid(e,t);var i="<?xml version='1.0' encoding='UTF-8'?><rows total_count='%1' pos='%2' set_parent='%3'>".replace("%1",t._total_count||e.length).replace("%2",t.start).replace("%3",t.set_parent||""),s=this.caption_flds(t);return i+=s.head,e.forEach(function(e){i+='<row id="'+e.ref+'"><cell class="'+n(e)+'">'+a(e[s.acols[0].id])+"</cell>";for(var t=1;t<s.acols.length;t++)i+="<cell>"+a(e[s.acols[t].id])+"</cell>";i+="</row>"}),i+"</rows>"},$p.iface.data_to_tree=function(e){function t(n,a){var i={id:a.ref,text:a.presentation,items:[]};n.push(i),$p._find_rows(e,{parent:a.ref},function(e){t(i.items,e)}),i.items.length||delete i.items}var n=[{id:$p.utils.blank.guid,text:"..."}];return $p._find_rows(e,{parent:$p.utils.blank.guid},function(e){t(n,e)}),n},$p.iface.ODropdownList=ODropdownList,dhtmlXCellObject.prototype.attachDynTree=function(e,t,n){this.setCollapsedText&&this.setCollapsedText("Дерево"),t||(t={is_folder:!0});var a=this.attachTreeView();return a.__define({filter:{get:function(){},set:function(e){t=e},enumerable:!1,configurable:!1}}),setTimeout(function(){e.sync_grid({action:"get_tree",filter:t},a).then(function(e){n&&n(e)})}),a},OCombo._extend(dhtmlXCombo),$p.iface.OCombo=OCombo,$p.iface.select_from_list=function(e,t){return new Promise(function(n,a){function i(e){"cancel"!=e&&(s=c.getSelectedRowId()),l.close()}Array.isArray(e)&&e.length?1==e.length&&n(e[0]):n(void 0);var s,o,r={name:"wnd_select_from_list",wnd:{id:"wnd_select_from_list",width:300,height:300,modal:!0,center:!0,caption:$p.msg.select_from_list,allow_close:!0,on_close:function(){return s&&n(e[parseInt(s)-1]),!0}}},l=$p.iface.dat_blank(null,r.wnd),c=l.attachGrid(),p=l.attachToolbar({items:[{id:"select",type:"button",text:$p.msg.select_from_list},{id:"cancel",type:"button",text:"Отмена"}],onClick:i});c.setIconsPath(dhtmlx.image_path),c.setImagePath(dhtmlx.image_path),c.setHeader($p.msg.value),c.setColTypes("ro"),c.enableAutoWidth(!0,1200,600),c.attachEvent("onRowDblClicked",i),c.enableMultiselect(!!t),c.setNoHeader(!0),c.init(),p.addSpacer("select"),l.hideHeader(),l.cell.offsetParent.querySelector(".dhxwin_brd").style.border="none",e.forEach(function(e,t){var n;n="object"==typeof e?e.presentation||e.text||e.toString():e.toString(),c.addRow(1+t,n),e.selected&&(o=1+t)}),o&&c.selectRowById(o)})},$p.iface.ODateRangePicker=ODateRangePicker,dhtmlXCellObject.prototype.attachHeadFields=function(e){function t(e){if(a)u.entBox&&!u.entBox.parentElement?setTimeout(u.destructor):e.forEach(function(e){"unload"==e.type?d&&d.close?d.close():u.destructor():u.forEachRow(function(t){t==e.name&&u.cells(t,1).setValue(a[e.name])})});else{var i=[];e.forEach(function(e){i.indexOf[e.object]==-1&&(i.push(e.object),Object.unobserve(e.object,t),c&&c instanceof TabularSection&&Object.unobserve(e.object,n))}),i=null}}function n(t){var n;t.forEach(function(t){!n&&u.clearAll&&l==t.tabular&&(n=!0,u.clearAll(),u.parse(o.get_property_grid_xml(i,a,{title:e.ts_title,ts:l,selection:r,metadata:s}),function(){},"xml"))})}var a,i,s,o,r,l,c,p,d=this,u=d.attachGrid(),m=u.destructor;return new dhtmlXPropertyGrid(u),u.setInitWidthsP("40,60"),u.setDateFormat("%d.%m.%Y %H:%i"),u.init(),u.setSizes(),u.attachEvent("onPropertyChanged",function(e,t,n){if(e||u&&u.getSelectedRowId())return p.on_select(t)}),u.attachEvent("onCheckbox",function(e,t,n){return void 0!=a[e]?p.on_select(n,{obj:a,field:e}):e.split("|").length>1?p.on_select(n,u.get_cell_field(e)):void 0}),u.attachEvent("onKeyPress",function(e,t,n){switch(e){case 13:case 9:u.editStop&&u.editStop();break;case 46:}}),e.read_only&&u.setEditable(!1),u.__define({selection:{get:function(){return r},set:function(e){r=e,this.reload()}},reload:{value:function(){n([{tabular:l}])}},get_cell_field:{value:function(e){if(a){var t={row_id:e||u.getSelectedRowId()},n=t.row_id.split("|");if(n.length<2)return{obj:a,field:n[0]}._mixin(p);var i;return r?a[n[0]].find_rows(r,function(e){if(e.property==n[1]||e.param==n[1]||e.Свойство==n[1]||e.Параметр==n[1])return i=e,!1}):i=a[n[0]].find(n[1]),i?(t.obj=i,i["Значение"]?(t.field="Значение",t.property=i.Свойство||i.Параметр):(t.field="value",t.property=i.property||i.param),t._mixin(p)):void 0}},enumerable:!1},_obj:{get:function(){return a}},_owner_cell:{get:function(){return d}},destructor:{value:function(){a&&Object.unobserve(a,t),c&&c instanceof TabularSection&&Object.unobserve(c,n),a=null,c=null,s=null,o=null,p=null,m.call(u)}},attach:{value:function(e){a&&Object.unobserve(a,t),c&&c instanceof TabularSection&&Object.unobserve(a,n),e.oxml&&(i=e.oxml),e.selection&&(r=e.selection),a=e.obj,s=e.metadata||a._metadata.fields,o=a._manager,l=e.ts||"",c=l?a[l]:a.extra_fields||a["ДополнительныеРеквизиты"],c&&!l&&(l=a.extra_fields?"extra_fields":"ДополнительныеРеквизиты"),p={on_select:function(e,t){if(t||(t=u.get_cell_field()),t){var n=o.handle_event(a,"value_change",{field:t.field,value:e,tabular_section:t.row_id?l:"",grid:u,cell:u.cells(t.row_id||t.field,1),wnd:p.pwnd});return"boolean"!=typeof n&&(t.obj[t.field]=e,n=!0),n}},pwnd:e.pwnd||d},Object.observe(a,t,["update","unload"]),c&&c instanceof TabularSection&&Object.observe(a,n,["row","rows"]),l&&!e.ts_title&&(e.ts_title=a._metadata.tabular_sections[l].synonym),n([{tabular:l}])}}}),e&&u.attach(e),u},dhtmlXGridObject.prototype.get_cell_value=function(){var e=this.get_cell_field();if(e&&e.obj)return e.obj[e.field]},dhtmlXCellObject.prototype.attachTabular=function(e){function t(e){var t=f.getSelectedRowId();return t&&!isNaN(Number(t))?Number(t)-1:void(e||$p.msg.show_msg({type:"alert-warning",text:$p.msg.no_selected_row.replace("%1",o._metadata.tabular_sections[r].synonym||r),title:(o._metadata.obj_presentation||o._metadata.synonym)+": "+o.presentation}))}function n(e,t,n,a,i){if(2!=e||a==i)return!0;var s=f.get_cell_field(),l=c.handle_event(o,"value_change",{field:s.field,value:a,tabular_section:r,grid:f,row:s.obj,cell:t&&n?f.cells(t,n):f.getSelectedCellIndex()>=0?f.cells():null,wnd:g.pwnd});return"boolean"!=typeof l&&(s.obj[s.field]=a,l=!0),l}function a(e){f.clearAll&&e.some(function(e){if("rows"==e.type&&e.tabular==r)return l.sync_grid(f,m),!0})}function i(e){if(e.length>20)try{l.sync_grid(f,m)}catch(e){}else e.forEach(function(e){r==e.tabular&&(e.row&&f.getSelectedRowId()==e.row.row?void 0!=f.getColIndexById(e.name)&&f.cells(e.row.row,f.getColIndexById(e.name)).setCValue($p.utils.is_data_obj(e.row[e.name])?e.row[e.name].presentation:e.row[e.name]):l.sync_grid(f,m))})}function s(e){if(e.clipboardData.types.indexOf("text/plain")!=-1)try{$p.eve.callEvent("tabular_paste",[{obj:o,grid:f,tsname:r,e:e,data:e.clipboardData.getData("text/plain")}])}catch(e){return}}var o=e.obj,r=e.ts,l=o[r],c=o._manager,p=e.metadata||c.metadata().tabular_sections[r].fields,d=this,u=e.ts_captions||{},m=e.selection;if(e.ts_captions||_md.ts_captions(c.class_name,r,u)){var f=this.attachGrid(),h=this.attachToolbar(),_=f.destructor,g={on_select:function(e){n(2,null,null,e)},pwnd:e.pwnd||d,is_tabular:!0};return f.setDateFormat("%d.%m.%Y %H:%i"),f.enableAccessKeyMap(),f._add_row=function(){if(!e.read_only){var t;if(m)for(var n in m)p[n]&&("object"!=typeof m[n]||$p.is_data_obj(m[n]))&&(t||(t={}),t[n]=m[n]);var a=l.add(t);if(c.handle_event(o,"add_row",{tabular_section:r,grid:f,row:a,wnd:g.pwnd})===!1)return;setTimeout(function(){f.selectRowById(a.row)},100)}},f._del_row=function(){if(!e.read_only){var n=t();if(void 0!=n){if(c.handle_event(o,"del_row",{tabular_section:r,grid:f,row:n,wnd:g.pwnd})===!1)return;l.del(n),setTimeout(function(){f.selectRowById(n<l.count()?n+1:n)},100)}}},h.setIconsPath(dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()),h.loadStruct(e.toolbar_struct||$p.injected_data["toolbar_add_del.xml"],function(){this.attachEvent("onclick",function(e){switch(e){case"btn_add":f._add_row();break;case"btn_delete":f._del_row()}})}),f.setIconsPath(dhtmlx.image_path),f.setImagePath(dhtmlx.image_path),f.setHeader(u.headers),u.min_widths&&f.setInitWidths(u.widths),u.min_widths&&f.setColumnMinWidth(u.min_widths),u.aligns&&f.setColAlign(u.aligns),f.setColSorting(u.sortings),f.setColTypes(u.types),f.setColumnIds(u.fields.join(",")),f.enableAutoWidth(!0,1200,600),f.enableEditTabOnly(!0),f.init(),e.read_only&&(f.setEditable(!1),h.forEachItem(function(e){["btn_add","btn_delete"].indexOf(e)!=-1&&h.disableItem(e)})),f.__define({selection:{get:function(){return m},set:function(e){m=e,a([{tabular:r,type:"rows"}])}},destructor:{value:function(){o&&(Object.unobserve(o,i),Object.unobserve(o,a)),o=null,l=null,p=null,c=null,g=null,d.detachToolbar(),f.entBox.removeEventListener("paste",s),_.call(f)}},get_cell_field:{value:function(){if(l){var e,n,a=t(!0),i=f.getSelectedCellIndex();if(void 0!=a?e=l.get(a):f._last&&(e=l.get(f._last.row)),i>=0?n=f.getColumnId(i):f._last&&(n=f.getColumnId(f._last.cindex)),e&&n)return{obj:e,field:n,metadata:p[n]}._mixin(g)}}},refresh_row:{value:function(e){f.selectRowById(e.row),f.forEachCell(e.row,function(t,n){var a=e[f.getColumnId(n)];t.setCValue($p.utils.is_data_obj(a)?a.presentation:a)})}}}),f.attachEvent("onEditCell",n),f.attachEvent("onRowSelect",function(e,t){l&&(f._last={row:e-1,cindex:t})}),a([{tabular:r,type:"rows"}]),Object.observe(o,i,["row"]),Object.observe(o,a,["rows"]),f.entBox.addEventListener("paste",s),f}},$p.iface.Toolbar_filter=function(e){function t(){i&&clearTimeout(i),i=setTimeout(function(){i&&a.call_event()},500)}function n(e,t){"min"==t?a.сalendar.setSensitiveRange(e.value,null):a.сalendar.setSensitiveRange(null,e.value)}var a=this,i=0,s="desktop"==$p.job_prm.device_type?300:120,o={};e.pos||(e.pos=6),a.__define({custom_selection:{get:function(){return o},enumerable:!1,configurable:!1},toolbar:{get:function(){return e.toolbar},enumerable:!1,configurable:!1},call_event:{value:function(){i&&(clearTimeout(i),i=0),e.onchange.call(a,a.get_filter())}}}),a.toolbar.addText("div_filter",e.pos,""),a.div=a.toolbar.objPull[a.toolbar.idPrefix+"div_filter"],e.pos++,(e.manager instanceof DocManager||e.manager instanceof BusinessProcessManager||e.manager instanceof TaskManager||e.period)&&(s="desktop"==$p.job_prm.device_type?180:120,a.toolbar.addInput("input_date_from",e.pos,"","desktop"==$p.job_prm.device_type?80:72),e.pos++,a.toolbar.addText("lbl_date_till",e.pos,"-"),e.pos++,a.toolbar.addInput("input_date_till",e.pos,"","desktop"==$p.job_prm.device_type?80:72),e.pos++,a.input_date_from=a.toolbar.getInput("input_date_from"),a.input_date_from.onclick=function(){n(a.input_date_till,"max")},a.input_date_till=a.toolbar.getInput("input_date_till"),a.input_date_till.onclick=function(){n(a.input_date_from,"min")},a.сalendar=new dhtmlXCalendarObject([a.input_date_from,a.input_date_till]),a.сalendar.attachEvent("onclick",a.call_event),e.date_from||(e.date_from=new Date((new Date).getFullYear().toFixed()+"-01-01")),e.date_till||(e.date_till=$p.utils.date_add_day(new Date,1)),a.input_date_from.value=$p.moment(e.date_from).format("L"),a.input_date_till.value=$p.moment(e.date_till).format("L"),"doc"!=e.manager.cachable||e.custom_selection||(o._view={get value(){return"doc/by_date"}},o._key={get value(){var t=a.get_filter(!0);return{startkey:[e.manager.class_name,t.date_from.getFullYear(),t.date_from.getMonth()+1,t.date_from.getDate()],endkey:[e.manager.class_name,t.date_till.getFullYear(),t.date_till.getMonth()+1,t.date_till.getDate()],_drop_date:!0,_order_by:!0,_search:t.filter.toLowerCase()}}})),e.hide_filter?a.input_date_till?a.toolbar.addSpacer("input_date_till"):a.toolbar.addSpacer("div_filter"):(a.toolbar.addSeparator("filter_sep",e.pos),e.pos++,a.toolbar.addInput("input_filter",e.pos,"",s),a.input_filter=a.toolbar.getInput("input_filter"),a.input_filter.onchange=a.call_event,a.input_filter.onclick=function(){var e=a.input_filter.value;setTimeout(function(){e!=a.input_filter.value&&a.call_event()})},a.input_filter.onkeydown=t,a.input_filter.type="search",a.input_filter.setAttribute("placeholder","Фильтр"),a.toolbar.addSpacer("input_filter"))},$p.iface.Toolbar_filter.prototype.__define({get_filter:{value:function(e){var t,n,a={date_from:this.input_date_from?$p.utils.date_add_day(dhx4.str2date(this.input_date_from.value),0,!0):"",date_till:this.input_date_till?$p.utils.date_add_day(dhx4.str2date(this.input_date_till.value),1,!0):"",filter:this.input_filter?this.input_filter.value:""};if(!e)for(t in this.custom_selection)a.selection||(a.selection=[]),n={},n[t]=this.custom_selection[t].value,a.selection.push(n);return a}},add_filter:{value:function(e){var t=this.toolbar.getPosition("input_filter")-2,n=dhx4.newId(),a=(this.toolbar.getWidth("input_filter")/2).round(0);this.toolbar.setWidth("input_filter",a),this.toolbar.addText("lbl_"+n,t,e.text||""),t++,this.toolbar.addInput("input_"+n,t,"",a),this.custom_selection[e.name]=this.toolbar.getInput("input_"+n)}}}),$p.iface.dat_blank=function(e,t){t||(t={});var n,a=(e||$p.iface.w).createWindow({id:dhx4.newId(),left:t.left||700,top:t.top||20,width:t.width||220,height:t.height||300,move:!0,park:!t.allow_close,center:!!t.center,resize:!0,caption:t.caption||"Tools"}),i={x:(e||$p.iface.w).vp.clientWidth,y:(e||$p.iface.w).vp.clientHeight};return a.getPosition()[0]+a.getDimension()[0]>i.x?(i.x=i.x-a.getDimension()[0],n=!0):i.x=a.getPosition()[0],a.getPosition()[1]+a.getDimension()[1]>i.y?(i.y=i.y-a.getDimension()[1],n=!0):i.y=a.getPosition()[1],n&&(i.x<0||i.y<0?a.maximize():a.setPosition(i.x,i.y)),e=null,t.hasOwnProperty("allow_minmax")&&!t.allow_minmax&&a.button("minmax").hide(),t.allow_close?a.button("park").hide():a.button("close").hide(),a.attachEvent("onClose",function(){var e="function"!=typeof t.on_close||t.on_close(a);if(e)return t.pwnd_modal&&t.pwnd&&t.pwnd.setModal&&t.pwnd.setModal(1),e}),a.setIconCss("without_icon"),a.cell.parentNode.children[1].classList.add("dat_gui"),$p.iface.bind_help(a,t.help_path),a.elmnts={grids:{}},a.wnd_options=function(e){var t=a.getPosition(),n=a.getDimension(),i=a.isParked();e.left=t[0],e.top=t[1],e.width=n[0],e.parked=i,i||(e.height=n[1])},a.bottom_toolbar=function(e){var t={wrapper:a.cell,width:"100%",height:"28px",bottom:"0px",left:"0px",name:"tb_bottom",buttons:[{name:"btn_cancel",text:"Отмена",title:"Закрыть без сохранения",width:"60px",float:"right"},{name:"btn_ok",b:"Ок",title:"Применить изменения",width:"30px",float:"right"}],onclick:function(e){return!1}}._mixin(e),n=new OTooolBar(t),i=a.attachStatusBar({height:12});return i.style.zIndex=-1e3,i.firstChild.style.backgroundColor="transparent",i.firstChild.style.border="none",n},t.modal&&(t.pwnd&&t.pwnd.setModal&&(t.pwnd_modal=t.pwnd.isModal(),t.pwnd.setModal(0)),a.setModal(1)),a},$p.iface.pgrid_on_select=function(e){if(void 0!==e){var t=this.grid instanceof dhtmlXGridObject?this.grid:this,n=t.getUserData("","source"),a=t.getSelectedRowId();if(void 0!=n.o[a])"number"==typeof n.o[a]?n.o[a]=$p.utils.fix_number(e,!0):n.o[a]=e;else if(a.indexOf("fprms")>-1){var i=$p._find(n.o.fprms,a.split("|")[1]);i.value=e}t.cells().setValue($p.utils.is_data_obj(e)?e.presentation:e||""),n.grid_on_change&&n.grid_on_change.call(t,a,e)}},$p.iface.pgrid_on_change=function(e,t,n){e&&$p.iface.pgrid_on_select.call(this,t)},$p.iface.pgrid_on_checkbox=function(e,t,n){var a=this.grid instanceof dhtmlXGridObject?this.grid:this,i=a.getUserData("","source");void 0!=i.o[e]&&(i.o[e]=n),i.grid_on_change&&i.grid_on_change(e,n)},$p.iface.frm_auth=function(e,t,n){function a(n,a){$p.ajax.username=n,$p.ajax.password=$p.aes.Ctr.encrypt(a),n?($p.wsql.get_user_param("user_name")!=n&&$p.wsql.set_user_param("user_name",n),$p.wsql.pouch.log_in(n,a).then(function(){$p.wsql.get_user_param("enable_save_pwd")?$p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd"))!=a&&$p.wsql.set_user_param("user_pwd",$p.aes.Ctr.encrypt(a)):""!=$p.wsql.get_user_param("user_pwd")&&$p.wsql.set_user_param("user_pwd",""),$p.eve.logged_in=!0,e.modal_dialog?s.close():t&&t()}).catch(function(e){l=!0,o.onerror(e)}).then(function(){$p.iface.sync&&$p.iface.sync.close(),s&&s.progressOff&&(s.progressOff(),!l&&e.hide_header&&s.hideHeader()),$p.iface.cell_tree&&!l&&$p.iface.cell_tree.expand()})):this.validate()}function i(e){if(l=!1,this.resetValidateCss(),"guest"==this.getCheckedValue("type")){var t=this.getItemValue("guest"),n="";$p.job_prm.guests&&$p.job_prm.guests.length&&$p.job_prm.guests.some(function(e){if(e.username==t)return n=$p.aes.Ctr.decrypt(e.password),!0}),a.call(this,t,n)}else"auth"==this.getCheckedValue("type")&&a.call(this,this.getItemValue("login"),this.getItemValue("password"))}e||(e={});var s,o,r,l;e.modal_dialog?(e.options||(e.options={name:"frm_auth",caption:"Вход на сервер",width:360,height:300,center:!0,allow_close:!0,allow_minmax:!0,modal:!0}),s=$p.iface.dat_blank(e._dxw,e.options),s.attachEvent("onClose",function(e){return l?n&&n(err):t&&t(),!0}),o=s.attachForm()):(s=e.cell||$p.iface.docs,o=$p.iface.auth=s.attachForm(),$p.msg.show_msg($p.msg.init_login,s)),o.loadStruct($p.injected_data["form_auth.xml"],function(){var t;if($p.job_prm.guests&&$p.job_prm.guests.length){var n=$p.job_prm.guests.map(function(e){var n={text:e.username,value:e.username};return $p.wsql.get_user_param("user_name")==e.username&&(n.selected=!0,t=e.username),n});t||(n[0].selected=!0,t=n[0].value),o.reloadOptions("guest",n)}$p.wsql.get_user_param("user_name")&&$p.wsql.get_user_param("user_name")!=t&&(o.setItemValue("login",$p.wsql.get_user_param("user_name")),o.setItemValue("type","auth"),$p.wsql.get_user_param("enable_save_pwd")&&$p.wsql.get_user_param("user_pwd")&&o.setItemValue("password",$p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd")))),e.modal_dialog||((r=((s.getWidth?s.getWidth():s.cell.offsetWidth)-500)/2)>=10?o.cont.style.paddingLeft=r.toFixed()+"px":o.cont.style.paddingLeft="20px"),setTimeout(function(){dhx4.callEvent("on_draw_auth",[o]),($p.wsql.get_user_param("autologin")||e.try_auto)&&(t||$p.wsql.get_user_param("user_name")&&$p.wsql.get_user_param("user_pwd"))&&i.call(o)})}),o.attachEvent("onButtonClick",i),o.attachEvent("onKeyDown",function(e,t,n,a){13==t.keyCode&&("password"!=n&&"guest"!=this.getCheckedValue("type")||i.call(this))}),o.onerror=function(e){$p.ajax.authorized=!1;var t=e.message.toLowerCase();t.indexOf("auth")!=-1?($p.msg.show_msg({title:$p.msg.main_title+$p.version,type:"alert-error",text:$p.msg.error_auth}),o.setItemValue("password",""),o.validate()):t.indexOf("gateway")==-1&&t.indexOf("net")==-1||$p.msg.show_msg({title:$p.msg.main_title+$p.version,type:"alert-error",text:$p.msg.error_network})}},$p.iface.open_settings=function(e){var t=e||("undefined"!=typeof event?event:void 0);t&&t.preventDefault();var n=$p.job_prm.parse_url();return $p.iface.set_hash(n.obj,n.ref,n.frm,"settings"),$p.iface.cancel_bubble(t)},$p.iface.swith_view=function(e){var t,n=$p.iface,a=function(e){function t(e,t){return e.text>t.text?1:e.text<t.text?-1:void 0}if(n.tree){if(n.tree._view!=e&&["rep","cal"].indexOf(e)==-1){if(n.tree.deleteChildItems(0),"oper"==e){var a,i,s={id:0,item:[{id:"oper_cat",text:$p.msg.meta_cat,open:!0,item:[]},{id:"oper_doc",text:$p.msg.meta_doc,item:[]},{id:"oper_cch",text:$p.msg.meta_cch,item:[]},{id:"oper_cacc",text:$p.msg.meta_cacc,item:[]},{id:"oper_tsk",text:$p.msg.meta_tsk,item:[]}]},o=s.item[0].item;for(a in $p.cat)"function"!=typeof $p.cat[a]&&(i=$p.cat[a].metadata(),i.hide||o.push({id:"oper.cat."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),o=s.item[1].item;for(a in $p.doc)"function"!=typeof $p.doc[a]&&(i=$p.doc[a].metadata(),i.hide||o.push({id:"oper.doc."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),o=s.item[2].item;for(a in $p.cch)"function"!=typeof $p.cch[a]&&(i=$p.cch[a].metadata(),i.hide||o.push({id:"oper.cch."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),o=s.item[3].item;for(a in $p.cacc)"function"!=typeof $p.cacc[a]&&(i=$p.cacc[a].metadata(),i.hide||o.push({id:"oper.cacc."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),o=s.item[4].item;for(a in $p.tsk)"function"!=typeof $p.tsk[a]&&(i=$p.tsk[a].metadata(),i.hide||o.push({id:"oper.tsk."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),n.tree.parse(s,function(){var e=$p.job_prm.parse_url();e.obj&&n.tree.selectItem(e.view+"."+e.obj,!0)},"json")}else n.tree.loadXML(n.tree.tree_filteres,function(){});n.tree._view=e}}else{var r=$p.job_prm.parse_url();if(r.obj){var l=r.obj.split(".");if(l.length>1){var c=$p.md.mgr_by_class_name(r.obj);"function"==typeof n.docs.close&&n.docs.close(),c&&c.form_list(n.docs,{})}}}};return 0==e.indexOf(n.docs.getViewName())?n.docs.getViewName():(t=n.docs.showView(e),1==t&&("cal"!=e||window.dhtmlXScheduler||($p.load_script("dist/dhtmlxscheduler.min.js","script",function(){scheduler.config.first_hour=8,scheduler.config.last_hour=22,n.docs.scheduler=n.docs.attachScheduler(new Date("2015-11-20"),"week","scheduler_here"),n.docs.scheduler.attachEvent("onBeforeViewChange",function(e,t,n,a){return"timeline"!=n||($p.msg.show_not_implemented(),!1)})}),$p.load_script("dist/dhtmlxscheduler.css","link"))),a(e),void("def"==e?n.main.showStatusBar():n.main.hideStatusBar()))},$p.iface.OTooolBar=OTooolBar,$p.iface.add_button=function(e,t,n){var a=document.createElement("div"),i="";return a.name=(t?t.name+"_":"")+n.name,e.appendChild(a),a.className=0==n.name.indexOf("sep_")?"md_otooolbar_sep":"md_otooolbar_button",n.hasOwnProperty("class_name")&&a.classList.add(n.class_name),n.img&&(i='<img src="'+(t?t.image_path:"")+n.img+'">'),n.b?i+='<b style="vertical-align: super;"> '+n.b+"</b>":n.text?i+='<span style="vertical-align: super;"> '+n.text+"</span>":n.css&&a.classList.add(n.css),a.innerHTML=i,n.float&&(a.style.float=n.float),n.clear&&(a.style.clear=n.clear),n.width&&(a.style.width=n.width),n.paddingRight&&(a.style.paddingRight=n.paddingRight),n.paddingLeft&&(a.style.paddingLeft=n.paddingLeft),n.tooltip&&(a.title=n.tooltip),a},"undefined"!=typeof window&&"dhtmlx"in window&&(eXcell_addr.prototype=eXcell_proto,window.eXcell_addr=eXcell_addr),DataManager.prototype.form_obj=function(e,t){function n(){h||((e instanceof dhtmlXLayoutCell||e instanceof dhtmlXSideBarCell||e instanceof dhtmlXCarouselCell)&&(t.bind_pwnd||t.Приклеить)?("function"==typeof e.close&&e.close(!0),m=e,m.close=function(t){var n=m||e;(t||d())&&(n&&(n.elmnts&&["vault","vault_pop"].forEach(function(e){n.elmnts[e]&&n.elmnts[e].unload&&n.elmnts[e].unload()}),v&&v.class_name&&$p.eve.callEvent("frm_close",[v.class_name,y&&y._obj?y.ref:""]),n.conf&&(n.detachToolbar(),n.detachStatusBar(),n.conf.unloading=!0,n.detachObject(!0))),p(t))},m.elmnts={grids:{}}):(f={name:"wnd_obj_"+v.class_name,wnd:{top:80+40*Math.random(),left:120+80*Math.random(),width:700,height:400,modal:!0,center:!1,pwnd:e,allow_close:!0,allow_minmax:!0,on_close:u,caption:x.obj_presentation||x.synonym}},m=$p.iface.dat_blank(null,f.wnd)),m.ref||m.__define({ref:{get:function(){return y?y.ref:$p.utils.blank.guid},enumerable:!1,configurable:!0},set_text:{value:function(e){if(t&&t.set_text||m&&m.setText){var n=y.presentation;if(!n)return;y instanceof CatObj?n=(x.obj_presentation||x.synonym)+": "+n:y instanceof DocObj&&(n+=y.posted?" (проведен)":" (не проведен)"),y._modified&&n.lastIndexOf("*")!=n.length-1?n+=" *":y._modified||n.lastIndexOf("*")!=n.length-1||(n=n.replace(" *","")),(e||g!==n)&&(g=n,t.set_text?t.set_text(n):m.setText(n))}},enumerable:!1,configurable:!0}}),m.elmnts.frm_tabs=m.attachTabbar({arrows_mode:"auto",offsets:{top:0,right:0,bottom:0,left:0}}),m.elmnts.frm_tabs.addTab("tab_header"," Реквизиты ",null,null,!0),m.elmnts.tabs={tab_header:m.elmnts.frm_tabs.cells("tab_header")},m.elmnts.frm_toolbar=m.attachToolbar(),m.elmnts.frm_toolbar.setIconsPath(dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()),m.elmnts.frm_toolbar.loadStruct(t.toolbar_struct||$p.injected_data["toolbar_obj.xml"],function(){m===e&&(this.cont.style.top="4px"),this.addSpacer("btn_unpost"),this.attachEvent("onclick",t.toolbar_click||s);var n=$p.current_acl.get_acl(v.class_name);v instanceof DocManager&&n.indexOf("p")!=-1?(this.enableItem("btn_post"),t.toolbar_struct||this.setItemText("btn_save_close","<b>Провести и закрыть</b>")):this.hideItem("btn_post"),v instanceof DocManager&&n.indexOf("o")!=-1?this.enableItem("btn_unpost"):this.hideItem("btn_unpost"),n.indexOf("e")==-1&&(this.hideItem("btn_save_close"),this.disableItem("btn_save")),t.on_select&&this.setItemText("btn_save_close","Записать и выбрать"),v instanceof CatManager||v instanceof DocManager?(v.printing_plates().then(function(e){for(var t in e)m.elmnts.frm_toolbar.addListOption("bs_print",t,"~","button",e[t].toString())}),m.elmnts.vault_pop=new dhtmlXPopup({toolbar:this,id:"btn_files"}),m.elmnts.vault_pop.attachEvent("onShow",r)):this.disableItem("bs_print"),m!=e&&this.hideItem("btn_close")}),h=!0)}function a(e){y&&m&&m.set_text()}function i(){if(h||(clearTimeout(_),n()),m.set_text(),!t.hide_header&&m.showHeader&&m.showHeader(),t.draw_tabular_sections)t.draw_tabular_sections(y,m,l);else if(!y.is_folder)if(x.form&&x.form.obj&&x.form.obj.tabular_sections_order)x.form.obj.tabular_sections_order.forEach(function(e){l(e)});else for(var e in x.tabular_sections)"extra_fields"!==e&&y[e]instanceof TabularSection&&l(e);if(t.draw_pg_header)t.draw_pg_header(y,m);else{var i=$p.current_acl.get_acl(v.class_name);m.elmnts.pg_header=m.elmnts.tabs.tab_header.attachHeadFields({obj:y,pwnd:m,read_only:i.indexOf("e")==-1}),m.attachEvent("onResizeFinish",function(e){m.elmnts.pg_header.enableAutoHeight(!1,m.elmnts.tabs.tab_header._getHeight()-20,!0)})}return Object.observe(y,a,["update","row"]),{wnd:m,o:y}}function s(e){"btn_save_close"==e?c("close"):"btn_save"==e?c("save"):"btn_post"==e?c("post"):"btn_unpost"==e?c("unpost"):"btn_close"==e?m.close():"btn_go_connection"==e?o():"prn_"==e.substr(0,4)?v.print(y,e,m):"btn_import"==e?v.import(null,y):"btn_export"==e&&v.export({items:[y],pwnd:m,obj:!0})}function o(){$p.msg.show_not_implemented()}function r(){m.elmnts.vault||(m.elmnts.vault=m.elmnts.vault_pop.attachVault(400,250,{_obj:y,buttonClear:!1,autoStart:!0,filesLimit:10,mode:"pouch"}),m.elmnts.vault.conf.wnd=m)}function l(e,t){if(_md.ts_captions(v.class_name,e)){m.elmnts.frm_tabs.addTab("tab_"+e," "+x.tabular_sections[e].synonym+" "),m.elmnts.tabs["tab_"+e]=m.elmnts.frm_tabs.cells("tab_"+e);var n=$p.current_acl.get_acl(v.class_name);if(m.elmnts.grids[e]=m.elmnts.tabs["tab_"+e].attachTabular({obj:y,ts:e,pwnd:m,read_only:n.indexOf("e")==-1,toolbar_struct:t}),n.indexOf("e")==-1){var a=m.elmnts.tabs["tab_"+e].getAttachedToolbar();a.disableItem("btn_add"),a.disableItem("btn_delete")}}}function c(e){m.progressOn();var n;y instanceof DocObj&&("post"==e?n=!0:"unpost"==e?n=!1:"close"==e&&$p.current_acl.get_acl(v.class_name).indexOf("p")!=-1&&(n=!0)),y.save(n).then(function(){m.progressOff(),"close"==e?(t.on_select&&t.on_select(y),m.close()):m.set_text()}).catch(function(e){m.progressOff(),e instanceof Error&&$p.record_log(e)})}function p(n){t&&t.on_close&&!n&&t.on_close(),n||(delete m.ref,delete m.set_text,Object.unobserve(y,a),v=m=y=x=f=e=t=null)}function d(){return!(y._modified&&!b)||(dhtmlx.confirm({title:y.presentation,text:$p.msg.modified_close,cancel:$p.msg.cancel,callback:function(e){e&&(b=!0,"ram"==y._manager.cachable?this.close():y.is_new()?(y.unload(),this.close()):(setTimeout(y.load.bind(y),100),this.close()))}.bind(m)}),!1)}function u(e){if(d())return setTimeout(p),e&&e.elmnts&&["vault","vault_pop"].forEach(function(t){e.elmnts[t]&&e.elmnts[t].unload&&e.elmnts[t].unload()}),v&&v.class_name&&$p.eve.callEvent("frm_close",[v.class_name,y&&y._obj?y.ref:""]),!0}var m,f,h,_,g,b,v=this,x=v.metadata(),y=t.o;return _=setTimeout(n),$p.utils.is_data_obj(y)?y.is_new()&&t.on_select?v.create({},!0).then(function(e){return y=e,e=null,i()}):y.is_new()&&!y.empty()?y.load().then(i):Promise.resolve(i()):(e&&e.progressOn&&e.progressOn(),v.get(t.hasOwnProperty("ref")?t.ref:t,!0,!0).then(function(t){return y=t,t=null,e&&e.progressOff&&e.progressOff(),i()}).catch(function(t){e&&e.progressOff&&e.progressOff(),m.close(),$p.record_log(t)}))},DataObj.prototype.form_obj=function(e,t){return t||(t={}),t.o=this,this._manager.form_obj(e,t)},DataProcessorsManager.prototype.form_rep=function(e,t){function n(){if((e instanceof dhtmlXLayoutCell||e instanceof dhtmlXSideBarCell||e instanceof dhtmlXCarouselCell)&&(t.bind_pwnd||t.Приклеить)){if(o==e&&o._mgr==c)return;"function"==typeof e.close&&e.close(!0),o=e,o.close=function(t){var n=o||e;(t||check_modified())&&(n&&n.conf&&(n.detachToolbar(),n.detachStatusBar(),n.conf.unloading=!0,n.detachObject(!0)),s(t))},o.elmnts={grids:{}}}else r={name:"wnd_rep_"+c.class_name,wnd:{top:80+40*Math.random(),left:120+80*Math.random(),width:700,height:400,modal:!0,center:!1,pwnd:e,allow_close:!0,allow_minmax:!0,on_close:frm_close,caption:p.obj_presentation||p.synonym}},o=$p.iface.dat_blank(null,r.wnd);o._mgr=c,o.report=c.create(),o.set_text||o.__define({set_text:{value:function(e){if(t&&t.set_text||o&&o.setText){var n=p.obj_presentation||p.synonym;(e||l!==n)&&(l=n,t.set_text?t.set_text(n):o.setText(n))}},configurable:!0}}),o.elmnts.layout=o.attachLayout({pattern:"2U",cells:[{id:"a",text:"Отчет",header:!1},{id:"b",text:"Параметры",collapsed_text:"Параметры",width:220}],offsets:{top:0,right:0,bottom:0,left:0}}),o.elmnts.frm_toolbar=o.attachToolbar(),o.elmnts.frm_toolbar.setIconsPath(dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()),o.elmnts.frm_toolbar.loadStruct(t.toolbar_struct||$p.injected_data["toolbar_rep.xml"],function(){o===e&&(this.cont.style.top="4px"),this.addSpacer("btn_run"),this.attachEvent("onclick",t.toolbar_click||a)}),o.set_text(),!t.hide_header&&o.showHeader&&o.showHeader(),o.elmnts.table=new $p.HandsontableDocument(o.elmnts.layout.cells("a"),{ +allow_offline:o.report.allow_offline,autorun:!1}).then(function(e){if(!e._online)return o.elmnts.table=null}),o.elmnts.frm_prm=document.createElement("DIV"),o.elmnts.frm_prm.style="height: 100%; min-height: 300px; width: 100%",o.elmnts.layout.cells("b").attachObject(o.elmnts.frm_prm),o.report.daterange=new $p.iface.ODateRangePicker(o.elmnts.frm_prm,t)}function a(e){"btn_close"==e?o.close():"btn_run"==e&&o.report.build().then(i).catch(i)}function i(e){o.elmnts.table.requery(e)}function s(n){t&&t.on_close&&!n&&t.on_close(),n||(delete o.set_text,o.elmnts.table&&o.elmnts.table.hot.destroy(),o.report.daterange&&o.report.daterange.remove(),o.report=null,c=o=p=r=e=t=null)}var o,r,l,c=this,p=c.metadata();return t||(t={}),t.date_from||(t.date_from=new Date((new Date).getFullYear().toFixed()+"-01-01")),t.date_till||(t.date_till=new Date((new Date).getFullYear().toFixed()+"-12-31")),n(),o},DataManager.prototype.form_selection=function(e,t){function n(){return e instanceof dhtmlXCellObject?(e instanceof dhtmlXTabBarCell||"function"!=typeof e.close||e.close(!0),f=e,f.close=function(t){(f||e)&&((f||e).detachToolbar(),(f||e).detachStatusBar(),(f||e).conf&&((f||e).conf.unloading=!0),(f||e).detachObject(!0)),p(t)},t.hide_header||setTimeout(function(){f.showHeader()})):(f=$p.iface.w.createWindow(null,0,0,700,500),f.centerOnScreen(),f.setModal(1),f.button("park").hide(),f.button("minmax").show(),f.button("minmax").enable(),f.attachEvent("onClose",d)),$p.iface.bind_help(f),f.setText&&!t.hide_text&&f.setText("Список "+(h.class_name.indexOf("doc.")==-1?'справочника "':'документов "')+(_.list_presentation||_.synonym)+'"'),document.body.addEventListener("keydown",a,!1),f.elmnts={},!t.status_bar&&t.smart_rendering||(f.elmnts.status_bar=f.attachStatusBar()),t.smart_rendering||f.elmnts.status_bar.setText("<div id='"+h.class_name.replace(".","_")+"_select_recinfoArea'></div>"),f.elmnts.toolbar=f.attachToolbar(),f.elmnts.toolbar.setIconsPath(dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()),f.elmnts.toolbar.loadStruct(t.toolbar_struct||$p.injected_data["toolbar_selection.xml"],function(){this.attachEvent("onclick",o),f===e&&(this.cont.parentElement.classList.add("dhx_cell_toolbar_no_borders"),this.cont.parentElement.classList.remove("dhx_cell_toolbar_def"),this.cont.style.top="4px");var n={manager:h,toolbar:this,onchange:i,hide_filter:t.hide_filter,custom_selection:t.custom_selection};t.date_from&&(n.date_from=t.date_from),t.date_till&&(n.date_till=t.date_till),t.period&&(n.period=t.period),f.elmnts.filter=new $p.iface.Toolbar_filter(n);var a=$p.current_acl.get_acl(h.class_name);a.indexOf("i")==-1&&this.hideItem("btn_new"),a.indexOf("v")==-1&&this.hideItem("btn_edit"),a.indexOf("d")==-1&&this.hideItem("btn_delete"),y||(this.hideItem("btn_select"),this.hideItem("sep1"),$p.iface.docs&&$p.iface.docs.getViewName&&"oper"==$p.iface.docs.getViewName()&&this.addListOption("bs_more","btn_order_list","~","button","<i class='fa fa-briefcase fa-lg fa-fw'></i> Список заказов")),this.addListOption("bs_more","btn_import","~","button","<i class='fa fa-upload fa-lg fa-fw'></i> Загрузить из файла"),this.addListOption("bs_more","btn_export","~","button","<i class='fa fa-download fa-lg fa-fw'></i> Выгрузить в файл"),h.printing_plates?h.printing_plates().then(function(e){var t;for(var n in e)f.elmnts.toolbar.addListOption("bs_print",n,"~","button",e[n].toString()),t=!0;t||f.elmnts.toolbar.hideItem("bs_print")}):f.elmnts.toolbar.hideItem("bs_print"),s()}),f._mgr=h,f}function a(e){function t(){var e;return $p.iface.w.forEachWindow(function(t){t==f||!t.isModal()&&$p.iface.w.getTopmostWindow()!=t||(e=!0)}),e}if(f&&f.is_visible&&f.is_visible())if(e.ctrlKey&&70==e.keyCode){if(!t())return setTimeout(function(){f.elmnts.filter.input_filter&&"desktop"==$p.job_prm.device_type&&f.elmnts.filter.input_filter.focus()}),$p.iface.cancel_bubble(e)}else if(e.shiftKey&&116==e.keyCode){if(!t())return setTimeout(function(){f.elmnts.grid.reload()}),e.preventDefault&&e.preventDefault(),$p.iface.cancel_bubble(e)}else 27==e.keyCode&&(t()||setTimeout(function(){f.close()}))}function i(e){f&&f.elmnts&&(g&&(e.filter||e.hide_tree?f.elmnts.cell_tree.collapse():f.elmnts.cell_tree.expand()),f.elmnts.grid.reload())}function s(){var e,n,a,i,s,o;g?(e=f.attachLayout("2U"),a=e.cells("b"),a.hideHeader(),n=f.elmnts.cell_tree=e.cells("a"),n.setWidth("220"),n.hideHeader(),i=f.elmnts.tree=n.attachDynTree(h,null,function(){setTimeout(function(){s&&s.reload&&s.reload()},20)}),i.attachEvent("onSelect",function(e,t){t&&(this.do_not_reload?delete this.do_not_reload:setTimeout(function(){s&&s.reload&&s.reload()},20))}),i.attachEvent("onDblClick",function(e){r(e)})):(a=f,setTimeout(function(){s&&s.reload&&s.reload()},20)),s=f.elmnts.grid=a.attachGrid(),s.setIconsPath(dhtmlx.image_path),s.setImagePath(dhtmlx.image_path),s.attachEvent("onBeforeSorting",m),s.attachEvent("onBeforePageChanged",function(){return!!this.getRowsNum()}),s.attachEvent("onXLE",function(){a.progressOff()}),s.attachEvent("onXLS",function(){a.progressOn()}),s.attachEvent("onDynXLS",function(e,t){var n=u(e,t);if(n)return h.sync_grid(n,s),!1}),s.attachEvent("onRowDblClicked",function(e,t){if(i&&i.items[e]){i.selectItem(e);var n=i.getParentId(e);n&&n!=$p.utils.blank.guid&&i.openItem(n)}else r(e)}),t.smart_rendering?s.enableSmartRendering(!0,50):(s.setPagingWTMode(!0,!0,!0,[20,30,60]),s.enablePaging(!0,30,8,h.class_name.replace(".","_")+"_select_recinfoArea"),s.setPagingSkin("toolbar",dhtmlx.skin)),$p.iface.docs&&$p.iface.docs.getViewName&&"oper"==$p.iface.docs.getViewName()&&s.enableMultiselect(!0),s.reload=function(){var e=u();return e?(a.progressOn(),s.clearAll(),h.sync_grid(e,s).then(function(n){if("object"==typeof n)$p.msg.check_soap_result(n);else if(!o){if(e.initial_value){var r=n.indexOf("set_parent"),l=n.indexOf("'>",r),c=n.substr(r+12,l-r-12);$p.utils.is_guid(c)&&g&&(i.do_not_reload=!0,i.selectItem(c,!1)),s.selectRowById(e.initial_value)}else e.parent&&$p.utils.is_guid(e.parent)&&g&&(i.do_not_reload=!0,i.selectItem(e.parent,!1));s.setColumnMinWidth(200,s.getColIndexById("presentation")),s.enableAutoWidth(!0,1200,600),s.setSizes(),o=!0,f.elmnts.filter.input_filter&&"desktop"==$p.job_prm.device_type&&f.elmnts.filter.input_filter.focus(),t.on_grid_inited&&t.on_grid_inited()}v&&o&&s.setSortImgState(!0,b,v),a.progressOff()})):Promise.resolve()}}function o(e){if(!t.toolbar_click||t.toolbar_click(e,f,h)!==!1)if("btn_select"==e)r();else if("btn_new"==e)h.create({},!0).then(function(e){t.on_new?t.on_new(e,f):$p.job_prm.keep_hash?e.form_obj(f):(e._set_loaded(e.ref),$p.iface.set_hash(h.class_name,e.ref))});else if("btn_edit"==e){var n=f.elmnts.grid.getSelectedRowId();n?t.on_edit?t.on_edit(h,n,f):$p.job_prm.keep_hash?h.form_obj(f,{ref:n}):$p.iface.set_hash(h.class_name,n):$p.msg.show_msg({type:"alert-warning",text:$p.msg.no_selected_row.replace("%1",""),title:$p.msg.main_title})}else"prn_"==e.substr(0,4)?l(e):"btn_order_list"==e?$p.iface.set_hash("","","","def"):"btn_delete"==e?c():"btn_import"==e?h.import():"btn_export"==e?h.export(f.elmnts.grid.getSelectedRowId()):"btn_requery"==e&&(x={},f.elmnts.grid.reload())}function r(n){n||(n=f.elmnts.grid.getSelectedRowId());var a;if(t.selection&&t.selection.forEach(function(e){for(var t in e)"is_folder"==t&&(a=e[t])}),f.elmnts.tree&&f.elmnts.tree.items[n]&&f.elmnts.tree.getSelectedId()!=n)return void f.elmnts.tree.selectItem(n,!0);if(n&&a===!0&&f.elmnts.grid.cells(n,0).cell.classList.contains("cell_ref_elm"))return void $p.msg.show_msg($p.msg.select_grp);if(!n&&f.elmnts.tree||f.elmnts.tree&&f.elmnts.tree.getSelectedId()==n){if(a===!1)return void $p.msg.show_msg($p.msg.select_elm);n=f.elmnts.tree.getSelectedId()}n&&(t.on_edit?t.on_edit(h,n,f):y?h.get(n,!0).then(function(t){f.close(),y.call(e.grid||e,t)}):$p.job_prm.keep_hash?h.form_obj(f,{ref:n}):$p.iface.set_hash(h.class_name,n))}function l(e){var t=f.elmnts.grid.getSelectedRowId();t?h.print(t,e,f):$p.msg.show_msg({type:"alert-warning",text:$p.msg.no_selected_row.replace("%1",""),title:$p.msg.main_title})}function c(){var e=f.elmnts.grid.getSelectedRowId();e?h.get(e,!0,!0).then(function(e){dhtmlx.confirm({title:$p.msg.main_title,text:e._deleted?$p.msg.mark_undelete_confirm.replace("%1",e.presentation):$p.msg.mark_delete_confirm.replace("%1",e.presentation),cancel:"Отмена",callback:function(t){t&&e.mark_deleted(!e._deleted)}})}):$p.msg.show_msg({type:"alert-warning",text:$p.msg.no_selected_row.replace("%1",""),title:$p.msg.main_title})}function p(n){document.body.removeEventListener("keydown",a),t&&t.on_close&&!n&&t.on_close(),n||(h=f=_=x=y=e=t=null)}function d(){return setTimeout(p,10),e.on_unload&&e.on_unload.call(e.grid||e),w&&($p.eve.detachEvent(w),w=null),!0}function u(e,n){var a=f.elmnts.filter.get_filter()._mixin({action:"get_selection",metadata:_,class_name:h.class_name,order_by:f.elmnts.grid.columnIds[b]||b,direction:v,start:e||((f.elmnts.grid.currentPage||1)-1)*f.elmnts.grid.rowsBufferOutSize,count:n||f.elmnts.grid.rowsBufferOutSize,get_header:void 0==x.get_header}),i=g?f.elmnts.tree.getSelectedId():null;if(t.smart_rendering&&(a.smart_rendering=!0),t.date_from&&!a.date_from&&(a.date_from=t.date_from),t.date_till&&!a.date_till&&(a.date_till=t.date_till),t.initial_value&&(a.initial_value=t.initial_value),t.custom_selection&&(a.custom_selection=t.custom_selection),t.selection)if(a.selection)if(Array.isArray(t.selection))t.selection.forEach(function(e){a.selection.push(e)});else for(var s in t.selection){res.selection||(res.selection=[]);var o={};o[s]=t.selection[s],a.selection.push(o)}else a.selection=t.selection;t.owner&&!a.owner&&(a.owner=t.owner),a.parent=!i&&!t.parent||a.filter?null:i||t.parent,g&&!a.parent&&(a.parent=$p.utils.blank.guid);for(var r in a)if(x[r]!=a[r])return x=a,a}function m(e){var t=f.elmnts.grid.getSortingState();return b=e,v="des"==t[1]?"asc":"des",f.elmnts.grid.reload(),!0}e||(e=t&&t.pwnd?t.pwnd:{}),t||e instanceof dhtmlXCellObject||(t=e,e={}),t||(t={});var f,h=this,_=t.metadata||h.metadata(),g=_.hierarchical&&!(h instanceof ChartOfAccountManager),b=0,v="asc",x={},y=e.on_select||t.on_select,w=$p.eve.attachEvent("frm_close",function(e,t){h&&h.class_name==e&&f&&f.elmnts&&f.elmnts.grid.reload().then(function(){$p.utils.is_empty_guid(t)||f.elmnts.grid.selectRowById(t,!1,!0,!0)})});return g&&t.initial_value&&t.initial_value!=$p.utils.blank.guid&&!t.parent?h.get(t.initial_value,!0).then(function(e){return t.parent=e.parent.ref,t.set_parent=t.parent,n()}):n()},DataManager.prototype.form_list=function(e,t){return this.form_selection(e,t)},$p.iface.wnd_sync=function(){function e(){var e={name:"wnd_sync",wnd:{id:"wnd_sync",top:130,left:200,width:496,height:290,modal:!0,center:!0,caption:"Подготовка данных"}};t.wnd_sync=$p.iface.dat_blank(null,e.wnd);var n=[{type:"block",name:"form_block_1",list:[{type:"label",name:"form_label_1",label:$p.msg.sync_data},{type:"block",name:"form_block_2",list:[{type:"template",name:"img_long",className:"img_long"},{type:"newcolumn"},{type:"template",name:"text_processed"},{type:"template",name:"text_current"},{type:"template",name:"text_bottom"}]}]},{type:"button",name:"form_button_1",value:$p.msg.sync_break}];t.frm_sync=t.wnd_sync.attachForm(n),t.frm_sync.attachEvent("onButtonClick",function(e){t&&(t.do_break=!0)}),t.frm_sync.setItemValue("text_processed","Инициализация"),t.frm_sync.setItemValue("text_bottom","Загружается структура таблиц...")}var t,n=$p.iface.sync={};n.create=function(n){t=n,e()},n.update=function(e){t.frm_sync.setItemValue("text_processed","Обработано элементов: "+t.step*t.step_size+" из "+t.count_all);var n,a="",i=0;for(var s in e){if(i++,i>4)break;a&&(a+="<br />"),n=$p.cat[s].metadata(),a+=(n.list_presentation||n.synonym)+" ("+e[s].length+")"}t.frm_sync.setItemValue("text_current","Текущий запрос: "+t.step+" ("+Math.round(t.step*t.step_size*100/t.count_all)+"%)"),t.frm_sync.setItemValue("text_bottom",a)},n.close=function(){t&&t.wnd_sync&&(t.wnd_sync.close(),delete t.wnd_sync,delete t.frm_sync)}},DataManager.prototype.export=function(e){function t(){$p.wsql.restore_options("data_manager",l),l.wnd.caption="Экспорт "+r.family_name+" '"+(r.metadata().synonym||r.metadata().name)+"'",o=$p.iface.dat_blank(null,l.wnd),o.bottom_toolbar({buttons:[{name:"btn_cancel",text:'<i class="fa fa-times fa-lg"></i> Отмена',title:"Отмена",width:"80px",float:"right"},{name:"btn_ok",b:'<i class="fa fa-floppy-o"></i> Ок',title:"Выполнить экспорт",width:"50px",float:"right"}],onclick:function(e){return"btn_ok"==e?i():o.close(),!1}}),o.button("close").show(),o.button("park").hide(),o.attachEvent("onClose",s);var t=[{type:"fieldset",name:"form_range",label:"Выгрузить",list:[{type:"settings",labelWidth:320,labelAlign:"left",position:"label-right"},{type:"radio",name:"range",label:"Выделенные строки",value:"selected"},{type:"radio",name:"range",label:"Весь справочник",value:"all"}]},{type:"fieldset",name:"form_fieldset_2",label:"Дополнительно выгрузить",list:[{type:"settings",labelWidth:160,position:"label-right"},{type:"checkbox",name:"meta",label:"Описание метаданных",labelAlign:"left",position:"label-right",checked:l.meta},{type:"newcolumn"},{type:"checkbox",name:"relation",label:"Связанные объекты",position:"label-right",checked:l.relation,tooltip:"Связанные объекты по ссылкам (пока не реализовано)"}]},{type:"fieldset",name:"fieldset_format",label:"Формат файла",list:[{type:"settings",labelWidth:60,labelAlign:"left",position:"label-right"},{type:"radio",name:"format",label:"json",value:"json",tooltip:"Выгрузить в формате JSON"},{type:"newcolumn"},{type:"radio",name:"format",label:"xlsx",value:"xlsx",tooltip:"Выгрузить в офисном формате XLSX"},{type:"newcolumn"},{type:"radio",name:"format",label:"atom",value:"atom",tooltip:"Выгрузить в формате XML Atom"}]}];o.elmnts.frm=o.attachForm(t),o.elmnts.frm.setItemValue("range",l.range||"all"),e.items&&1==e.items.length?(e.obj?o.elmnts.frm.setItemLabel("range","selected","Тек. объект: "+e.items[0].presentation):r.get(e.items[0],!0).then(function(e){o.elmnts.frm.setItemLabel("range","selected","Тек. объект: "+e.presentation)}),o.elmnts.frm.setItemValue("range","selected")):e.items&&e.items.length&&o.elmnts.frm.setItemLabel("range","selected","Выделенные строки ("+e.items.length+" элем.)"),r instanceof DocManager&&o.elmnts.frm.setItemLabel("range","all","Все документы из кеша (0 элем.)"),o.elmnts.frm.setItemValue("format",l.format||"json"),o.elmnts.frm.attachEvent("onChange",n),n(),e.pwnd&&e.pwnd.isModal&&e.pwnd.isModal()&&(e.set_pwnd_modal=!0,e.pwnd.setModal(!1)),o.setModal(!0)}function n(){o.elmnts.frm.setItemValue("relation",!1),o.elmnts.frm.disableItem("relation"),"all"==o.elmnts.frm.getItemValue("range")?(o.elmnts.frm.disableItem("format","atom"),"atom"==o.elmnts.frm.getItemValue("format")&&o.elmnts.frm.setItemValue("format","json")):o.elmnts.frm.enableItem("format","atom"),"json"==o.elmnts.frm.getItemValue("format")?o.elmnts.frm.enableItem("meta"):"sql"==o.elmnts.frm.getItemValue("format")?(o.elmnts.frm.setItemValue("meta",!1),o.elmnts.frm.disableItem("meta")):(o.elmnts.frm.setItemValue("meta",!1),o.elmnts.frm.disableItem("meta"))}function a(){return l.format=o.elmnts.frm.getItemValue("format"),l.range=o.elmnts.frm.getItemValue("range"),l.meta=o.elmnts.frm.getItemValue("meta"),l.relation=o.elmnts.frm.getItemValue("relation"),l}function i(){function t(){e.obj?$p.wsql.alasql("SELECT * INTO XLSX('"+r.table_name+".xlsx',{headers:true}) FROM ?",[e.items[0]._obj]):$p.wsql.alasql("SELECT * INTO XLSX('"+r.table_name+".xlsx',{headers:true}) FROM "+r.table_name)}a();var n={meta:{},items:{}},i=n.items[r.class_name]=[];if(l.meta&&(n.meta[r.class_name]=r.metadata()),"json"==l.format)e.obj?i.push(e.items[0]._obj):r.each(function(t){"all"!=l.range&&e.items.indexOf(t.ref)==-1||i.push(t._obj)}),e.items.length&&!i.length?r.get(e.items[0],!0).then(function(e){i.push(e._obj),alasql.utils.saveFile(r.table_name+".json",JSON.stringify(n,null,4))}):alasql.utils.saveFile(r.table_name+".json",JSON.stringify(n,null,4));else if("xlsx"==l.format)window.xlsx?t():$p.load_script("//cdn.jsdelivr.net/js-xlsx/latest/xlsx.core.min.js","script",t);else if("atom"==l.format&&e.items.length){var s=e.obj?Promise.resolve(e.items[0]):r.get(e.items[0],!0);s.then(function(e){alasql.utils.saveFile(r.table_name+".xml",e.to_atom())})}else $p.msg.show_not_implemented()}function s(t){return $p.iface.popup.hide(),o.wnd_options(l.wnd),$p.wsql.save_options("data_manager",a()),o.setModal(!1),e.set_pwnd_modal&&e.pwnd.setModal&&e.pwnd.setModal(!0),!0}e&&"string"==typeof e?e={items:e.split(",")}:e||(e={items:[]});var o,r=this,l={name:"export",wnd:{top:130,left:200,width:480,height:350}};t()},DataManager.prototype.import=function(e,t){function n(e){function n(e,n){var a=_md.mgr_by_class_name(e);if(n.length)if(t){if(t._manager==a)for(var s in n)$p.utils.fix_guid(n[s])==t.ref&&(i=!0,a.load_array([n[s]],!0))}else i=!0,a.load_array(n,!0)}if(o.close(),a.files.length){var s=new FileReader;s.onload=function(e){try{var t=JSON.parse(s.result);if(t.items)for(var a in t.items)n(a,t.items[a]);else["cat","doc","ireg","areg","cch","cacc"].forEach(function(e){if(t[e])for(var a in t[e])n(e+"."+a,t.cat[a])});i||$p.msg.show_msg($p.msg.sync_no_data)}catch(e){$p.msg.show_msg(e.message)}},s.readAsText(a.files[0])}}var a,i;if(!e&&void 0!=typeof window){var s={name:"import",wnd:{width:300,height:100,caption:$p.msg.select_file_import}},o=$p.iface.dat_blank(null,s.wnd);a=document.createElement("input"),a.setAttribute("id","json_file"),a.setAttribute("type","file"),a.setAttribute("accept",".json"),a.setAttribute("value","*.json"),a.onchange=n,o.button("close").show(),o.button("park").hide(),o.attachObject(a),o.centerOnScreen(),o.setModal(!0),setTimeout(function(){a.click()},100)}},$p.eve.__define({set_offline:{value:function(e){var t=$p.job_prm.offline;$p.job_prm.offline=!(!e&&!$p.wsql.get_user_param("offline","boolean")),t!=$p.job_prm.offline&&(t=$p.job_prm.offline)}},on_rotate:{value:function(e){$p.job_prm.device_orient=0==window.orientation||180==window.orientation?"portrait":"landscape","undefined"!=typeof e&&$p.eve.callEvent("onOrientationChange",[$p.job_prm.device_orient])}},steps:{value:{load_meta:0,authorization:1,create_managers:2,process_access:3,load_data_files:4,load_data_db:5,load_data_wsql:6,save_data_wsql:7}},log_in:{value:function(e){var t,n={};return e($p.eve.steps.load_meta),$p.ajax.default_attr(n,$p.job_prm.irest_url()),($p.job_prm.offline?Promise.resolve({responseURL:"",response:""}):$p.ajax.get_ex(n.url,n)).then(function(e){if($p.job_prm.offline||($p.job_prm.irest_enabled=!0),"{"==e.response[0])return JSON.parse(e.response)}).catch(function(){}).then(function(n){return e($p.eve.steps.authorization),t=n,t.root=!0,$p.job_prm.offline||$p.job_prm.irest_enabled?t:$p.ajax.get_ex($p.job_prm.rest_url()+"?$format=json",!0).then(function(){return t})}).catch(function(e){throw $p.iface.auth.onerror&&$p.iface.auth.onerror(e),e}).then(function(t){return e($p.eve.steps.load_data_files),$p.job_prm.offline?t:($p.eve.callEvent("log_in",[$p.ajax.authorized=!0]),"string"==typeof t&&(t=JSON.parse(t)),void($p.msg.check_soap_result(t)||($p.wsql.get_user_param("enable_save_pwd")?$p.wsql.set_user_param("user_pwd",$p.ajax.password):$p.wsql.get_user_param("user_pwd")&&$p.wsql.set_user_param("user_pwd",""),t.now_1c&&t.now_js&&$p.wsql.set_user_param("time_diff",t.now_1c-t.now_js))))}).then(function(){_md.printing_plates(t.printing_plates)})}}}),function(w,eve,msg){var timer_setted=!1,cache;w.addEventListener("online",eve.set_offline),w.addEventListener("offline",function(){eve.set_offline(!0)}),w.addEventListener("load",function(){setTimeout(function(){function navigate(e){e&&(location.origin+location.pathname).indexOf(e)==-1&&location.replace(e)}function init_params(){function e(){var e=dhtmlx.codebase,t=!0,n=!0;e.indexOf("cdn.jsdelivr.net")!=-1&&(e="//cdn.jsdelivr.net/metadata/latest/");for(var a=0;a<document.styleSheets.length;a++)document.styleSheets[a].href&&(document.styleSheets[a].href.indexOf("dhx_web")==-1&&document.styleSheets[a].href.indexOf("dhx_terrace")==-1||(t=!1),document.styleSheets[a].href.indexOf("metadata.css")!=-1&&(n=!1));dhtmlx.skin=$p.wsql.get_user_param("skin")||$p.job_prm.skin||"dhx_web",t&&$p.load_script(e+("dhx_web"==dhtmlx.skin?"dhx_web.css":"dhx_terrace.css"),"link"),n&&$p.load_script(e+"metadata.css","link"),$p.job_prm.additional_css&&$p.job_prm.additional_css.forEach(function(e){(dhx4.isIE||e.indexOf("ie_only")==-1)&&$p.load_script(e,"link")}),dhtmlx.image_path="//oknosoft.github.io/metadata.js/lib/imgs/",dhtmlx.skin_suffix=function(){return dhtmlx.skin.replace("dhx","")+"/"},dhx4.ajax.cache=!0,$p.iface.__define("w",{value:new dhtmlXWindows,enumerable:!1}),$p.iface.w.setSkin(dhtmlx.skin),$p.iface.__define("popup",{value:new dhtmlXPopup,enumerable:!1})}$p.wsql.init_params(),"dhtmlx"in w&&e(),"undefined"==typeof w.orientation?$p.job_prm.device_orient=w.innerWidth>w.innerHeight?"landscape":"portrait":eve.on_rotate(),w.addEventListener("orientationchange",eve.on_rotate,!1),eve.stepper={step:0,count_all:0,step_size:57,files:0},eve.set_offline(!navigator.onLine),setTimeout(function(){$p.wsql.pouch.load_data().catch($p.record_log);var e;(e=document.querySelector("#splash"))&&e.parentNode.removeChild(e),eve.callEvent("iface_init",[$p])},20),(cache=w.applicationCache)&&(cache.addEventListener("noupdate",function(e){},!1),cache.addEventListener("cached",function(e){timer_setted=!0,$p.iface.appcache&&$p.iface.appcache.close()},!1),cache.addEventListener("updateready",function(e){try{cache.swapCache()}catch(e){}$p.iface.do_reload()},!1),cache.addEventListener("error",$p.record_log,!1))}if(!w.JSON||!w.indexedDB)throw eve.redirect=!0,msg.show_msg({type:"alert-error",text:msg.unsupported_browser,title:msg.unsupported_browser_title}),msg.unsupported_browser;$p.__define("job_prm",{value:new JobPrm,writable:!1}),($p.job_prm.use_ip_geo||$p.job_prm.use_google_geo)&&($p.ipinfo=new IPInfo),$p.job_prm.use_google_geo&&(window.google&&window.google.maps?location_callback():$p.on("iface_init",function(){setTimeout(function(){$p.load_script("//maps.google.com/maps/api/js?callback=$p.ipinfo.location_callback","script",function(){})},100)})),$p.job_prm.allow_post_message&&w.addEventListener("message",function(event){if(("*"==$p.job_prm.allow_post_message||$p.job_prm.allow_post_message==event.origin)&&"string"==typeof event.data)try{var res=eval(event.data);if(res&&event.source){if("object"==typeof res)res=JSON.stringify(res);else if("function"==typeof res)return;event.source.postMessage(res,"*")}}catch(e){$p.record_log(e)}}),$p.job_prm.__define("device_type",{get:function(){var e=$p.wsql.get_user_param("device_type");return e||(e=function(e){return e<800?"phone":e<1024?"tablet":"desktop"}(Math.max(screen.width,screen.height)),$p.wsql.set_user_param("device_type",e)),e},set:function(e){$p.wsql.set_user_param("device_type",e)}}),document.body.addEventListener("keydown",function(e){eve.callEvent("keydown",[e])},!1),setTimeout(init_params,10)},10)},!1),w.onbeforeunload=function(){if(!eve.redirect)return msg.onbeforeunload},w.addEventListener("popstat",$p.iface.hash_route),w.addEventListener("hashchange",$p.iface.hash_route)}(window,$p.eve,$p.msg),SpreadsheetDocument.prototype.__define({clear:{value:function(){for(;this._attr.content.firstChild;)this._attr.content.removeChild(this._attr.content.firstChild)}},put:{value:function(e,t){var n;e instanceof HTMLElement?(n=document.createElement(e.tagName),n.innerHTML=e.innerHTML,t||(t=e.attributes)):(n=document.createElement("DIV"),n.innerHTML=e),t&&Object.keys(t).forEach(function(e){"id"!=e&&"id"!=t[e].name&&n.setAttribute(t[e].name||e,t[e].value||t[e])}),this._attr.content.appendChild(n)}},content:{get:function(){return this._attr.content},set:function(e){this.clear(),"string"==typeof e?this._attr.content.innerHTML=e:e instanceof HTMLElement&&(this._attr.content.innerHTML=e.innerHTML)}},title:{get:function(){return this._attr.title},set:function(e){this._attr.title=e}}}),$p.SpreadsheetDocument=SpreadsheetDocument,$p.HandsontableDocument=HandsontableDocument,$p.injected_data._mixin({"form_auth.xml":'<?xml version="1.0" encoding="UTF-8"?>\n<items>\n\t<item type="settings" position="label-left" labelWidth="80" inputWidth="180" noteWidth="180"/>\n\t<item type="fieldset" name="data" inputWidth="auto" label="Авторизация">\n\n <item type="radio" name="type" labelWidth="auto" position="label-right" checked="true" value="guest" label="Гостевой (демо) режим">\n <item type="select" name="guest" label="Роль">\n <option value="Дилер" label="Дилер"/>\n </item>\n </item>\n\n\t\t<item type="radio" name="type" labelWidth="auto" position="label-right" value="auth" label="Есть учетная запись">\n\t\t\t<item type="input" value="" name="login" label="Логин" validate="NotEmpty" />\n\t\t\t<item type="password" value="" name="password" label="Пароль" validate="NotEmpty" />\n\t\t</item>\n\n\t\t<item type="button" value="Войти" name="submit"/>\n\n <item type="template" name="text_options" className="order_dealer_options" inputWidth="170"\n value="<a href=\'#\' onclick=\'$p.iface.open_settings();\' title=\'Страница настроек программы\' > <i class=\'fa fa-cog fa-lg\'></i> Настройки </a> <a href=\'//www.oknosoft.ru/feedback\' target=\'_blank\' style=\'margin-left: 9px;\' title=\'Задать вопрос через форму обратной связи\' > <i class=\'fa fa-question-circle fa-lg\'></i> Вопрос </a>" />\n\n\t</item>\n</items>',"toolbar_add_del.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n <item id="sep0" type="separator"/>\r\n <item type="button" id="btn_add" text="<i class=\'fa fa-plus-circle fa-fw\'></i> Добавить" title="Добавить строку" />\r\n <item type="button" id="btn_delete" text="<i class=\'fa fa-times fa-fw\'></i> Удалить" title="Удалить строку" />\r\n</toolbar>',"toolbar_obj.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n <item id="sep0" type="separator"/>\r\n <item type="button" id="btn_save_close" text="<b>Записать и закрыть</b>" title="Рассчитать, записать и закрыть" />\r\n <item type="button" id="btn_save" text="<i class=\'fa fa-floppy-o fa-fw\'></i>" title="Рассчитать и записать данные"/>\r\n <item type="button" id="btn_post" enabled="false" text="<i class=\'fa fa-check-square-o fa-fw\'></i>" title="Провести документ" />\r\n <item type="button" id="btn_unpost" enabled="false" text="<i class=\'fa fa-square-o fa-fw\'></i>" title="Отмена проведения" />\r\n\r\n <item type="button" id="btn_files" text="<i class=\'fa fa-paperclip fa-fw\'></i>" title="Присоединенные файлы"/>\r\n\r\n <item type="buttonSelect" id="bs_print" text="<i class=\'fa fa-print fa-fw\'></i>" title="Печать" openAll="true">\r\n </item>\r\n\r\n <item type="buttonSelect" id="bs_create_by_virtue" text="<i class=\'fa fa-bolt fa-fw\'></i>" title="Создать на основании" openAll="true" >\r\n <item type="button" id="btn_message" enabled="false" text="Сообщение" />\r\n </item>\r\n\r\n <item type="buttonSelect" id="bs_go_to" text="<i class=\'fa fa-external-link fa-fw\'></i>" title="Перейти" openAll="true" >\r\n <item type="button" id="btn_go_connection" enabled="false" text="Связи" />\r\n </item>\r\n\r\n <item type="buttonSelect" id="bs_more" text="<i class=\'fa fa-th-large fa-fw\'></i>" title="Дополнительно" openAll="true">\r\n\r\n <item type="button" id="btn_import" text="<i class=\'fa fa-upload fa-fw\'></i> Загрузить из файла" />\r\n <item type="button" id="btn_export" text="<i class=\'fa fa-download fa-fw\'></i> Выгрузить в файл" />\r\n </item>\r\n\r\n <item id="sep1" type="separator"/>\r\n <item type="button" id="btn_close" text="<i class=\'fa fa-times fa-fw\'></i>" title="Закрыть форму"/>\r\n <item id="sep2" type="separator"/>\r\n\r\n</toolbar>\r\n',"toolbar_ok_cancel.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n <item id="btn_ok" type="button" img="" imgdis="" text="<b>Ок</b>" />\r\n <item id="btn_cancel" type="button"\timg="" imgdis="" text="Отмена" />\r\n</toolbar>',"toolbar_rep.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n <item id="sep0" type="separator"/>\r\n <item type="button" id="btn_run" text="<i class=\'fa fa-play fa-fw\'></i> Сформировать" title="Сформировать отчет"/>\r\n\r\n <item type="buttonSelect" id="bs_more" text="<i class=\'fa fa-th-large fa-fw\'></i>" title="Дополнительно" openAll="true">\r\n\r\n <item type="button" id="btn_print" text="<i class=\'fa fa-print fa-fw\'></i> Печать" />\r\n\r\n <item id="sep3" type="separator"/>\r\n\r\n <item type="button" id="btn_export" text="<i class=\'fa fa-file-excel-o fa-fw\'></i> Выгрузить в файл" />\r\n\r\n <item id="sep4" type="separator"/>\r\n\r\n <item type="button" id="btn_import" text="<i class=\'fa fa-folder-open-o fa-fw\'></i> Выбрать вариант" />\r\n <item type="button" id="btn_export" text="<i class=\'fa fa-floppy-o fa-fw\'></i> Сохранить вариант" />\r\n\r\n </item>\r\n\r\n <item id="sep1" type="separator"/>\r\n\r\n</toolbar>\r\n',"toolbar_selection.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n\r\n <item id="sep0" type="separator"/>\r\n\r\n <item id="btn_select" type="button" title="Выбрать элемент списка" text="<b>Выбрать</b>" />\r\n\r\n <item id="sep1" type="separator"/>\r\n <item id="btn_new" type="button"\ttext="<i class=\'fa fa-plus-circle fa-fw\'></i>"\ttitle="Создать" />\r\n <item id="btn_edit" type="button"\ttext="<i class=\'fa fa-pencil fa-fw\'></i>"\ttitle="Изменить" />\r\n <item id="btn_delete" type="button"\ttext="<i class=\'fa fa-times fa-fw\'></i>"\ttitle="Удалить" />\r\n <item id="sep2" type="separator"/>\r\n\r\n <item type="buttonSelect" id="bs_print" text="<i class=\'fa fa-print fa-fw\'></i> Печать" openAll="true" >\r\n </item>\r\n\r\n <item type="buttonSelect" id="bs_more" text="<i class=\'fa fa-th-large fa-fw\'></i>" title="Дополнительно" openAll="true">\r\n <item id="btn_requery" type="button"\ttext="<i class=\'fa fa-refresh fa-fw\'></i> Обновить список" />\r\n </item>\r\n\r\n <item id="sep3" type="separator"/>\r\n\r\n</toolbar>'});var xmlToJSON=function(){this.version="1.3";var e={mergeCDATA:!0,grokAttr:!0,grokText:!0,normalize:!0,xmlns:!0,namespaceKey:"_ns",textKey:"_text",valueKey:"_value",attrKey:"_attr",cdataKey:"_cdata",attrsAsObject:!0,stripAttrPrefix:!0,stripElemPrefix:!0,childrenAsArray:!0},t=new RegExp(/(?!xmlns)^.*:/),n=new RegExp(/^\s+|\s+$/g);return this.grokType=function(e){return/^\s*$/.test(e)?null:/^(?:true|false)$/i.test(e)?"true"===e.toLowerCase():isFinite(e)?parseFloat(e):e},this.parseString=function(e,t){return this.parseXML(this.stringToXML(e),t)},this.parseXML=function(a,i){for(var s in i)e[s]=i[s];var o={},r=0,l="";if(e.xmlns&&a.namespaceURI&&(o[e.namespaceKey]=a.namespaceURI),a.attributes&&a.attributes.length>0){var c={};for(r;r<a.attributes.length;r++){var p=a.attributes.item(r);f={};var d="";d=e.stripAttrPrefix?p.name.replace(t,""):p.name,e.grokAttr?f[e.valueKey]=this.grokType(p.value.replace(n,"")):f[e.valueKey]=p.value.replace(n,""),e.xmlns&&p.namespaceURI&&(f[e.namespaceKey]=p.namespaceURI),e.attrsAsObject?c[d]=f:o[e.attrKey+d]=f}e.attrsAsObject&&(o[e.attrKey]=c)}if(a.hasChildNodes())for(var u,m,f,h=0;h<a.childNodes.length;h++)u=a.childNodes.item(h),4===u.nodeType?e.mergeCDATA?l+=u.nodeValue:o.hasOwnProperty(e.cdataKey)?(o[e.cdataKey].constructor!==Array&&(o[e.cdataKey]=[o[e.cdataKey]]),o[e.cdataKey].push(u.nodeValue)):e.childrenAsArray?(o[e.cdataKey]=[],o[e.cdataKey].push(u.nodeValue)):o[e.cdataKey]=u.nodeValue:3===u.nodeType?l+=u.nodeValue:1===u.nodeType&&(0===r&&(o={}), +m=e.stripElemPrefix?u.nodeName.replace(t,""):u.nodeName,f=xmlToJSON.parseXML(u),o.hasOwnProperty(m)?(o[m].constructor!==Array&&(o[m]=[o[m]]),o[m].push(f)):(e.childrenAsArray?(o[m]=[],o[m].push(f)):o[m]=f,r++));else l||(e.childrenAsArray?(o[e.textKey]=[],o[e.textKey].push(null)):o[e.textKey]=null);if(l)if(e.grokText){var _=this.grokType(l.replace(n,""));null!==_&&void 0!==_&&(o[e.textKey]=_)}else e.normalize?o[e.textKey]=l.replace(n,"").replace(/\s+/g," "):o[e.textKey]=l.replace(n,"");return o},this.xmlToString=function(e){try{var t=e.xml?e.xml:(new XMLSerializer).serializeToString(e);return t}catch(e){return null}},this.stringToXML=function(e){try{var t=null;if(window.DOMParser){var n=new DOMParser;return t=n.parseFromString(e,"text/xml")}return t=new ActiveXObject("Microsoft.XMLDOM"),t.async=!1,t.loadXML(e),t}catch(e){return null}},this}();"undefined"!=typeof module&&null!==module&&module.exports?module.exports=xmlToJSON:"function"==typeof define&&define.amd&&define(function(){return xmlToJSON});/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ +var saveAs=saveAs||function(e){"use strict";if(!("undefined"==typeof e||"undefined"!=typeof navigator&&/MSIE [1-9]\./.test(navigator.userAgent))){var t=e.document,n=function(){return e.URL||e.webkitURL||e},a=t.createElementNS("http://www.w3.org/1999/xhtml","a"),i="download"in a,s=function(e){var t=new MouseEvent("click");e.dispatchEvent(t)},o=/constructor/i.test(e.HTMLElement),r=/CriOS\/[\d]+/.test(navigator.userAgent),l=function(t){(e.setImmediate||e.setTimeout)(function(){throw t},0)},c="application/octet-stream",p=4e4,d=function(e){var t=function(){"string"==typeof e?n().revokeObjectURL(e):e.remove()};setTimeout(t,p)},u=function(e,t,n){t=[].concat(t);for(var a=t.length;a--;){var i=e["on"+t[a]];if("function"==typeof i)try{i.call(e,n||e)}catch(e){l(e)}}},m=function(e){return/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob([String.fromCharCode(65279),e],{type:e.type}):e},f=function(t,l,p){p||(t=m(t));var f,h=this,_=t.type,g=_===c,b=function(){u(h,"writestart progress write writeend".split(" "))},v=function(){if((r||g&&o)&&e.FileReader){var a=new FileReader;return a.onloadend=function(){var t=r?a.result:a.result.replace(/^data:[^;]*;/,"data:attachment/file;"),n=e.open(t,"_blank");n||(e.location.href=t),t=void 0,h.readyState=h.DONE,b()},a.readAsDataURL(t),void(h.readyState=h.INIT)}if(f||(f=n().createObjectURL(t)),g)e.location.href=f;else{var i=e.open(f,"_blank");i||(e.location.href=f)}h.readyState=h.DONE,b(),d(f)};return h.readyState=h.INIT,i?(f=n().createObjectURL(t),void setTimeout(function(){a.href=f,a.download=l,s(a),b(),d(f),h.readyState=h.DONE})):void v()},h=f.prototype,_=function(e,t,n){return new f(e,t||e.name||"download",n)};return"undefined"!=typeof navigator&&navigator.msSaveOrOpenBlob?function(e,t,n){return t=t||e.name||"download",n||(e=m(e)),navigator.msSaveOrOpenBlob(e,t)}:(h.abort=function(){},h.readyState=h.INIT=0,h.WRITING=1,h.DONE=2,h.error=h.onwritestart=h.onprogress=h.onwrite=h.onabort=h.onerror=h.onwriteend=null,_)}}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||this.content);/*! * @version: 2.1.24 * @author: Dan Grossman http://www.dangrossman.info/ * @copyright: Copyright (c) 2012-2016 Dan Grossman. All rights reserved. @@ -21,6 +22,6 @@ var saveAs=saveAs||function(e){"use strict";if(!("undefined"==typeof e||"undefin * Copyright(c) 2014 Jonathan Ong * MIT Licensed */ -return"undefined"!=typeof module&&module.exports?module.exports.saveAs=saveAs:"undefined"!=typeof define&&null!==define&&null!==define.amd&&define([],function(){return saveAs}),"undefined"!=typeof module&&module.exports&&(module.exports=Aes),function(){"use strict";var e=[["","один","два","три","четыре","пять","шесть","семь","восемь","девять","десять","одиннадцать","двенадцать","тринадцать","четырнадцать","пятнадцать","шестнадцать","семнадцать","восемнадцать","девятнадцать"],["","","двадцать","тридцать","сорок","пятьдесят","шестьдесят","семьдесят","восемьдесят","девяносто"],["","сто","двести","триста","четыреста","пятьсот","шестьсот","семьсот","восемьсот","девятьсот"]],t=function(e){return parseFloat(e)},n=function(e,t){if(3!==t.length)return!1;e=Math.abs(e)%100;var n=e%10;return e>10&&e<20?t[2]:n>1&&n<5?t[1]:1===n?t[0]:t[2]},a=function(a,i){var s,o,r="";return 3===a.length&&(s=a.substr(0,1),a=a.substr(1,3),r=""+e[2][s]+" "),a<20?r=r+e[0][t(a)]+" ":(s=a.substr(0,1),o=a.substr(1,2),r=r+e[1][s]+" "+e[0][o]+" "),0===i?r+=n(a,["рубль","рубля","рублей"]):1===i?" "!==r&&(r+=n(a,["тысяча ","тысячи ","тысяч "]),r=r.replace("один ","одна ").replace("два ","две ")):2===i?" "!==r&&(r+=n(a,["миллион ","миллиона ","миллионов "])):3===i&&(r+=n(a,["миллиард ","миллиарда ","миллиардов "])),r},i=function(e){var t=n(e,["копейка","копейки","копеек"]);return 0===e?e="00":e<10&&(e="0"+e)," "+e+" "+t},s=function(e){if(!e)return!1;var n=typeof e;if("number"!==n&&"string"!==n)return!1;if("string"===n&&(e=t(e.replace(",",".")),isNaN(e)))return!1;if(e<=0)return!1;var s,o;e=e.toFixed(2),e.indexOf(".")!==-1&&(s=e.split("."),e=s[0],o=s[1]);for(var r,l="",c=e.length-1,p="",d=0;c>=0;)r=e.substr(c,1),p=r+p,3!==p.length&&0!==c||isNaN(t(p))||(l=a(p,d)+l,p="",d++),c--;return l=l.replace(/\s+/g," "),o&&(l+=i(t(o))),l};Number.prototype.in_words||(Number.prototype.in_words=function(){return s(this)})}(),function(e,t){if("function"==typeof define&&define.amd)define(["moment","jquery"],function(n,a){return e.daterangepicker=t(n,a)});else if("object"==typeof module&&module.exports){var n="undefined"!=typeof window?window.jQuery:void 0;n||(n=require("jquery"),n.fn||(n.fn={})),module.exports=t(require("moment"),n)}else e.daterangepicker=t(e.moment,e.jQuery)}(this,function(e,t){var n=function(n,a,i){if(this.parentEl="body",this.element=t(n),this.startDate=e().startOf("day"),this.endDate=e().endOf("day"),this.minDate=!1,this.maxDate=!1,this.dateLimit=!1,this.autoApply=!1,this.singleDatePicker=!1,this.showDropdowns=!1,this.showWeekNumbers=!1,this.showISOWeekNumbers=!1,this.showCustomRangeLabel=!0,this.timePicker=!1,this.timePicker24Hour=!1,this.timePickerIncrement=1,this.timePickerSeconds=!1,this.linkedCalendars=!0,this.autoUpdateInput=!0,this.alwaysShowCalendars=!1,this.ranges={},this.opens="right",this.element.hasClass("pull-right")&&(this.opens="left"),this.drops="down",this.element.hasClass("dropup")&&(this.drops="up"),this.buttonClasses="btn btn-sm",this.applyClass="btn-success",this.cancelClass="btn-default",this.locale={direction:"ltr",format:"DD.MM.YYYY",separator:" - ",applyLabel:"Применить",cancelLabel:"Отмена",weekLabel:"W",customRangeLabel:"Произвольные даты",daysOfWeek:e.weekdaysMin(),monthNames:e.monthsShort(),firstDay:e.localeData().firstDayOfWeek()},this.callback=function(){},this.isShowing=!1,this.leftCalendar={},this.rightCalendar={},"object"==typeof a&&null!==a||(a={}),a=t.extend(this.element.data(),a),"string"==typeof a.template||a.template instanceof t||(a.template='<div class="daterangepicker dropdown-menu"><div class="calendar left"><div class="daterangepicker_input"><input class="input-mini form-control" type="text" name="daterangepicker_start" value="" /><i class="fa fa-calendar glyphicon glyphicon-calendar"></i><div class="calendar-time"><div></div><i class="fa fa-clock-o glyphicon glyphicon-time"></i></div></div><div class="calendar-table"></div></div><div class="calendar right"><div class="daterangepicker_input"><input class="input-mini form-control" type="text" name="daterangepicker_end" value="" /><i class="fa fa-calendar glyphicon glyphicon-calendar"></i><div class="calendar-time"><div></div><i class="fa fa-clock-o glyphicon glyphicon-time"></i></div></div><div class="calendar-table"></div></div><div class="ranges"><div class="range_inputs"><button class="applyBtn" disabled="disabled" type="button"></button> <button class="cancelBtn" type="button"></button></div></div></div>'),this.parentEl=t(a.parentEl&&t(a.parentEl).length?a.parentEl:this.parentEl),this.container=t(a.template).appendTo(this.parentEl),"object"==typeof a.locale&&("string"==typeof a.locale.direction&&(this.locale.direction=a.locale.direction),"string"==typeof a.locale.format&&(this.locale.format=a.locale.format),"string"==typeof a.locale.separator&&(this.locale.separator=a.locale.separator),"object"==typeof a.locale.daysOfWeek&&(this.locale.daysOfWeek=a.locale.daysOfWeek.slice()),"object"==typeof a.locale.monthNames&&(this.locale.monthNames=a.locale.monthNames.slice()),"number"==typeof a.locale.firstDay&&(this.locale.firstDay=a.locale.firstDay),"string"==typeof a.locale.applyLabel&&(this.locale.applyLabel=a.locale.applyLabel),"string"==typeof a.locale.cancelLabel&&(this.locale.cancelLabel=a.locale.cancelLabel),"string"==typeof a.locale.weekLabel&&(this.locale.weekLabel=a.locale.weekLabel),"string"==typeof a.locale.customRangeLabel&&(this.locale.customRangeLabel=a.locale.customRangeLabel)),this.container.addClass(this.locale.direction),"string"==typeof a.startDate&&(this.startDate=e(a.startDate,this.locale.format)),"string"==typeof a.endDate&&(this.endDate=e(a.endDate,this.locale.format)),"string"==typeof a.minDate&&(this.minDate=e(a.minDate,this.locale.format)),"string"==typeof a.maxDate&&(this.maxDate=e(a.maxDate,this.locale.format)),"object"==typeof a.startDate&&(this.startDate=e(a.startDate)),"object"==typeof a.endDate&&(this.endDate=e(a.endDate)),"object"==typeof a.minDate&&(this.minDate=e(a.minDate)),"object"==typeof a.maxDate&&(this.maxDate=e(a.maxDate)),this.minDate&&this.startDate.isBefore(this.minDate)&&(this.startDate=this.minDate.clone()),this.maxDate&&this.endDate.isAfter(this.maxDate)&&(this.endDate=this.maxDate.clone()),"string"==typeof a.applyClass&&(this.applyClass=a.applyClass),"string"==typeof a.cancelClass&&(this.cancelClass=a.cancelClass),"object"==typeof a.dateLimit&&(this.dateLimit=a.dateLimit),"string"==typeof a.opens&&(this.opens=a.opens),"string"==typeof a.drops&&(this.drops=a.drops),"boolean"==typeof a.showWeekNumbers&&(this.showWeekNumbers=a.showWeekNumbers),"boolean"==typeof a.showISOWeekNumbers&&(this.showISOWeekNumbers=a.showISOWeekNumbers),"string"==typeof a.buttonClasses&&(this.buttonClasses=a.buttonClasses),"object"==typeof a.buttonClasses&&(this.buttonClasses=a.buttonClasses.join(" ")),"boolean"==typeof a.showDropdowns&&(this.showDropdowns=a.showDropdowns),"boolean"==typeof a.showCustomRangeLabel&&(this.showCustomRangeLabel=a.showCustomRangeLabel),"boolean"==typeof a.singleDatePicker&&(this.singleDatePicker=a.singleDatePicker,this.singleDatePicker&&(this.endDate=this.startDate.clone())),"boolean"==typeof a.timePicker&&(this.timePicker=a.timePicker),"boolean"==typeof a.timePickerSeconds&&(this.timePickerSeconds=a.timePickerSeconds),"number"==typeof a.timePickerIncrement&&(this.timePickerIncrement=a.timePickerIncrement),"boolean"==typeof a.timePicker24Hour&&(this.timePicker24Hour=a.timePicker24Hour),"boolean"==typeof a.autoApply&&(this.autoApply=a.autoApply),"boolean"==typeof a.autoUpdateInput&&(this.autoUpdateInput=a.autoUpdateInput),"boolean"==typeof a.linkedCalendars&&(this.linkedCalendars=a.linkedCalendars),"function"==typeof a.isInvalidDate&&(this.isInvalidDate=a.isInvalidDate),"function"==typeof a.isCustomDate&&(this.isCustomDate=a.isCustomDate),"boolean"==typeof a.alwaysShowCalendars&&(this.alwaysShowCalendars=a.alwaysShowCalendars),0!=this.locale.firstDay)for(var s=this.locale.firstDay;s>0;)this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift()),s--;var o,r,l;if("undefined"==typeof a.startDate&&"undefined"==typeof a.endDate&&t(this.element).is("input[type=text]")){var c=t(this.element).val(),p=c.split(this.locale.separator);o=r=null,2==p.length?(o=e(p[0],this.locale.format),r=e(p[1],this.locale.format)):this.singleDatePicker&&""!==c&&(o=e(c,this.locale.format),r=e(c,this.locale.format)),null!==o&&null!==r&&(this.setStartDate(o),this.setEndDate(r))}if("object"==typeof a.ranges){for(l in a.ranges){o="string"==typeof a.ranges[l][0]?e(a.ranges[l][0],this.locale.format):e(a.ranges[l][0]),r="string"==typeof a.ranges[l][1]?e(a.ranges[l][1],this.locale.format):e(a.ranges[l][1]),this.minDate&&o.isBefore(this.minDate)&&(o=this.minDate.clone());var d=this.maxDate;if(this.dateLimit&&d&&o.clone().add(this.dateLimit).isAfter(d)&&(d=o.clone().add(this.dateLimit)),d&&r.isAfter(d)&&(r=d.clone()),!(this.minDate&&r.isBefore(this.minDate,this.timepicker?"minute":"day")||d&&o.isAfter(d,this.timepicker?"minute":"day"))){var u=document.createElement("textarea");u.innerHTML=l;var f=u.value;this.ranges[f]=[o,r]}}var m="<ul>";for(l in this.ranges)m+='<li data-range-key="'+l+'">'+l+"</li>";this.showCustomRangeLabel&&(m+='<li data-range-key="'+this.locale.customRangeLabel+'">'+this.locale.customRangeLabel+"</li>"),m+="</ul>",this.container.find(".ranges").prepend(m)}"function"==typeof i&&(this.callback=i),this.timePicker||(this.startDate=this.startDate.startOf("day"),this.endDate=this.endDate.endOf("day"),this.container.find(".calendar-time").hide()),this.timePicker&&this.autoApply&&(this.autoApply=!1),this.autoApply&&"object"!=typeof a.ranges?this.container.find(".ranges").hide():this.autoApply&&this.container.find(".applyBtn, .cancelBtn").addClass("hide"),this.singleDatePicker&&(this.container.addClass("single"),this.container.find(".calendar.left").addClass("single"),this.container.find(".calendar.left").show(),this.container.find(".calendar.right").hide(),this.container.find(".daterangepicker_input input, .daterangepicker_input > i").hide(),this.timePicker?this.container.find(".ranges ul").hide():this.container.find(".ranges").hide()),("undefined"==typeof a.ranges&&!this.singleDatePicker||this.alwaysShowCalendars)&&this.container.addClass("show-calendar"),this.container.addClass("opens"+this.opens),"undefined"!=typeof a.ranges&&"right"==this.opens&&this.container.find(".ranges").prependTo(this.container.find(".calendar.left").parent()),this.container.find(".applyBtn, .cancelBtn").addClass(this.buttonClasses),this.applyClass.length&&this.container.find(".applyBtn").addClass(this.applyClass),this.cancelClass.length&&this.container.find(".cancelBtn").addClass(this.cancelClass),this.container.find(".applyBtn").html(this.locale.applyLabel),this.container.find(".cancelBtn").html(this.locale.cancelLabel),this.container.find(".calendar").on("click.daterangepicker",".prev",t.proxy(this.clickPrev,this)).on("click.daterangepicker",".next",t.proxy(this.clickNext,this)).on("mousedown.daterangepicker","td.available",t.proxy(this.clickDate,this)).on("mouseenter.daterangepicker","td.available",t.proxy(this.hoverDate,this)).on("mouseleave.daterangepicker","td.available",t.proxy(this.updateFormInputs,this)).on("change.daterangepicker","select.yearselect",t.proxy(this.monthOrYearChanged,this)).on("change.daterangepicker","select.monthselect",t.proxy(this.monthOrYearChanged,this)).on("change.daterangepicker","select.hourselect,select.minuteselect,select.secondselect,select.ampmselect",t.proxy(this.timeChanged,this)).on("click.daterangepicker",".daterangepicker_input input",t.proxy(this.showCalendars,this)).on("focus.daterangepicker",".daterangepicker_input input",t.proxy(this.formInputsFocused,this)).on("blur.daterangepicker",".daterangepicker_input input",t.proxy(this.formInputsBlurred,this)).on("change.daterangepicker",".daterangepicker_input input",t.proxy(this.formInputsChanged,this)),this.container.find(".ranges").on("click.daterangepicker","button.applyBtn",t.proxy(this.clickApply,this)).on("click.daterangepicker","button.cancelBtn",t.proxy(this.clickCancel,this)).on("click.daterangepicker","li",t.proxy(this.clickRange,this)).on("mouseenter.daterangepicker","li",t.proxy(this.hoverRange,this)).on("mouseleave.daterangepicker","li",t.proxy(this.updateFormInputs,this)),this.element.is("input")||this.element.is("button")?this.element.on({"click.daterangepicker":t.proxy(this.show,this),"focus.daterangepicker":t.proxy(this.show,this),"keyup.daterangepicker":t.proxy(this.elementChanged,this),"keydown.daterangepicker":t.proxy(this.keydown,this)}):this.element.on("click.daterangepicker",t.proxy(this.toggle,this)),this.element.is("input")&&!this.singleDatePicker&&this.autoUpdateInput?(this.element.val(this.startDate.format(this.locale.format)+this.locale.separator+this.endDate.format(this.locale.format)),this.element.trigger("change")):this.element.is("input")&&this.autoUpdateInput&&(this.element.val(this.startDate.format(this.locale.format)),this.element.trigger("change"))};return n.prototype={constructor:n,setStartDate:function(t){"string"==typeof t&&(this.startDate=e(t,this.locale.format)),"object"==typeof t&&(this.startDate=e(t)),this.timePicker||(this.startDate=this.startDate.startOf("day")),this.timePicker&&this.timePickerIncrement&&this.startDate.minute(Math.round(this.startDate.minute()/this.timePickerIncrement)*this.timePickerIncrement),this.minDate&&this.startDate.isBefore(this.minDate)&&(this.startDate=this.minDate,this.timePicker&&this.timePickerIncrement&&this.startDate.minute(Math.round(this.startDate.minute()/this.timePickerIncrement)*this.timePickerIncrement)),this.maxDate&&this.startDate.isAfter(this.maxDate)&&(this.startDate=this.maxDate,this.timePicker&&this.timePickerIncrement&&this.startDate.minute(Math.floor(this.startDate.minute()/this.timePickerIncrement)*this.timePickerIncrement)),this.isShowing||this.updateElement(),this.updateMonthsInView()},setEndDate:function(t){"string"==typeof t&&(this.endDate=e(t,this.locale.format)),"object"==typeof t&&(this.endDate=e(t)),this.timePicker||(this.endDate=this.endDate.endOf("day")),this.timePicker&&this.timePickerIncrement&&this.endDate.minute(Math.round(this.endDate.minute()/this.timePickerIncrement)*this.timePickerIncrement),this.endDate.isBefore(this.startDate)&&(this.endDate=this.startDate.clone()),this.maxDate&&this.endDate.isAfter(this.maxDate)&&(this.endDate=this.maxDate),this.dateLimit&&this.startDate.clone().add(this.dateLimit).isBefore(this.endDate)&&(this.endDate=this.startDate.clone().add(this.dateLimit)),this.previousRightTime=this.endDate.clone(),this.isShowing||this.updateElement(),this.updateMonthsInView()},isInvalidDate:function(){return!1},isCustomDate:function(){return!1},updateView:function(){this.timePicker&&(this.renderTimePicker("left"),this.renderTimePicker("right"),this.endDate?this.container.find(".right .calendar-time select").removeAttr("disabled").removeClass("disabled"):this.container.find(".right .calendar-time select").attr("disabled","disabled").addClass("disabled")),this.endDate?(this.container.find('input[name="daterangepicker_end"]').removeClass("active"),this.container.find('input[name="daterangepicker_start"]').addClass("active")):(this.container.find('input[name="daterangepicker_end"]').addClass("active"),this.container.find('input[name="daterangepicker_start"]').removeClass("active")),this.updateMonthsInView(),this.updateCalendars(),this.updateFormInputs()},updateMonthsInView:function(){if(this.endDate){if(!this.singleDatePicker&&this.leftCalendar.month&&this.rightCalendar.month&&(this.startDate.format("YYYY-MM")==this.leftCalendar.month.format("YYYY-MM")||this.startDate.format("YYYY-MM")==this.rightCalendar.month.format("YYYY-MM"))&&(this.endDate.format("YYYY-MM")==this.leftCalendar.month.format("YYYY-MM")||this.endDate.format("YYYY-MM")==this.rightCalendar.month.format("YYYY-MM")))return;this.leftCalendar.month=this.startDate.clone().date(2),this.linkedCalendars||this.endDate.month()==this.startDate.month()&&this.endDate.year()==this.startDate.year()?this.rightCalendar.month=this.startDate.clone().date(2).add(1,"month"):this.rightCalendar.month=this.endDate.clone().date(2)}else this.leftCalendar.month.format("YYYY-MM")!=this.startDate.format("YYYY-MM")&&this.rightCalendar.month.format("YYYY-MM")!=this.startDate.format("YYYY-MM")&&(this.leftCalendar.month=this.startDate.clone().date(2),this.rightCalendar.month=this.startDate.clone().date(2).add(1,"month"));this.maxDate&&this.linkedCalendars&&!this.singleDatePicker&&this.rightCalendar.month>this.maxDate&&(this.rightCalendar.month=this.maxDate.clone().date(2),this.leftCalendar.month=this.maxDate.clone().date(2).subtract(1,"month"))},updateCalendars:function(){if(this.timePicker){var e,t,n;if(this.endDate){if(e=parseInt(this.container.find(".left .hourselect").val(),10),t=parseInt(this.container.find(".left .minuteselect").val(),10),n=this.timePickerSeconds?parseInt(this.container.find(".left .secondselect").val(),10):0,!this.timePicker24Hour){var a=this.container.find(".left .ampmselect").val();"PM"===a&&e<12&&(e+=12),"AM"===a&&12===e&&(e=0)}}else if(e=parseInt(this.container.find(".right .hourselect").val(),10),t=parseInt(this.container.find(".right .minuteselect").val(),10),n=this.timePickerSeconds?parseInt(this.container.find(".right .secondselect").val(),10):0,!this.timePicker24Hour){var a=this.container.find(".right .ampmselect").val();"PM"===a&&e<12&&(e+=12),"AM"===a&&12===e&&(e=0)}this.leftCalendar.month.hour(e).minute(t).second(n),this.rightCalendar.month.hour(e).minute(t).second(n)}this.renderCalendar("left"),this.renderCalendar("right"),this.container.find(".ranges li").removeClass("active"),null!=this.endDate&&this.calculateChosenLabel()},renderCalendar:function(n){var a="left"==n?this.leftCalendar:this.rightCalendar,i=a.month.month(),s=a.month.year(),o=a.month.hour(),r=a.month.minute(),l=a.month.second(),c=e([s,i]).daysInMonth(),p=e([s,i,1]),d=e([s,i,c]),u=e(p).subtract(1,"month").month(),f=e(p).subtract(1,"month").year(),m=e([f,u]).daysInMonth(),h=p.day(),a=[];a.firstDay=p,a.lastDay=d;for(var _=0;_<6;_++)a[_]=[];var g=m-h+this.locale.firstDay+1;g>m&&(g-=7),h==this.locale.firstDay&&(g=m-6);for(var b,v,x=e([f,u,g,12,r,l]),_=0,b=0,v=0;_<42;_++,b++,x=e(x).add(24,"hour"))_>0&&b%7===0&&(b=0,v++),a[v][b]=x.clone().hour(o).minute(r).second(l),x.hour(12),this.minDate&&a[v][b].format("YYYY-MM-DD")==this.minDate.format("YYYY-MM-DD")&&a[v][b].isBefore(this.minDate)&&"left"==n&&(a[v][b]=this.minDate.clone()),this.maxDate&&a[v][b].format("YYYY-MM-DD")==this.maxDate.format("YYYY-MM-DD")&&a[v][b].isAfter(this.maxDate)&&"right"==n&&(a[v][b]=this.maxDate.clone());"left"==n?this.leftCalendar.calendar=a:this.rightCalendar.calendar=a;var y="left"==n?this.minDate:this.startDate,w=this.maxDate,k=("left"==n?this.startDate:this.endDate,"ltr"==this.locale.direction?{left:"chevron-left",right:"chevron-right"}:{left:"chevron-right",right:"chevron-left"}),$='<table class="table-condensed">';$+="<thead>",$+="<tr>",(this.showWeekNumbers||this.showISOWeekNumbers)&&($+="<th></th>"),$+=y&&!y.isBefore(a.firstDay)||this.linkedCalendars&&"left"!=n?"<th></th>":'<th class="prev available"><i class="fa fa-'+k.left+" glyphicon glyphicon-"+k.left+'"></i></th>';var j=this.locale.monthNames[a[1][1].month()]+a[1][1].format(" YYYY");if(this.showDropdowns){for(var D=a[1][1].month(),O=a[1][1].year(),C=w&&w.year()||O+5,E=y&&y.year()||O-50,M=O==E,S=O==C,T='<select class="monthselect">',P=0;P<12;P++)T+=(!M||P>=y.month())&&(!S||P<=w.month())?"<option value='"+P+"'"+(P===D?" selected='selected'":"")+">"+this.locale.monthNames[P]+"</option>":"<option value='"+P+"'"+(P===D?" selected='selected'":"")+" disabled='disabled'>"+this.locale.monthNames[P]+"</option>";T+="</select>";for(var I='<select class="yearselect">',L=E;L<=C;L++)I+='<option value="'+L+'"'+(L===O?' selected="selected"':"")+">"+L+"</option>";I+="</select>",j=T+I}if($+='<th colspan="5" class="month">'+j+"</th>",$+=w&&!w.isAfter(a.lastDay)||this.linkedCalendars&&"right"!=n&&!this.singleDatePicker?"<th></th>":'<th class="next available"><i class="fa fa-'+k.right+" glyphicon glyphicon-"+k.right+'"></i></th>',$+="</tr>",$+="<tr>",(this.showWeekNumbers||this.showISOWeekNumbers)&&($+='<th class="week">'+this.locale.weekLabel+"</th>"),t.each(this.locale.daysOfWeek,function(e,t){$+="<th>"+t+"</th>"}),$+="</tr>",$+="</thead>",$+="<tbody>",null==this.endDate&&this.dateLimit){var A=this.startDate.clone().add(this.dateLimit).endOf("day");w&&!A.isBefore(w)||(w=A)}for(var v=0;v<6;v++){$+="<tr>",this.showWeekNumbers?$+='<td class="week">'+a[v][0].week()+"</td>":this.showISOWeekNumbers&&($+='<td class="week">'+a[v][0].isoWeek()+"</td>");for(var b=0;b<7;b++){var q=[];a[v][b].isSame(new Date,"day")&&q.push("today"),a[v][b].isoWeekday()>5&&q.push("weekend"),a[v][b].month()!=a[1][1].month()&&q.push("off"),this.minDate&&a[v][b].isBefore(this.minDate,"day")&&q.push("off","disabled"),w&&a[v][b].isAfter(w,"day")&&q.push("off","disabled"),this.isInvalidDate(a[v][b])&&q.push("off","disabled"),a[v][b].format("YYYY-MM-DD")==this.startDate.format("YYYY-MM-DD")&&q.push("active","start-date"),null!=this.endDate&&a[v][b].format("YYYY-MM-DD")==this.endDate.format("YYYY-MM-DD")&&q.push("active","end-date"),null!=this.endDate&&a[v][b]>this.startDate&&a[v][b]<this.endDate&&q.push("in-range");var R=this.isCustomDate(a[v][b]);R!==!1&&("string"==typeof R?q.push(R):Array.prototype.push.apply(q,R));for(var N="",Y=!1,_=0;_<q.length;_++)N+=q[_]+" ","disabled"==q[_]&&(Y=!0);Y||(N+="available"),$+='<td class="'+N.replace(/^\s+|\s+$/g,"")+'" data-title="r'+v+"c"+b+'">'+a[v][b].date()+"</td>"}$+="</tr>"}$+="</tbody>",$+="</table>",this.container.find(".calendar."+n+" .calendar-table").html($)},renderTimePicker:function(e){if("right"!=e||this.endDate){var t,n,a,i=this.maxDate;if(!this.dateLimit||this.maxDate&&!this.startDate.clone().add(this.dateLimit).isAfter(this.maxDate)||(i=this.startDate.clone().add(this.dateLimit)),"left"==e)n=this.startDate.clone(),a=this.minDate;else if("right"==e){n=this.endDate.clone(),a=this.startDate;var s=this.container.find(".calendar.right .calendar-time div");if(!this.endDate&&""!=s.html()&&(n.hour(s.find(".hourselect option:selected").val()||n.hour()),n.minute(s.find(".minuteselect option:selected").val()||n.minute()),n.second(s.find(".secondselect option:selected").val()||n.second()),!this.timePicker24Hour)){var o=s.find(".ampmselect option:selected").val();"PM"===o&&n.hour()<12&&n.hour(n.hour()+12),"AM"===o&&12===n.hour()&&n.hour(0)}n.isBefore(this.startDate)&&(n=this.startDate.clone()),i&&n.isAfter(i)&&(n=i.clone())}t='<select class="hourselect">';for(var r=this.timePicker24Hour?0:1,l=this.timePicker24Hour?23:12,c=r;c<=l;c++){var p=c;this.timePicker24Hour||(p=n.hour()>=12?12==c?12:c+12:12==c?0:c);var d=n.clone().hour(p),u=!1;a&&d.minute(59).isBefore(a)&&(u=!0),i&&d.minute(0).isAfter(i)&&(u=!0),t+=p!=n.hour()||u?u?'<option value="'+c+'" disabled="disabled" class="disabled">'+c+"</option>":'<option value="'+c+'">'+c+"</option>":'<option value="'+c+'" selected="selected">'+c+"</option>"}t+="</select> ",t+=': <select class="minuteselect">';for(var c=0;c<60;c+=this.timePickerIncrement){var f=c<10?"0"+c:c,d=n.clone().minute(c),u=!1;a&&d.second(59).isBefore(a)&&(u=!0),i&&d.second(0).isAfter(i)&&(u=!0),t+=n.minute()!=c||u?u?'<option value="'+c+'" disabled="disabled" class="disabled">'+f+"</option>":'<option value="'+c+'">'+f+"</option>":'<option value="'+c+'" selected="selected">'+f+"</option>"}if(t+="</select> ",this.timePickerSeconds){t+=': <select class="secondselect">';for(var c=0;c<60;c++){var f=c<10?"0"+c:c,d=n.clone().second(c),u=!1;a&&d.isBefore(a)&&(u=!0),i&&d.isAfter(i)&&(u=!0),t+=n.second()!=c||u?u?'<option value="'+c+'" disabled="disabled" class="disabled">'+f+"</option>":'<option value="'+c+'">'+f+"</option>":'<option value="'+c+'" selected="selected">'+f+"</option>"}t+="</select> "}if(!this.timePicker24Hour){t+='<select class="ampmselect">';var m="",h="";a&&n.clone().hour(12).minute(0).second(0).isBefore(a)&&(m=' disabled="disabled" class="disabled"'),i&&n.clone().hour(0).minute(0).second(0).isAfter(i)&&(h=' disabled="disabled" class="disabled"'),t+=n.hour()>=12?'<option value="AM"'+m+'>AM</option><option value="PM" selected="selected"'+h+">PM</option>":'<option value="AM" selected="selected"'+m+'>AM</option><option value="PM"'+h+">PM</option>",t+="</select>"}this.container.find(".calendar."+e+" .calendar-time div").html(t)}},updateFormInputs:function(){this.container.find("input[name=daterangepicker_start]").is(":focus")||this.container.find("input[name=daterangepicker_end]").is(":focus")||(this.container.find("input[name=daterangepicker_start]").val(this.startDate.format(this.locale.format)),this.endDate&&this.container.find("input[name=daterangepicker_end]").val(this.endDate.format(this.locale.format)),this.singleDatePicker||this.endDate&&(this.startDate.isBefore(this.endDate)||this.startDate.isSame(this.endDate))?this.container.find("button.applyBtn").removeAttr("disabled"):this.container.find("button.applyBtn").attr("disabled","disabled"))},move:function(){var e,n={top:0,left:0},a=t(window).width();this.parentEl.is("body")||(n={top:this.parentEl.offset().top-this.parentEl.scrollTop(),left:this.parentEl.offset().left-this.parentEl.scrollLeft()},a=this.parentEl[0].clientWidth+this.parentEl.offset().left),e="up"==this.drops?this.element.offset().top-this.container.outerHeight()-n.top:this.element.offset().top+this.element.outerHeight()-n.top,this.container["up"==this.drops?"addClass":"removeClass"]("dropup"),"left"==this.opens?(this.container.css({top:e,right:a-this.element.offset().left-this.element.outerWidth(),left:"auto"}),this.container.offset().left<0&&this.container.css({right:"auto",left:9})):"center"==this.opens?(this.container.css({top:e,left:this.element.offset().left-n.left+this.element.outerWidth()/2-this.container.outerWidth()/2,right:"auto"}),this.container.offset().left<0&&this.container.css({right:"auto",left:9})):(this.container.css({top:e,left:this.element.offset().left-n.left,right:"auto"}),this.container.offset().left+this.container.outerWidth()>t(window).width()&&this.container.css({left:"auto",right:0}))},show:function(e){this.isShowing||(this._outsideClickProxy=t.proxy(function(e){this.outsideClick(e)},this),t(document).on("mousedown.daterangepicker",this._outsideClickProxy).on("touchend.daterangepicker",this._outsideClickProxy).on("click.daterangepicker","[data-toggle=dropdown]",this._outsideClickProxy).on("focusin.daterangepicker",this._outsideClickProxy),t(window).on("resize.daterangepicker",t.proxy(function(e){this.move(e)},this)),this.oldStartDate=this.startDate.clone(),this.oldEndDate=this.endDate.clone(),this.previousRightTime=this.endDate.clone(),this.updateView(),this.container.show(),this.move(),this.element.trigger("show.daterangepicker",this),this.isShowing=!0)},hide:function(e){this.isShowing&&(this.endDate||(this.startDate=this.oldStartDate.clone(),this.endDate=this.oldEndDate.clone()),this.startDate.isSame(this.oldStartDate)&&this.endDate.isSame(this.oldEndDate)||this.callback(this.startDate,this.endDate,this.chosenLabel),this.updateElement(),t(document).off(".daterangepicker"),t(window).off(".daterangepicker"),this.container.hide(),this.element.trigger("hide.daterangepicker",this),this.isShowing=!1)},toggle:function(e){this.isShowing?this.hide():this.show()},outsideClick:function(e){var n=t(e.target);"focusin"==e.type||n.closest(this.element).length||n.closest(this.container).length||n.closest(".calendar-table").length||(this.hide(),this.element.trigger("outsideClick.daterangepicker",this))},showCalendars:function(){this.container.addClass("show-calendar"),this.move(),this.element.trigger("showCalendar.daterangepicker",this)},hideCalendars:function(){this.container.removeClass("show-calendar"),this.element.trigger("hideCalendar.daterangepicker",this)},hoverRange:function(e){if(!this.container.find("input[name=daterangepicker_start]").is(":focus")&&!this.container.find("input[name=daterangepicker_end]").is(":focus")){var t=e.target.getAttribute("data-range-key");if(t==this.locale.customRangeLabel)this.updateView();else{var n=this.ranges[t];this.container.find("input[name=daterangepicker_start]").val(n[0].format(this.locale.format)),this.container.find("input[name=daterangepicker_end]").val(n[1].format(this.locale.format))}}},clickRange:function(e){var t=e.target.getAttribute("data-range-key");if(this.chosenLabel=t,t==this.locale.customRangeLabel)this.showCalendars();else{var n=this.ranges[t];this.startDate=n[0],this.endDate=n[1],this.timePicker||(this.startDate.startOf("day"),this.endDate.endOf("day")),this.alwaysShowCalendars||this.hideCalendars(),this.clickApply()}},clickPrev:function(e){var n=t(e.target).parents(".calendar");n.hasClass("left")?(this.leftCalendar.month.subtract(1,"month"),this.linkedCalendars&&this.rightCalendar.month.subtract(1,"month")):this.rightCalendar.month.subtract(1,"month"),this.updateCalendars()},clickNext:function(e){var n=t(e.target).parents(".calendar");n.hasClass("left")?this.leftCalendar.month.add(1,"month"):(this.rightCalendar.month.add(1,"month"),this.linkedCalendars&&this.leftCalendar.month.add(1,"month")),this.updateCalendars()},hoverDate:function(e){if(t(e.target).hasClass("available")){var n=t(e.target).attr("data-title"),a=n.substr(1,1),i=n.substr(3,1),s=t(e.target).parents(".calendar"),o=s.hasClass("left")?this.leftCalendar.calendar[a][i]:this.rightCalendar.calendar[a][i];this.endDate&&!this.container.find("input[name=daterangepicker_start]").is(":focus")?this.container.find("input[name=daterangepicker_start]").val(o.format(this.locale.format)):this.endDate||this.container.find("input[name=daterangepicker_end]").is(":focus")||this.container.find("input[name=daterangepicker_end]").val(o.format(this.locale.format));var r=this.leftCalendar,l=this.rightCalendar,c=this.startDate;this.endDate||this.container.find(".calendar td").each(function(e,n){if(!t(n).hasClass("week")){var a=t(n).attr("data-title"),i=a.substr(1,1),s=a.substr(3,1),p=t(n).parents(".calendar"),d=p.hasClass("left")?r.calendar[i][s]:l.calendar[i][s];d.isAfter(c)&&d.isBefore(o)||d.isSame(o,"day")?t(n).addClass("in-range"):t(n).removeClass("in-range")}})}},clickDate:function(e){if(t(e.target).hasClass("available")){var n=t(e.target).attr("data-title"),a=n.substr(1,1),i=n.substr(3,1),s=t(e.target).parents(".calendar"),o=s.hasClass("left")?this.leftCalendar.calendar[a][i]:this.rightCalendar.calendar[a][i];if(this.endDate||o.isBefore(this.startDate,"day")){if(this.timePicker){var r=parseInt(this.container.find(".left .hourselect").val(),10);if(!this.timePicker24Hour){var l=this.container.find(".left .ampmselect").val();"PM"===l&&r<12&&(r+=12),"AM"===l&&12===r&&(r=0)}var c=parseInt(this.container.find(".left .minuteselect").val(),10),p=this.timePickerSeconds?parseInt(this.container.find(".left .secondselect").val(),10):0;o=o.clone().hour(r).minute(c).second(p)}this.endDate=null,this.setStartDate(o.clone())}else if(!this.endDate&&o.isBefore(this.startDate))this.setEndDate(this.startDate.clone());else{if(this.timePicker){var r=parseInt(this.container.find(".right .hourselect").val(),10);if(!this.timePicker24Hour){var l=this.container.find(".right .ampmselect").val();"PM"===l&&r<12&&(r+=12),"AM"===l&&12===r&&(r=0)}var c=parseInt(this.container.find(".right .minuteselect").val(),10),p=this.timePickerSeconds?parseInt(this.container.find(".right .secondselect").val(),10):0;o=o.clone().hour(r).minute(c).second(p)}this.setEndDate(o.clone()),this.autoApply&&(this.calculateChosenLabel(),this.clickApply())}this.singleDatePicker&&(this.setEndDate(this.startDate),this.timePicker||this.clickApply()),this.updateView(),e.stopPropagation()}},calculateChosenLabel:function(){var e=!0,t=0;for(var n in this.ranges){if(this.timePicker){if(this.startDate.isSame(this.ranges[n][0])&&this.endDate.isSame(this.ranges[n][1])){e=!1,this.chosenLabel=this.container.find(".ranges li:eq("+t+")").addClass("active").html();break}}else if(this.startDate.format("YYYY-MM-DD")==this.ranges[n][0].format("YYYY-MM-DD")&&this.endDate.format("YYYY-MM-DD")==this.ranges[n][1].format("YYYY-MM-DD")){ +return"undefined"!=typeof module&&module.exports?module.exports.saveAs=saveAs:"undefined"!=typeof define&&null!==define&&null!==define.amd&&define([],function(){return saveAs}),"undefined"!=typeof module&&module.exports&&(module.exports=Aes),function(){"use strict";var e=[["","один","два","три","четыре","пять","шесть","семь","восемь","девять","десять","одиннадцать","двенадцать","тринадцать","четырнадцать","пятнадцать","шестнадцать","семнадцать","восемнадцать","девятнадцать"],["","","двадцать","тридцать","сорок","пятьдесят","шестьдесят","семьдесят","восемьдесят","девяносто"],["","сто","двести","триста","четыреста","пятьсот","шестьсот","семьсот","восемьсот","девятьсот"]],t=function(e){return parseFloat(e)},n=function(e,t){if(3!==t.length)return!1;e=Math.abs(e)%100;var n=e%10;return e>10&&e<20?t[2]:n>1&&n<5?t[1]:1===n?t[0]:t[2]},a=function(a,i){var s,o,r="";return 3===a.length&&(s=a.substr(0,1),a=a.substr(1,3),r=""+e[2][s]+" "),a<20?r=r+e[0][t(a)]+" ":(s=a.substr(0,1),o=a.substr(1,2),r=r+e[1][s]+" "+e[0][o]+" "),0===i?r+=n(a,["рубль","рубля","рублей"]):1===i?" "!==r&&(r+=n(a,["тысяча ","тысячи ","тысяч "]),r=r.replace("один ","одна ").replace("два ","две ")):2===i?" "!==r&&(r+=n(a,["миллион ","миллиона ","миллионов "])):3===i&&(r+=n(a,["миллиард ","миллиарда ","миллиардов "])),r},i=function(e){var t=n(e,["копейка","копейки","копеек"]);return 0===e?e="00":e<10&&(e="0"+e)," "+e+" "+t},s=function(e){if(!e)return!1;var n=typeof e;if("number"!==n&&"string"!==n)return!1;if("string"===n&&(e=t(e.replace(",",".")),isNaN(e)))return!1;if(e<=0)return!1;var s,o;e=e.toFixed(2),e.indexOf(".")!==-1&&(s=e.split("."),e=s[0],o=s[1]);for(var r,l="",c=e.length-1,p="",d=0;c>=0;)r=e.substr(c,1),p=r+p,3!==p.length&&0!==c||isNaN(t(p))||(l=a(p,d)+l,p="",d++),c--;return l=l.replace(/\s+/g," "),o&&(l+=i(t(o))),l};Number.prototype.in_words||(Number.prototype.in_words=function(){return s(this)})}(),function(e,t){if("function"==typeof define&&define.amd)define(["moment","jquery"],function(n,a){return e.daterangepicker=t(n,a)});else if("object"==typeof module&&module.exports){var n="undefined"!=typeof window?window.jQuery:void 0;n||(n=require("jquery"),n.fn||(n.fn={})),module.exports=t(require("moment"),n)}else e.daterangepicker=t(e.moment,e.jQuery)}(this,function(e,t){var n=function(n,a,i){if(this.parentEl="body",this.element=t(n),this.startDate=e().startOf("day"),this.endDate=e().endOf("day"),this.minDate=!1,this.maxDate=!1,this.dateLimit=!1,this.autoApply=!1,this.singleDatePicker=!1,this.showDropdowns=!1,this.showWeekNumbers=!1,this.showISOWeekNumbers=!1,this.showCustomRangeLabel=!0,this.timePicker=!1,this.timePicker24Hour=!1,this.timePickerIncrement=1,this.timePickerSeconds=!1,this.linkedCalendars=!0,this.autoUpdateInput=!0,this.alwaysShowCalendars=!1,this.ranges={},this.opens="right",this.element.hasClass("pull-right")&&(this.opens="left"),this.drops="down",this.element.hasClass("dropup")&&(this.drops="up"),this.buttonClasses="btn btn-sm",this.applyClass="btn-success",this.cancelClass="btn-default",this.locale={direction:"ltr",format:"DD.MM.YYYY",separator:" - ",applyLabel:"Применить",cancelLabel:"Отмена",weekLabel:"W",customRangeLabel:"Произвольные даты",daysOfWeek:e.weekdaysMin(),monthNames:e.monthsShort(),firstDay:e.localeData().firstDayOfWeek()},this.callback=function(){},this.isShowing=!1,this.leftCalendar={},this.rightCalendar={},"object"==typeof a&&null!==a||(a={}),a=t.extend(this.element.data(),a),"string"==typeof a.template||a.template instanceof t||(a.template='<div class="daterangepicker dropdown-menu"><div class="calendar left"><div class="daterangepicker_input"><input class="input-mini form-control" type="text" name="daterangepicker_start" value="" /><i class="fa fa-calendar glyphicon glyphicon-calendar"></i><div class="calendar-time"><div></div><i class="fa fa-clock-o glyphicon glyphicon-time"></i></div></div><div class="calendar-table"></div></div><div class="calendar right"><div class="daterangepicker_input"><input class="input-mini form-control" type="text" name="daterangepicker_end" value="" /><i class="fa fa-calendar glyphicon glyphicon-calendar"></i><div class="calendar-time"><div></div><i class="fa fa-clock-o glyphicon glyphicon-time"></i></div></div><div class="calendar-table"></div></div><div class="ranges"><div class="range_inputs"><button class="applyBtn" disabled="disabled" type="button"></button> <button class="cancelBtn" type="button"></button></div></div></div>'),this.parentEl=t(a.parentEl&&t(a.parentEl).length?a.parentEl:this.parentEl),this.container=t(a.template).appendTo(this.parentEl),"object"==typeof a.locale&&("string"==typeof a.locale.direction&&(this.locale.direction=a.locale.direction),"string"==typeof a.locale.format&&(this.locale.format=a.locale.format),"string"==typeof a.locale.separator&&(this.locale.separator=a.locale.separator),"object"==typeof a.locale.daysOfWeek&&(this.locale.daysOfWeek=a.locale.daysOfWeek.slice()),"object"==typeof a.locale.monthNames&&(this.locale.monthNames=a.locale.monthNames.slice()),"number"==typeof a.locale.firstDay&&(this.locale.firstDay=a.locale.firstDay),"string"==typeof a.locale.applyLabel&&(this.locale.applyLabel=a.locale.applyLabel),"string"==typeof a.locale.cancelLabel&&(this.locale.cancelLabel=a.locale.cancelLabel),"string"==typeof a.locale.weekLabel&&(this.locale.weekLabel=a.locale.weekLabel),"string"==typeof a.locale.customRangeLabel&&(this.locale.customRangeLabel=a.locale.customRangeLabel)),this.container.addClass(this.locale.direction),"string"==typeof a.startDate&&(this.startDate=e(a.startDate,this.locale.format)),"string"==typeof a.endDate&&(this.endDate=e(a.endDate,this.locale.format)),"string"==typeof a.minDate&&(this.minDate=e(a.minDate,this.locale.format)),"string"==typeof a.maxDate&&(this.maxDate=e(a.maxDate,this.locale.format)),"object"==typeof a.startDate&&(this.startDate=e(a.startDate)),"object"==typeof a.endDate&&(this.endDate=e(a.endDate)),"object"==typeof a.minDate&&(this.minDate=e(a.minDate)),"object"==typeof a.maxDate&&(this.maxDate=e(a.maxDate)),this.minDate&&this.startDate.isBefore(this.minDate)&&(this.startDate=this.minDate.clone()),this.maxDate&&this.endDate.isAfter(this.maxDate)&&(this.endDate=this.maxDate.clone()),"string"==typeof a.applyClass&&(this.applyClass=a.applyClass),"string"==typeof a.cancelClass&&(this.cancelClass=a.cancelClass),"object"==typeof a.dateLimit&&(this.dateLimit=a.dateLimit),"string"==typeof a.opens&&(this.opens=a.opens),"string"==typeof a.drops&&(this.drops=a.drops),"boolean"==typeof a.showWeekNumbers&&(this.showWeekNumbers=a.showWeekNumbers),"boolean"==typeof a.showISOWeekNumbers&&(this.showISOWeekNumbers=a.showISOWeekNumbers),"string"==typeof a.buttonClasses&&(this.buttonClasses=a.buttonClasses),"object"==typeof a.buttonClasses&&(this.buttonClasses=a.buttonClasses.join(" ")),"boolean"==typeof a.showDropdowns&&(this.showDropdowns=a.showDropdowns),"boolean"==typeof a.showCustomRangeLabel&&(this.showCustomRangeLabel=a.showCustomRangeLabel),"boolean"==typeof a.singleDatePicker&&(this.singleDatePicker=a.singleDatePicker,this.singleDatePicker&&(this.endDate=this.startDate.clone())),"boolean"==typeof a.timePicker&&(this.timePicker=a.timePicker),"boolean"==typeof a.timePickerSeconds&&(this.timePickerSeconds=a.timePickerSeconds),"number"==typeof a.timePickerIncrement&&(this.timePickerIncrement=a.timePickerIncrement),"boolean"==typeof a.timePicker24Hour&&(this.timePicker24Hour=a.timePicker24Hour),"boolean"==typeof a.autoApply&&(this.autoApply=a.autoApply),"boolean"==typeof a.autoUpdateInput&&(this.autoUpdateInput=a.autoUpdateInput),"boolean"==typeof a.linkedCalendars&&(this.linkedCalendars=a.linkedCalendars),"function"==typeof a.isInvalidDate&&(this.isInvalidDate=a.isInvalidDate),"function"==typeof a.isCustomDate&&(this.isCustomDate=a.isCustomDate),"boolean"==typeof a.alwaysShowCalendars&&(this.alwaysShowCalendars=a.alwaysShowCalendars),0!=this.locale.firstDay)for(var s=this.locale.firstDay;s>0;)this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift()),s--;var o,r,l;if("undefined"==typeof a.startDate&&"undefined"==typeof a.endDate&&t(this.element).is("input[type=text]")){var c=t(this.element).val(),p=c.split(this.locale.separator);o=r=null,2==p.length?(o=e(p[0],this.locale.format),r=e(p[1],this.locale.format)):this.singleDatePicker&&""!==c&&(o=e(c,this.locale.format),r=e(c,this.locale.format)),null!==o&&null!==r&&(this.setStartDate(o),this.setEndDate(r))}if("object"==typeof a.ranges){for(l in a.ranges){o="string"==typeof a.ranges[l][0]?e(a.ranges[l][0],this.locale.format):e(a.ranges[l][0]),r="string"==typeof a.ranges[l][1]?e(a.ranges[l][1],this.locale.format):e(a.ranges[l][1]),this.minDate&&o.isBefore(this.minDate)&&(o=this.minDate.clone());var d=this.maxDate;if(this.dateLimit&&d&&o.clone().add(this.dateLimit).isAfter(d)&&(d=o.clone().add(this.dateLimit)),d&&r.isAfter(d)&&(r=d.clone()),!(this.minDate&&r.isBefore(this.minDate,this.timepicker?"minute":"day")||d&&o.isAfter(d,this.timepicker?"minute":"day"))){var u=document.createElement("textarea");u.innerHTML=l;var m=u.value;this.ranges[m]=[o,r]}}var f="<ul>";for(l in this.ranges)f+='<li data-range-key="'+l+'">'+l+"</li>";this.showCustomRangeLabel&&(f+='<li data-range-key="'+this.locale.customRangeLabel+'">'+this.locale.customRangeLabel+"</li>"),f+="</ul>",this.container.find(".ranges").prepend(f)}"function"==typeof i&&(this.callback=i),this.timePicker||(this.startDate=this.startDate.startOf("day"),this.endDate=this.endDate.endOf("day"),this.container.find(".calendar-time").hide()),this.timePicker&&this.autoApply&&(this.autoApply=!1),this.autoApply&&"object"!=typeof a.ranges?this.container.find(".ranges").hide():this.autoApply&&this.container.find(".applyBtn, .cancelBtn").addClass("hide"),this.singleDatePicker&&(this.container.addClass("single"),this.container.find(".calendar.left").addClass("single"),this.container.find(".calendar.left").show(),this.container.find(".calendar.right").hide(),this.container.find(".daterangepicker_input input, .daterangepicker_input > i").hide(),this.timePicker?this.container.find(".ranges ul").hide():this.container.find(".ranges").hide()),("undefined"==typeof a.ranges&&!this.singleDatePicker||this.alwaysShowCalendars)&&this.container.addClass("show-calendar"),this.container.addClass("opens"+this.opens),"undefined"!=typeof a.ranges&&"right"==this.opens&&this.container.find(".ranges").prependTo(this.container.find(".calendar.left").parent()),this.container.find(".applyBtn, .cancelBtn").addClass(this.buttonClasses),this.applyClass.length&&this.container.find(".applyBtn").addClass(this.applyClass),this.cancelClass.length&&this.container.find(".cancelBtn").addClass(this.cancelClass),this.container.find(".applyBtn").html(this.locale.applyLabel),this.container.find(".cancelBtn").html(this.locale.cancelLabel),this.container.find(".calendar").on("click.daterangepicker",".prev",t.proxy(this.clickPrev,this)).on("click.daterangepicker",".next",t.proxy(this.clickNext,this)).on("mousedown.daterangepicker","td.available",t.proxy(this.clickDate,this)).on("mouseenter.daterangepicker","td.available",t.proxy(this.hoverDate,this)).on("mouseleave.daterangepicker","td.available",t.proxy(this.updateFormInputs,this)).on("change.daterangepicker","select.yearselect",t.proxy(this.monthOrYearChanged,this)).on("change.daterangepicker","select.monthselect",t.proxy(this.monthOrYearChanged,this)).on("change.daterangepicker","select.hourselect,select.minuteselect,select.secondselect,select.ampmselect",t.proxy(this.timeChanged,this)).on("click.daterangepicker",".daterangepicker_input input",t.proxy(this.showCalendars,this)).on("focus.daterangepicker",".daterangepicker_input input",t.proxy(this.formInputsFocused,this)).on("blur.daterangepicker",".daterangepicker_input input",t.proxy(this.formInputsBlurred,this)).on("change.daterangepicker",".daterangepicker_input input",t.proxy(this.formInputsChanged,this)),this.container.find(".ranges").on("click.daterangepicker","button.applyBtn",t.proxy(this.clickApply,this)).on("click.daterangepicker","button.cancelBtn",t.proxy(this.clickCancel,this)).on("click.daterangepicker","li",t.proxy(this.clickRange,this)).on("mouseenter.daterangepicker","li",t.proxy(this.hoverRange,this)).on("mouseleave.daterangepicker","li",t.proxy(this.updateFormInputs,this)),this.element.is("input")||this.element.is("button")?this.element.on({"click.daterangepicker":t.proxy(this.show,this),"focus.daterangepicker":t.proxy(this.show,this),"keyup.daterangepicker":t.proxy(this.elementChanged,this),"keydown.daterangepicker":t.proxy(this.keydown,this)}):this.element.on("click.daterangepicker",t.proxy(this.toggle,this)),this.element.is("input")&&!this.singleDatePicker&&this.autoUpdateInput?(this.element.val(this.startDate.format(this.locale.format)+this.locale.separator+this.endDate.format(this.locale.format)),this.element.trigger("change")):this.element.is("input")&&this.autoUpdateInput&&(this.element.val(this.startDate.format(this.locale.format)),this.element.trigger("change"))};return n.prototype={constructor:n,setStartDate:function(t){"string"==typeof t&&(this.startDate=e(t,this.locale.format)),"object"==typeof t&&(this.startDate=e(t)),this.timePicker||(this.startDate=this.startDate.startOf("day")),this.timePicker&&this.timePickerIncrement&&this.startDate.minute(Math.round(this.startDate.minute()/this.timePickerIncrement)*this.timePickerIncrement),this.minDate&&this.startDate.isBefore(this.minDate)&&(this.startDate=this.minDate,this.timePicker&&this.timePickerIncrement&&this.startDate.minute(Math.round(this.startDate.minute()/this.timePickerIncrement)*this.timePickerIncrement)),this.maxDate&&this.startDate.isAfter(this.maxDate)&&(this.startDate=this.maxDate,this.timePicker&&this.timePickerIncrement&&this.startDate.minute(Math.floor(this.startDate.minute()/this.timePickerIncrement)*this.timePickerIncrement)),this.isShowing||this.updateElement(),this.updateMonthsInView()},setEndDate:function(t){"string"==typeof t&&(this.endDate=e(t,this.locale.format)),"object"==typeof t&&(this.endDate=e(t)),this.timePicker||(this.endDate=this.endDate.endOf("day")),this.timePicker&&this.timePickerIncrement&&this.endDate.minute(Math.round(this.endDate.minute()/this.timePickerIncrement)*this.timePickerIncrement),this.endDate.isBefore(this.startDate)&&(this.endDate=this.startDate.clone()),this.maxDate&&this.endDate.isAfter(this.maxDate)&&(this.endDate=this.maxDate),this.dateLimit&&this.startDate.clone().add(this.dateLimit).isBefore(this.endDate)&&(this.endDate=this.startDate.clone().add(this.dateLimit)),this.previousRightTime=this.endDate.clone(),this.isShowing||this.updateElement(),this.updateMonthsInView()},isInvalidDate:function(){return!1},isCustomDate:function(){return!1},updateView:function(){this.timePicker&&(this.renderTimePicker("left"),this.renderTimePicker("right"),this.endDate?this.container.find(".right .calendar-time select").removeAttr("disabled").removeClass("disabled"):this.container.find(".right .calendar-time select").attr("disabled","disabled").addClass("disabled")),this.endDate?(this.container.find('input[name="daterangepicker_end"]').removeClass("active"),this.container.find('input[name="daterangepicker_start"]').addClass("active")):(this.container.find('input[name="daterangepicker_end"]').addClass("active"),this.container.find('input[name="daterangepicker_start"]').removeClass("active")),this.updateMonthsInView(),this.updateCalendars(),this.updateFormInputs()},updateMonthsInView:function(){if(this.endDate){if(!this.singleDatePicker&&this.leftCalendar.month&&this.rightCalendar.month&&(this.startDate.format("YYYY-MM")==this.leftCalendar.month.format("YYYY-MM")||this.startDate.format("YYYY-MM")==this.rightCalendar.month.format("YYYY-MM"))&&(this.endDate.format("YYYY-MM")==this.leftCalendar.month.format("YYYY-MM")||this.endDate.format("YYYY-MM")==this.rightCalendar.month.format("YYYY-MM")))return;this.leftCalendar.month=this.startDate.clone().date(2),this.linkedCalendars||this.endDate.month()==this.startDate.month()&&this.endDate.year()==this.startDate.year()?this.rightCalendar.month=this.startDate.clone().date(2).add(1,"month"):this.rightCalendar.month=this.endDate.clone().date(2)}else this.leftCalendar.month.format("YYYY-MM")!=this.startDate.format("YYYY-MM")&&this.rightCalendar.month.format("YYYY-MM")!=this.startDate.format("YYYY-MM")&&(this.leftCalendar.month=this.startDate.clone().date(2),this.rightCalendar.month=this.startDate.clone().date(2).add(1,"month"));this.maxDate&&this.linkedCalendars&&!this.singleDatePicker&&this.rightCalendar.month>this.maxDate&&(this.rightCalendar.month=this.maxDate.clone().date(2),this.leftCalendar.month=this.maxDate.clone().date(2).subtract(1,"month"))},updateCalendars:function(){if(this.timePicker){var e,t,n;if(this.endDate){if(e=parseInt(this.container.find(".left .hourselect").val(),10),t=parseInt(this.container.find(".left .minuteselect").val(),10),n=this.timePickerSeconds?parseInt(this.container.find(".left .secondselect").val(),10):0,!this.timePicker24Hour){var a=this.container.find(".left .ampmselect").val();"PM"===a&&e<12&&(e+=12),"AM"===a&&12===e&&(e=0)}}else if(e=parseInt(this.container.find(".right .hourselect").val(),10),t=parseInt(this.container.find(".right .minuteselect").val(),10),n=this.timePickerSeconds?parseInt(this.container.find(".right .secondselect").val(),10):0,!this.timePicker24Hour){var a=this.container.find(".right .ampmselect").val();"PM"===a&&e<12&&(e+=12),"AM"===a&&12===e&&(e=0)}this.leftCalendar.month.hour(e).minute(t).second(n),this.rightCalendar.month.hour(e).minute(t).second(n)}this.renderCalendar("left"),this.renderCalendar("right"),this.container.find(".ranges li").removeClass("active"),null!=this.endDate&&this.calculateChosenLabel()},renderCalendar:function(n){var a="left"==n?this.leftCalendar:this.rightCalendar,i=a.month.month(),s=a.month.year(),o=a.month.hour(),r=a.month.minute(),l=a.month.second(),c=e([s,i]).daysInMonth(),p=e([s,i,1]),d=e([s,i,c]),u=e(p).subtract(1,"month").month(),m=e(p).subtract(1,"month").year(),f=e([m,u]).daysInMonth(),h=p.day(),a=[];a.firstDay=p,a.lastDay=d;for(var _=0;_<6;_++)a[_]=[];var g=f-h+this.locale.firstDay+1;g>f&&(g-=7),h==this.locale.firstDay&&(g=f-6);for(var b,v,x=e([m,u,g,12,r,l]),_=0,b=0,v=0;_<42;_++,b++,x=e(x).add(24,"hour"))_>0&&b%7===0&&(b=0,v++),a[v][b]=x.clone().hour(o).minute(r).second(l),x.hour(12),this.minDate&&a[v][b].format("YYYY-MM-DD")==this.minDate.format("YYYY-MM-DD")&&a[v][b].isBefore(this.minDate)&&"left"==n&&(a[v][b]=this.minDate.clone()),this.maxDate&&a[v][b].format("YYYY-MM-DD")==this.maxDate.format("YYYY-MM-DD")&&a[v][b].isAfter(this.maxDate)&&"right"==n&&(a[v][b]=this.maxDate.clone());"left"==n?this.leftCalendar.calendar=a:this.rightCalendar.calendar=a;var y="left"==n?this.minDate:this.startDate,w=this.maxDate,k=("left"==n?this.startDate:this.endDate,"ltr"==this.locale.direction?{left:"chevron-left",right:"chevron-right"}:{left:"chevron-right",right:"chevron-left"}),$='<table class="table-condensed">';$+="<thead>",$+="<tr>",(this.showWeekNumbers||this.showISOWeekNumbers)&&($+="<th></th>"),$+=y&&!y.isBefore(a.firstDay)||this.linkedCalendars&&"left"!=n?"<th></th>":'<th class="prev available"><i class="fa fa-'+k.left+" glyphicon glyphicon-"+k.left+'"></i></th>';var j=this.locale.monthNames[a[1][1].month()]+a[1][1].format(" YYYY");if(this.showDropdowns){for(var D=a[1][1].month(),O=a[1][1].year(),C=w&&w.year()||O+5,M=y&&y.year()||O-50,E=O==M,S=O==C,T='<select class="monthselect">',P=0;P<12;P++)T+=(!E||P>=y.month())&&(!S||P<=w.month())?"<option value='"+P+"'"+(P===D?" selected='selected'":"")+">"+this.locale.monthNames[P]+"</option>":"<option value='"+P+"'"+(P===D?" selected='selected'":"")+" disabled='disabled'>"+this.locale.monthNames[P]+"</option>";T+="</select>";for(var I='<select class="yearselect">',L=M;L<=C;L++)I+='<option value="'+L+'"'+(L===O?' selected="selected"':"")+">"+L+"</option>";I+="</select>",j=T+I}if($+='<th colspan="5" class="month">'+j+"</th>",$+=w&&!w.isAfter(a.lastDay)||this.linkedCalendars&&"right"!=n&&!this.singleDatePicker?"<th></th>":'<th class="next available"><i class="fa fa-'+k.right+" glyphicon glyphicon-"+k.right+'"></i></th>',$+="</tr>",$+="<tr>",(this.showWeekNumbers||this.showISOWeekNumbers)&&($+='<th class="week">'+this.locale.weekLabel+"</th>"),t.each(this.locale.daysOfWeek,function(e,t){$+="<th>"+t+"</th>"}),$+="</tr>",$+="</thead>",$+="<tbody>",null==this.endDate&&this.dateLimit){var q=this.startDate.clone().add(this.dateLimit).endOf("day");w&&!q.isBefore(w)||(w=q)}for(var v=0;v<6;v++){$+="<tr>",this.showWeekNumbers?$+='<td class="week">'+a[v][0].week()+"</td>":this.showISOWeekNumbers&&($+='<td class="week">'+a[v][0].isoWeek()+"</td>");for(var b=0;b<7;b++){var A=[];a[v][b].isSame(new Date,"day")&&A.push("today"),a[v][b].isoWeekday()>5&&A.push("weekend"),a[v][b].month()!=a[1][1].month()&&A.push("off"),this.minDate&&a[v][b].isBefore(this.minDate,"day")&&A.push("off","disabled"),w&&a[v][b].isAfter(w,"day")&&A.push("off","disabled"),this.isInvalidDate(a[v][b])&&A.push("off","disabled"),a[v][b].format("YYYY-MM-DD")==this.startDate.format("YYYY-MM-DD")&&A.push("active","start-date"),null!=this.endDate&&a[v][b].format("YYYY-MM-DD")==this.endDate.format("YYYY-MM-DD")&&A.push("active","end-date"),null!=this.endDate&&a[v][b]>this.startDate&&a[v][b]<this.endDate&&A.push("in-range");var R=this.isCustomDate(a[v][b]);R!==!1&&("string"==typeof R?A.push(R):Array.prototype.push.apply(A,R));for(var N="",Y=!1,_=0;_<A.length;_++)N+=A[_]+" ","disabled"==A[_]&&(Y=!0);Y||(N+="available"),$+='<td class="'+N.replace(/^\s+|\s+$/g,"")+'" data-title="r'+v+"c"+b+'">'+a[v][b].date()+"</td>"}$+="</tr>"}$+="</tbody>",$+="</table>",this.container.find(".calendar."+n+" .calendar-table").html($)},renderTimePicker:function(e){if("right"!=e||this.endDate){var t,n,a,i=this.maxDate;if(!this.dateLimit||this.maxDate&&!this.startDate.clone().add(this.dateLimit).isAfter(this.maxDate)||(i=this.startDate.clone().add(this.dateLimit)),"left"==e)n=this.startDate.clone(),a=this.minDate;else if("right"==e){n=this.endDate.clone(),a=this.startDate;var s=this.container.find(".calendar.right .calendar-time div");if(!this.endDate&&""!=s.html()&&(n.hour(s.find(".hourselect option:selected").val()||n.hour()),n.minute(s.find(".minuteselect option:selected").val()||n.minute()),n.second(s.find(".secondselect option:selected").val()||n.second()),!this.timePicker24Hour)){var o=s.find(".ampmselect option:selected").val();"PM"===o&&n.hour()<12&&n.hour(n.hour()+12),"AM"===o&&12===n.hour()&&n.hour(0)}n.isBefore(this.startDate)&&(n=this.startDate.clone()),i&&n.isAfter(i)&&(n=i.clone())}t='<select class="hourselect">';for(var r=this.timePicker24Hour?0:1,l=this.timePicker24Hour?23:12,c=r;c<=l;c++){var p=c;this.timePicker24Hour||(p=n.hour()>=12?12==c?12:c+12:12==c?0:c);var d=n.clone().hour(p),u=!1;a&&d.minute(59).isBefore(a)&&(u=!0),i&&d.minute(0).isAfter(i)&&(u=!0),t+=p!=n.hour()||u?u?'<option value="'+c+'" disabled="disabled" class="disabled">'+c+"</option>":'<option value="'+c+'">'+c+"</option>":'<option value="'+c+'" selected="selected">'+c+"</option>"}t+="</select> ",t+=': <select class="minuteselect">';for(var c=0;c<60;c+=this.timePickerIncrement){var m=c<10?"0"+c:c,d=n.clone().minute(c),u=!1;a&&d.second(59).isBefore(a)&&(u=!0),i&&d.second(0).isAfter(i)&&(u=!0),t+=n.minute()!=c||u?u?'<option value="'+c+'" disabled="disabled" class="disabled">'+m+"</option>":'<option value="'+c+'">'+m+"</option>":'<option value="'+c+'" selected="selected">'+m+"</option>"}if(t+="</select> ",this.timePickerSeconds){t+=': <select class="secondselect">';for(var c=0;c<60;c++){var m=c<10?"0"+c:c,d=n.clone().second(c),u=!1;a&&d.isBefore(a)&&(u=!0),i&&d.isAfter(i)&&(u=!0),t+=n.second()!=c||u?u?'<option value="'+c+'" disabled="disabled" class="disabled">'+m+"</option>":'<option value="'+c+'">'+m+"</option>":'<option value="'+c+'" selected="selected">'+m+"</option>"}t+="</select> "}if(!this.timePicker24Hour){t+='<select class="ampmselect">';var f="",h="";a&&n.clone().hour(12).minute(0).second(0).isBefore(a)&&(f=' disabled="disabled" class="disabled"'),i&&n.clone().hour(0).minute(0).second(0).isAfter(i)&&(h=' disabled="disabled" class="disabled"'),t+=n.hour()>=12?'<option value="AM"'+f+'>AM</option><option value="PM" selected="selected"'+h+">PM</option>":'<option value="AM" selected="selected"'+f+'>AM</option><option value="PM"'+h+">PM</option>",t+="</select>"}this.container.find(".calendar."+e+" .calendar-time div").html(t)}},updateFormInputs:function(){this.container.find("input[name=daterangepicker_start]").is(":focus")||this.container.find("input[name=daterangepicker_end]").is(":focus")||(this.container.find("input[name=daterangepicker_start]").val(this.startDate.format(this.locale.format)),this.endDate&&this.container.find("input[name=daterangepicker_end]").val(this.endDate.format(this.locale.format)),this.singleDatePicker||this.endDate&&(this.startDate.isBefore(this.endDate)||this.startDate.isSame(this.endDate))?this.container.find("button.applyBtn").removeAttr("disabled"):this.container.find("button.applyBtn").attr("disabled","disabled"))},move:function(){var e,n={top:0,left:0},a=t(window).width();this.parentEl.is("body")||(n={top:this.parentEl.offset().top-this.parentEl.scrollTop(),left:this.parentEl.offset().left-this.parentEl.scrollLeft()},a=this.parentEl[0].clientWidth+this.parentEl.offset().left),e="up"==this.drops?this.element.offset().top-this.container.outerHeight()-n.top:this.element.offset().top+this.element.outerHeight()-n.top,this.container["up"==this.drops?"addClass":"removeClass"]("dropup"),"left"==this.opens?(this.container.css({top:e,right:a-this.element.offset().left-this.element.outerWidth(),left:"auto"}),this.container.offset().left<0&&this.container.css({right:"auto",left:9})):"center"==this.opens?(this.container.css({top:e,left:this.element.offset().left-n.left+this.element.outerWidth()/2-this.container.outerWidth()/2,right:"auto"}),this.container.offset().left<0&&this.container.css({right:"auto",left:9})):(this.container.css({top:e,left:this.element.offset().left-n.left,right:"auto"}),this.container.offset().left+this.container.outerWidth()>t(window).width()&&this.container.css({left:"auto",right:0}))},show:function(e){this.isShowing||(this._outsideClickProxy=t.proxy(function(e){this.outsideClick(e)},this),t(document).on("mousedown.daterangepicker",this._outsideClickProxy).on("touchend.daterangepicker",this._outsideClickProxy).on("click.daterangepicker","[data-toggle=dropdown]",this._outsideClickProxy).on("focusin.daterangepicker",this._outsideClickProxy),t(window).on("resize.daterangepicker",t.proxy(function(e){this.move(e)},this)),this.oldStartDate=this.startDate.clone(),this.oldEndDate=this.endDate.clone(),this.previousRightTime=this.endDate.clone(),this.updateView(),this.container.show(),this.move(),this.element.trigger("show.daterangepicker",this),this.isShowing=!0)},hide:function(e){this.isShowing&&(this.endDate||(this.startDate=this.oldStartDate.clone(),this.endDate=this.oldEndDate.clone()),this.startDate.isSame(this.oldStartDate)&&this.endDate.isSame(this.oldEndDate)||this.callback(this.startDate,this.endDate,this.chosenLabel),this.updateElement(),t(document).off(".daterangepicker"),t(window).off(".daterangepicker"),this.container.hide(),this.element.trigger("hide.daterangepicker",this),this.isShowing=!1)},toggle:function(e){this.isShowing?this.hide():this.show()},outsideClick:function(e){var n=t(e.target);"focusin"==e.type||n.closest(this.element).length||n.closest(this.container).length||n.closest(".calendar-table").length||(this.hide(),this.element.trigger("outsideClick.daterangepicker",this))},showCalendars:function(){this.container.addClass("show-calendar"),this.move(),this.element.trigger("showCalendar.daterangepicker",this)},hideCalendars:function(){this.container.removeClass("show-calendar"),this.element.trigger("hideCalendar.daterangepicker",this)},hoverRange:function(e){if(!this.container.find("input[name=daterangepicker_start]").is(":focus")&&!this.container.find("input[name=daterangepicker_end]").is(":focus")){var t=e.target.getAttribute("data-range-key");if(t==this.locale.customRangeLabel)this.updateView();else{var n=this.ranges[t];this.container.find("input[name=daterangepicker_start]").val(n[0].format(this.locale.format)),this.container.find("input[name=daterangepicker_end]").val(n[1].format(this.locale.format))}}},clickRange:function(e){var t=e.target.getAttribute("data-range-key");if(this.chosenLabel=t,t==this.locale.customRangeLabel)this.showCalendars();else{var n=this.ranges[t];this.startDate=n[0],this.endDate=n[1],this.timePicker||(this.startDate.startOf("day"),this.endDate.endOf("day")),this.alwaysShowCalendars||this.hideCalendars(),this.clickApply()}},clickPrev:function(e){var n=t(e.target).parents(".calendar");n.hasClass("left")?(this.leftCalendar.month.subtract(1,"month"),this.linkedCalendars&&this.rightCalendar.month.subtract(1,"month")):this.rightCalendar.month.subtract(1,"month"),this.updateCalendars()},clickNext:function(e){var n=t(e.target).parents(".calendar");n.hasClass("left")?this.leftCalendar.month.add(1,"month"):(this.rightCalendar.month.add(1,"month"),this.linkedCalendars&&this.leftCalendar.month.add(1,"month")),this.updateCalendars()},hoverDate:function(e){if(t(e.target).hasClass("available")){var n=t(e.target).attr("data-title"),a=n.substr(1,1),i=n.substr(3,1),s=t(e.target).parents(".calendar"),o=s.hasClass("left")?this.leftCalendar.calendar[a][i]:this.rightCalendar.calendar[a][i];this.endDate&&!this.container.find("input[name=daterangepicker_start]").is(":focus")?this.container.find("input[name=daterangepicker_start]").val(o.format(this.locale.format)):this.endDate||this.container.find("input[name=daterangepicker_end]").is(":focus")||this.container.find("input[name=daterangepicker_end]").val(o.format(this.locale.format));var r=this.leftCalendar,l=this.rightCalendar,c=this.startDate;this.endDate||this.container.find(".calendar td").each(function(e,n){if(!t(n).hasClass("week")){var a=t(n).attr("data-title"),i=a.substr(1,1),s=a.substr(3,1),p=t(n).parents(".calendar"),d=p.hasClass("left")?r.calendar[i][s]:l.calendar[i][s];d.isAfter(c)&&d.isBefore(o)||d.isSame(o,"day")?t(n).addClass("in-range"):t(n).removeClass("in-range")}})}},clickDate:function(e){if(t(e.target).hasClass("available")){var n=t(e.target).attr("data-title"),a=n.substr(1,1),i=n.substr(3,1),s=t(e.target).parents(".calendar"),o=s.hasClass("left")?this.leftCalendar.calendar[a][i]:this.rightCalendar.calendar[a][i];if(this.endDate||o.isBefore(this.startDate,"day")){if(this.timePicker){var r=parseInt(this.container.find(".left .hourselect").val(),10);if(!this.timePicker24Hour){var l=this.container.find(".left .ampmselect").val();"PM"===l&&r<12&&(r+=12),"AM"===l&&12===r&&(r=0)}var c=parseInt(this.container.find(".left .minuteselect").val(),10),p=this.timePickerSeconds?parseInt(this.container.find(".left .secondselect").val(),10):0;o=o.clone().hour(r).minute(c).second(p)}this.endDate=null,this.setStartDate(o.clone())}else if(!this.endDate&&o.isBefore(this.startDate))this.setEndDate(this.startDate.clone());else{if(this.timePicker){var r=parseInt(this.container.find(".right .hourselect").val(),10);if(!this.timePicker24Hour){var l=this.container.find(".right .ampmselect").val();"PM"===l&&r<12&&(r+=12),"AM"===l&&12===r&&(r=0)}var c=parseInt(this.container.find(".right .minuteselect").val(),10),p=this.timePickerSeconds?parseInt(this.container.find(".right .secondselect").val(),10):0;o=o.clone().hour(r).minute(c).second(p)}this.setEndDate(o.clone()),this.autoApply&&(this.calculateChosenLabel(),this.clickApply())}this.singleDatePicker&&(this.setEndDate(this.startDate),this.timePicker||this.clickApply()),this.updateView(),e.stopPropagation()}},calculateChosenLabel:function(){var e=!0,t=0;for(var n in this.ranges){if(this.timePicker){if(this.startDate.isSame(this.ranges[n][0])&&this.endDate.isSame(this.ranges[n][1])){e=!1,this.chosenLabel=this.container.find(".ranges li:eq("+t+")").addClass("active").html();break}}else if(this.startDate.format("YYYY-MM-DD")==this.ranges[n][0].format("YYYY-MM-DD")&&this.endDate.format("YYYY-MM-DD")==this.ranges[n][1].format("YYYY-MM-DD")){ e=!1,this.chosenLabel=this.container.find(".ranges li:eq("+t+")").addClass("active").html();break}t++}e&&this.showCustomRangeLabel&&(this.chosenLabel=this.container.find(".ranges li:last").addClass("active").html(),this.showCalendars())},clickApply:function(e){this.hide(),this.element.trigger("apply.daterangepicker",this)},clickCancel:function(e){this.startDate=this.oldStartDate,this.endDate=this.oldEndDate,this.hide(),this.element.trigger("cancel.daterangepicker",this)},monthOrYearChanged:function(e){var n=t(e.target).closest(".calendar").hasClass("left"),a=n?"left":"right",i=this.container.find(".calendar."+a),s=parseInt(i.find(".monthselect").val(),10),o=i.find(".yearselect").val();n||(o<this.startDate.year()||o==this.startDate.year()&&s<this.startDate.month())&&(s=this.startDate.month(),o=this.startDate.year()),this.minDate&&(o<this.minDate.year()||o==this.minDate.year()&&s<this.minDate.month())&&(s=this.minDate.month(),o=this.minDate.year()),this.maxDate&&(o>this.maxDate.year()||o==this.maxDate.year()&&s>this.maxDate.month())&&(s=this.maxDate.month(),o=this.maxDate.year()),n?(this.leftCalendar.month.month(s).year(o),this.linkedCalendars&&(this.rightCalendar.month=this.leftCalendar.month.clone().add(1,"month"))):(this.rightCalendar.month.month(s).year(o),this.linkedCalendars&&(this.leftCalendar.month=this.rightCalendar.month.clone().subtract(1,"month"))),this.updateCalendars()},timeChanged:function(e){var n=t(e.target).closest(".calendar"),a=n.hasClass("left"),i=parseInt(n.find(".hourselect").val(),10),s=parseInt(n.find(".minuteselect").val(),10),o=this.timePickerSeconds?parseInt(n.find(".secondselect").val(),10):0;if(!this.timePicker24Hour){var r=n.find(".ampmselect").val();"PM"===r&&i<12&&(i+=12),"AM"===r&&12===i&&(i=0)}if(a){var l=this.startDate.clone();l.hour(i),l.minute(s),l.second(o),this.setStartDate(l),this.singleDatePicker?this.endDate=this.startDate.clone():this.endDate&&this.endDate.format("YYYY-MM-DD")==l.format("YYYY-MM-DD")&&this.endDate.isBefore(l)&&this.setEndDate(l.clone())}else if(this.endDate){var c=this.endDate.clone();c.hour(i),c.minute(s),c.second(o),this.setEndDate(c)}this.updateCalendars(),this.updateFormInputs(),this.renderTimePicker("left"),this.renderTimePicker("right")},formInputsChanged:function(n){var a=t(n.target).closest(".calendar").hasClass("right"),i=e(this.container.find('input[name="daterangepicker_start"]').val(),this.locale.format),s=e(this.container.find('input[name="daterangepicker_end"]').val(),this.locale.format);i.isValid()&&s.isValid()&&(a&&s.isBefore(i)&&(i=s.clone()),this.setStartDate(i),this.setEndDate(s),a?this.container.find('input[name="daterangepicker_start"]').val(this.startDate.format(this.locale.format)):this.container.find('input[name="daterangepicker_end"]').val(this.endDate.format(this.locale.format))),this.updateView()},formInputsFocused:function(e){this.container.find('input[name="daterangepicker_start"], input[name="daterangepicker_end"]').removeClass("active"),t(e.target).addClass("active");var n=t(e.target).closest(".calendar").hasClass("right");n&&(this.endDate=null,this.setStartDate(this.startDate.clone()),this.updateView())},formInputsBlurred:function(t){if(!this.endDate){var n=this.container.find('input[name="daterangepicker_end"]').val(),a=e(n,this.locale.format);a.isValid()&&(this.setEndDate(a),this.updateView())}},elementChanged:function(){if(this.element.is("input")&&this.element.val().length&&!(this.element.val().length<this.locale.format.length)){var t=this.element.val().split(this.locale.separator),n=null,a=null;2===t.length&&(n=e(t[0],this.locale.format),a=e(t[1],this.locale.format)),(this.singleDatePicker||null===n||null===a)&&(n=e(this.element.val(),this.locale.format),a=n),n.isValid()&&a.isValid()&&(this.setStartDate(n),this.setEndDate(a),this.updateView())}},keydown:function(e){9!==e.keyCode&&13!==e.keyCode||this.hide()},updateElement:function(){this.element.is("input")&&!this.singleDatePicker&&this.autoUpdateInput?(this.element.val(this.startDate.format(this.locale.format)+this.locale.separator+this.endDate.format(this.locale.format)),this.element.trigger("change")):this.element.is("input")&&this.autoUpdateInput&&(this.element.val(this.startDate.format(this.locale.format)),this.element.trigger("change"))},remove:function(){this.container.remove(),this.element.off(".daterangepicker"),this.element.removeData()}},t.fn.daterangepicker=function(e,a){return this.each(function(){var i=t(this);i.data("daterangepicker")&&i.data("daterangepicker").remove(),i.data("daterangepicker",new n(i,e,a))}),this},n}),$p.utils.__define({mime_db:{value:{"application/andrew-inset":{extensions:["ez"]},"application/applixware":{extensions:["aw"]},"application/atom+xml":{compressible:!0,extensions:["atom"]},"application/atomcat+xml":{extensions:["atomcat"]},"application/atomsvc+xml":{extensions:["atomsvc"]},"application/bdoc":{compressible:!1,extensions:["bdoc"]},"application/ccxml+xml":{extensions:["ccxml"]},"application/cdmi-capability":{extensions:["cdmia"]},"application/cdmi-container":{extensions:["cdmic"]},"application/cdmi-domain":{extensions:["cdmid"]},"application/cdmi-object":{extensions:["cdmio"]},"application/cdmi-queue":{extensions:["cdmiq"]},"application/cu-seeme":{extensions:["cu"]},"application/dash+xml":{extensions:["mpd"]},"application/davmount+xml":{extensions:["davmount"]},"application/docbook+xml":{extensions:["dbk"]},"application/dssc+der":{extensions:["dssc"]},"application/dssc+xml":{extensions:["xdssc"]},"application/ecmascript":{compressible:!0,extensions:["ecma"]},"application/emma+xml":{extensions:["emma"]},"application/epub+zip":{extensions:["epub"]},"application/exi":{extensions:["exi"]},"application/font-tdpfr":{extensions:["pfr"]},"application/font-woff":{compressible:!1,extensions:["woff"]},"application/font-woff2":{compressible:!1,extensions:["woff2"]},"application/gml+xml":{extensions:["gml"]},"application/gpx+xml":{extensions:["gpx"]},"application/gxf":{extensions:["gxf"]},"application/hyperstudio":{extensions:["stk"]},"application/inkml+xml":{extensions:["ink","inkml"]},"application/ipfix":{extensions:["ipfix"]},"application/java-archive":{compressible:!1,extensions:["jar","war","ear"]},"application/java-serialized-object":{compressible:!1,extensions:["ser"]},"application/java-vm":{compressible:!1,extensions:["class"]},"application/javascript":{charset:"UTF-8",compressible:!0,extensions:["js"]},"application/json":{charset:"UTF-8",compressible:!0,extensions:["json","map"]},"application/json-patch+json":{compressible:!0},"application/json5":{extensions:["json5"]},"application/jsonml+json":{compressible:!0,extensions:["jsonml"]},"application/ld+json":{compressible:!0,extensions:["jsonld"]},"application/lost+xml":{extensions:["lostxml"]},"application/mac-binhex40":{extensions:["hqx"]},"application/mac-compactpro":{extensions:["cpt"]},"application/mads+xml":{extensions:["mads"]},"application/manifest+json":{charset:"UTF-8",compressible:!0,extensions:["webmanifest"]},"application/marc":{extensions:["mrc"]},"application/marcxml+xml":{extensions:["mrcx"]},"application/mathematica":{extensions:["ma","nb","mb"]},"application/mathml+xml":{extensions:["mathml"]},"application/mbox":{extensions:["mbox"]},"application/mediaservercontrol+xml":{extensions:["mscml"]},"application/metalink+xml":{extensions:["metalink"]},"application/metalink4+xml":{extensions:["meta4"]},"application/mets+xml":{extensions:["mets"]},"application/mods+xml":{extensions:["mods"]},"application/mp21":{extensions:["m21","mp21"]},"application/mp4":{extensions:["mp4s","m4p"]},"application/msword":{compressible:!1,extensions:["doc","dot"]},"application/mxf":{extensions:["mxf"]},"application/octet-stream":{compressible:!1,extensions:["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"]},"application/oda":{extensions:["oda"]},"application/oebps-package+xml":{extensions:["opf"]},"application/ogg":{compressible:!1,extensions:["ogx"]},"application/omdoc+xml":{extensions:["omdoc"]},"application/onenote":{extensions:["onetoc","onetoc2","onetmp","onepkg"]},"application/oxps":{extensions:["oxps"]},"application/patch-ops-error+xml":{extensions:["xer"]},"application/pdf":{compressible:!1,extensions:["pdf"]},"application/pgp-encrypted":{compressible:!1,extensions:["pgp"]},"application/pgp-signature":{extensions:["asc","sig"]},"application/pics-rules":{extensions:["prf"]},"application/pkcs10":{extensions:["p10"]},"application/pkcs7-mime":{extensions:["p7m","p7c"]},"application/pkcs7-signature":{extensions:["p7s"]},"application/pkcs8":{extensions:["p8"]},"application/pkix-attr-cert":{extensions:["ac"]},"application/pkix-cert":{extensions:["cer"]},"application/pkix-crl":{extensions:["crl"]},"application/pkix-pkipath":{extensions:["pkipath"]},"application/pkixcmp":{extensions:["pki"]},"application/pls+xml":{extensions:["pls"]},"application/postscript":{compressible:!0,extensions:["ai","eps","ps"]},"application/prs.cww":{extensions:["cww"]},"application/pskc+xml":{extensions:["pskcxml"]},"application/rdf+xml":{compressible:!0,extensions:["rdf"]},"application/reginfo+xml":{extensions:["rif"]},"application/relax-ng-compact-syntax":{extensions:["rnc"]},"application/resource-lists+xml":{extensions:["rl"]},"application/resource-lists-diff+xml":{extensions:["rld"]},"application/rls-services+xml":{extensions:["rs"]},"application/rpki-ghostbusters":{extensions:["gbr"]},"application/rpki-manifest":{extensions:["mft"]},"application/rpki-roa":{extensions:["roa"]},"application/rsd+xml":{extensions:["rsd"]},"application/rss+xml":{compressible:!0,extensions:["rss"]},"application/rtf":{compressible:!0,extensions:["rtf"]},"application/sbml+xml":{extensions:["sbml"]},"application/scvp-cv-request":{extensions:["scq"]},"application/scvp-cv-response":{extensions:["scs"]},"application/scvp-vp-request":{extensions:["spq"]},"application/scvp-vp-response":{extensions:["spp"]},"application/sdp":{extensions:["sdp"]},"application/set-payment-initiation":{extensions:["setpay"]},"application/set-registration-initiation":{extensions:["setreg"]},"application/shf+xml":{extensions:["shf"]},"application/smil+xml":{extensions:["smi","smil"]},"application/sparql-query":{extensions:["rq"]},"application/sparql-results+xml":{extensions:["srx"]},"application/srgs":{extensions:["gram"]},"application/srgs+xml":{extensions:["grxml"]},"application/sru+xml":{extensions:["sru"]},"application/ssdl+xml":{extensions:["ssdl"]},"application/ssml+xml":{extensions:["ssml"]},"application/tei+xml":{extensions:["tei","teicorpus"]},"application/thraud+xml":{extensions:["tfi"]},"application/timestamped-data":{extensions:["tsd"]},"application/vnd.3gpp.pic-bw-large":{extensions:["plb"]},"application/vnd.3gpp.pic-bw-small":{extensions:["psb"]},"application/vnd.3gpp.pic-bw-var":{extensions:["pvb"]},"application/vnd.3gpp2.tcap":{extensions:["tcap"]},"application/vnd.3m.post-it-notes":{extensions:["pwn"]},"application/vnd.accpac.simply.aso":{extensions:["aso"]},"application/vnd.accpac.simply.imp":{extensions:["imp"]},"application/vnd.acucobol":{extensions:["acu"]},"application/vnd.acucorp":{extensions:["atc","acutc"]},"application/vnd.adobe.air-application-installer-package+zip":{extensions:["air"]},"application/vnd.adobe.formscentral.fcdt":{extensions:["fcdt"]},"application/vnd.adobe.fxp":{extensions:["fxp","fxpl"]},"application/vnd.adobe.xdp+xml":{extensions:["xdp"]},"application/vnd.adobe.xfdf":{extensions:["xfdf"]},"application/vnd.ahead.space":{extensions:["ahead"]},"application/vnd.airzip.filesecure.azf":{extensions:["azf"]},"application/vnd.airzip.filesecure.azs":{extensions:["azs"]},"application/vnd.amazon.ebook":{extensions:["azw"]},"application/vnd.americandynamics.acc":{extensions:["acc"]},"application/vnd.amiga.ami":{extensions:["ami"]},"application/vnd.android.package-archive":{compressible:!1,extensions:["apk"]},"application/vnd.anser-web-certificate-issue-initiation":{extensions:["cii"]},"application/vnd.anser-web-funds-transfer-initiation":{extensions:["fti"]},"application/vnd.antix.game-component":{extensions:["atx"]},"application/vnd.apple.installer+xml":{extensions:["mpkg"]},"application/vnd.apple.mpegurl":{extensions:["m3u8"]},"application/vnd.apple.pkpass":{compressible:!1,extensions:["pkpass"]},"application/vnd.aristanetworks.swi":{extensions:["swi"]},"application/vnd.astraea-software.iota":{extensions:["iota"]},"application/vnd.audiograph":{extensions:["aep"]},"application/vnd.blueice.multipass":{extensions:["mpm"]},"application/vnd.bmi":{extensions:["bmi"]},"application/vnd.businessobjects":{extensions:["rep"]},"application/vnd.chemdraw+xml":{extensions:["cdxml"]},"application/vnd.chipnuts.karaoke-mmd":{extensions:["mmd"]},"application/vnd.cinderella":{extensions:["cdy"]},"application/vnd.claymore":{extensions:["cla"]},"application/vnd.cloanto.rp9":{extensions:["rp9"]},"application/vnd.clonk.c4group":{extensions:["c4g","c4d","c4f","c4p","c4u"]},"application/vnd.cluetrust.cartomobile-config":{extensions:["c11amc"]},"application/vnd.cluetrust.cartomobile-config-pkg":{extensions:["c11amz"]},"application/vnd.commonspace":{extensions:["csp"]},"application/vnd.contact.cmsg":{extensions:["cdbcmsg"]},"application/vnd.cosmocaller":{extensions:["cmc"]},"application/vnd.crick.clicker":{extensions:["clkx"]},"application/vnd.crick.clicker.keyboard":{extensions:["clkk"]},"application/vnd.crick.clicker.palette":{extensions:["clkp"]},"application/vnd.crick.clicker.template":{extensions:["clkt"]},"application/vnd.crick.clicker.wordbank":{extensions:["clkw"]},"application/vnd.criticaltools.wbs+xml":{extensions:["wbs"]},"application/vnd.ctc-posml":{extensions:["pml"]},"application/vnd.cups-ppd":{extensions:["ppd"]},"application/vnd.curl.car":{extensions:["car"]},"application/vnd.curl.pcurl":{extensions:["pcurl"]},"application/vnd.dart":{compressible:!0,extensions:["dart"]},"application/vnd.data-vision.rdz":{extensions:["rdz"]},"application/vnd.dece.data":{extensions:["uvf","uvvf","uvd","uvvd"]},"application/vnd.dece.ttml+xml":{extensions:["uvt","uvvt"]},"application/vnd.dece.unspecified":{extensions:["uvx","uvvx"]},"application/vnd.dece.zip":{extensions:["uvz","uvvz"]},"application/vnd.denovo.fcselayout-link":{extensions:["fe_launch"]},"application/vnd.dna":{extensions:["dna"]},"application/vnd.dolby.mlp":{extensions:["mlp"]},"application/vnd.dpgraph":{extensions:["dpg"]},"application/vnd.dreamfactory":{extensions:["dfac"]},"application/vnd.ds-keypoint":{extensions:["kpxx"]},"application/vnd.dvb.ait":{extensions:["ait"]},"application/vnd.dvb.service":{extensions:["svc"]},"application/vnd.dynageo":{extensions:["geo"]},"application/vnd.ecowin.chart":{extensions:["mag"]},"application/vnd.enliven":{extensions:["nml"]},"application/vnd.epson.esf":{extensions:["esf"]},"application/vnd.epson.msf":{extensions:["msf"]},"application/vnd.epson.quickanime":{extensions:["qam"]},"application/vnd.epson.salt":{extensions:["slt"]},"application/vnd.epson.ssf":{extensions:["ssf"]},"application/vnd.eszigno3+xml":{extensions:["es3","et3"]},"application/vnd.ezpix-album":{extensions:["ez2"]},"application/vnd.ezpix-package":{extensions:["ez3"]},"application/vnd.fdf":{extensions:["fdf"]},"application/vnd.fdsn.mseed":{extensions:["mseed"]},"application/vnd.fdsn.seed":{extensions:["seed","dataless"]},"application/vnd.flographit":{extensions:["gph"]},"application/vnd.fluxtime.clip":{extensions:["ftc"]},"application/vnd.framemaker":{extensions:["fm","frame","maker","book"]},"application/vnd.frogans.fnc":{extensions:["fnc"]},"application/vnd.frogans.ltf":{extensions:["ltf"]},"application/vnd.fsc.weblaunch":{extensions:["fsc"]},"application/vnd.fujitsu.oasys":{extensions:["oas"]},"application/vnd.fujitsu.oasys2":{extensions:["oa2"]},"application/vnd.fujitsu.oasys3":{extensions:["oa3"]},"application/vnd.fujitsu.oasysgp":{extensions:["fg5"]},"application/vnd.fujitsu.oasysprs":{extensions:["bh2"]},"application/vnd.fujixerox.ddd":{extensions:["ddd"]},"application/vnd.fujixerox.docuworks":{extensions:["xdw"]},"application/vnd.fujixerox.docuworks.binder":{extensions:["xbd"]},"application/vnd.fuzzysheet":{extensions:["fzs"]},"application/vnd.genomatix.tuxedo":{extensions:["txd"]},"application/vnd.geogebra.file":{extensions:["ggb"]},"application/vnd.geogebra.tool":{extensions:["ggt"]},"application/vnd.geometry-explorer":{extensions:["gex","gre"]},"application/vnd.geonext":{extensions:["gxt"]},"application/vnd.geoplan":{extensions:["g2w"]},"application/vnd.geospace":{extensions:["g3w"]},"application/vnd.gmx":{extensions:["gmx"]},"application/vnd.google-apps.document":{compressible:!1,extensions:["gdoc"]},"application/vnd.google-apps.presentation":{compressible:!1,extensions:["gslides"]},"application/vnd.google-apps.spreadsheet":{compressible:!1,extensions:["gsheet"]},"application/vnd.google-earth.kml+xml":{compressible:!0,extensions:["kml"]},"application/vnd.google-earth.kmz":{compressible:!1,extensions:["kmz"]},"application/vnd.grafeq":{extensions:["gqf","gqs"]},"application/vnd.groove-account":{extensions:["gac"]},"application/vnd.groove-help":{extensions:["ghf"]},"application/vnd.groove-identity-message":{extensions:["gim"]},"application/vnd.groove-injector":{extensions:["grv"]},"application/vnd.groove-tool-message":{extensions:["gtm"]},"application/vnd.groove-tool-template":{extensions:["tpl"]},"application/vnd.groove-vcard":{extensions:["vcg"]},"application/vnd.hal+xml":{extensions:["hal"]},"application/vnd.handheld-entertainment+xml":{extensions:["zmm"]},"application/vnd.hbci":{extensions:["hbci"]},"application/vnd.hhe.lesson-player":{extensions:["les"]},"application/vnd.hp-hpgl":{extensions:["hpgl"]},"application/vnd.hp-hpid":{extensions:["hpid"]},"application/vnd.hp-hps":{extensions:["hps"]},"application/vnd.hp-jlyt":{extensions:["jlt"]},"application/vnd.hp-pcl":{extensions:["pcl"]},"application/vnd.hp-pclxl":{extensions:["pclxl"]},"application/vnd.hydrostatix.sof-data":{extensions:["sfd-hdstx"]},"application/vnd.ibm.minipay":{extensions:["mpy"]},"application/vnd.ibm.modcap":{extensions:["afp","listafp","list3820"]},"application/vnd.ibm.rights-management":{extensions:["irm"]},"application/vnd.ibm.secure-container":{extensions:["sc"]},"application/vnd.iccprofile":{extensions:["icc","icm"]},"application/vnd.igloader":{extensions:["igl"]},"application/vnd.immervision-ivp":{extensions:["ivp"]},"application/vnd.immervision-ivu":{extensions:["ivu"]},"application/vnd.insors.igm":{extensions:["igm"]},"application/vnd.intercon.formnet":{extensions:["xpw","xpx"]},"application/vnd.intergeo":{extensions:["i2g"]},"application/vnd.intu.qbo":{extensions:["qbo"]},"application/vnd.intu.qfx":{extensions:["qfx"]},"application/vnd.ipunplugged.rcprofile":{extensions:["rcprofile"]},"application/vnd.irepository.package+xml":{extensions:["irp"]},"application/vnd.is-xpr":{extensions:["xpr"]},"application/vnd.isac.fcs":{extensions:["fcs"]},"application/vnd.jam":{extensions:["jam"]},"application/vnd.jcp.javame.midlet-rms":{extensions:["rms"]},"application/vnd.jisp":{extensions:["jisp"]},"application/vnd.joost.joda-archive":{extensions:["joda"]},"application/vnd.kahootz":{extensions:["ktz","ktr"]},"application/vnd.kde.karbon":{extensions:["karbon"]},"application/vnd.kde.kchart":{extensions:["chrt"]},"application/vnd.kde.kformula":{extensions:["kfo"]},"application/vnd.kde.kivio":{extensions:["flw"]},"application/vnd.kde.kontour":{extensions:["kon"]},"application/vnd.kde.kpresenter":{extensions:["kpr","kpt"]},"application/vnd.kde.kspread":{extensions:["ksp"]},"application/vnd.kde.kword":{extensions:["kwd","kwt"]},"application/vnd.kenameaapp":{extensions:["htke"]},"application/vnd.kidspiration":{extensions:["kia"]},"application/vnd.kinar":{extensions:["kne","knp"]},"application/vnd.koan":{extensions:["skp","skd","skt","skm"]},"application/vnd.kodak-descriptor":{extensions:["sse"]},"application/vnd.las.las+xml":{extensions:["lasxml"]},"application/vnd.llamagraphics.life-balance.desktop":{extensions:["lbd"]},"application/vnd.llamagraphics.life-balance.exchange+xml":{extensions:["lbe"]},"application/vnd.lotus-1-2-3":{extensions:["123"]},"application/vnd.lotus-approach":{extensions:["apr"]},"application/vnd.lotus-freelance":{extensions:["pre"]},"application/vnd.lotus-notes":{extensions:["nsf"]},"application/vnd.lotus-organizer":{extensions:["org"]},"application/vnd.lotus-screencam":{extensions:["scm"]},"application/vnd.lotus-wordpro":{extensions:["lwp"]},"application/vnd.macports.portpkg":{extensions:["portpkg"]},"application/vnd.mcd":{extensions:["mcd"]},"application/vnd.medcalcdata":{extensions:["mc1"]},"application/vnd.mediastation.cdkey":{extensions:["cdkey"]},"application/vnd.mfer":{extensions:["mwf"]},"application/vnd.mfmp":{extensions:["mfm"]},"application/vnd.micrografx.flo":{extensions:["flo"]},"application/vnd.micrografx.igx":{extensions:["igx"]},"application/vnd.mif":{extensions:["mif"]},"application/vnd.mobius.daf":{extensions:["daf"]},"application/vnd.mobius.dis":{extensions:["dis"]},"application/vnd.mobius.mbk":{extensions:["mbk"]},"application/vnd.mobius.mqy":{extensions:["mqy"]},"application/vnd.mobius.msl":{extensions:["msl"]},"application/vnd.mobius.plc":{extensions:["plc"]},"application/vnd.mobius.txf":{extensions:["txf"]},"application/vnd.mophun.application":{extensions:["mpn"]},"application/vnd.mophun.certificate":{extensions:["mpc"]},"application/vnd.mozilla.xul+xml":{compressible:!0,extensions:["xul"]},"application/vnd.ms-cab-compressed":{extensions:["cab"]},"application/vnd.ms-excel":{compressible:!1,extensions:["xls","xlm","xla","xlc","xlt","xlw"]},"application/vnd.ms-excel.addin.macroenabled.12":{extensions:["xlam"]},"application/vnd.ms-excel.sheet.binary.macroenabled.12":{extensions:["xlsb"]},"application/vnd.ms-excel.sheet.macroenabled.12":{extensions:["xlsm"]},"application/vnd.ms-excel.template.macroenabled.12":{extensions:["xltm"]},"application/vnd.ms-fontobject":{compressible:!0,extensions:["eot"]},"application/vnd.ms-htmlhelp":{extensions:["chm"]},"application/vnd.ms-ims":{extensions:["ims"]},"application/vnd.ms-lrm":{extensions:["lrm"]},"application/vnd.ms-officetheme":{extensions:["thmx"]},"application/vnd.ms-opentype":{compressible:!0},"application/vnd.ms-pki.seccat":{extensions:["cat"]},"application/vnd.ms-pki.stl":{extensions:["stl"]},"application/vnd.ms-powerpoint":{compressible:!1,extensions:["ppt","pps","pot"]},"application/vnd.ms-powerpoint.addin.macroenabled.12":{extensions:["ppam"]},"application/vnd.ms-powerpoint.presentation.macroenabled.12":{extensions:["pptm"]},"application/vnd.ms-powerpoint.slide.macroenabled.12":{extensions:["sldm"]},"application/vnd.ms-powerpoint.slideshow.macroenabled.12":{extensions:["ppsm"]},"application/vnd.ms-powerpoint.template.macroenabled.12":{extensions:["potm"]},"application/vnd.ms-project":{extensions:["mpp","mpt"]},"application/vnd.ms-word.document.macroenabled.12":{extensions:["docm"]},"application/vnd.ms-word.template.macroenabled.12":{extensions:["dotm"]},"application/vnd.ms-works":{extensions:["wps","wks","wcm","wdb"]},"application/vnd.ms-wpl":{extensions:["wpl"]},"application/vnd.ms-xpsdocument":{compressible:!1,extensions:["xps"]},"application/vnd.mseq":{extensions:["mseq"]},"application/vnd.musician":{extensions:["mus"]},"application/vnd.muvee.style":{extensions:["msty"]},"application/vnd.mynfc":{extensions:["taglet"]},"application/vnd.neurolanguage.nlu":{extensions:["nlu"]},"application/vnd.nitf":{extensions:["ntf","nitf"]},"application/vnd.noblenet-directory":{extensions:["nnd"]},"application/vnd.noblenet-sealer":{extensions:["nns"]},"application/vnd.noblenet-web":{extensions:["nnw"]},"application/vnd.nokia.n-gage.data":{extensions:["ngdat"]},"application/vnd.nokia.n-gage.symbian.install":{extensions:["n-gage"]},"application/vnd.nokia.radio-preset":{extensions:["rpst"]},"application/vnd.nokia.radio-presets":{extensions:["rpss"]},"application/vnd.novadigm.edm":{extensions:["edm"]},"application/vnd.novadigm.edx":{extensions:["edx"]},"application/vnd.novadigm.ext":{extensions:["ext"]},"application/vnd.oasis.opendocument.chart":{extensions:["odc"]},"application/vnd.oasis.opendocument.chart-template":{extensions:["otc"]},"application/vnd.oasis.opendocument.database":{extensions:["odb"]},"application/vnd.oasis.opendocument.formula":{extensions:["odf"]},"application/vnd.oasis.opendocument.formula-template":{extensions:["odft"]},"application/vnd.oasis.opendocument.graphics":{compressible:!1,extensions:["odg"]},"application/vnd.oasis.opendocument.graphics-template":{extensions:["otg"]},"application/vnd.oasis.opendocument.image":{extensions:["odi"]},"application/vnd.oasis.opendocument.image-template":{extensions:["oti"]},"application/vnd.oasis.opendocument.presentation":{compressible:!1,extensions:["odp"]},"application/vnd.oasis.opendocument.presentation-template":{extensions:["otp"]},"application/vnd.oasis.opendocument.spreadsheet":{compressible:!1,extensions:["ods"]},"application/vnd.oasis.opendocument.spreadsheet-template":{extensions:["ots"]},"application/vnd.oasis.opendocument.text":{compressible:!1,extensions:["odt"]},"application/vnd.oasis.opendocument.text-master":{extensions:["odm"]},"application/vnd.oasis.opendocument.text-template":{extensions:["ott"]},"application/vnd.oasis.opendocument.text-web":{extensions:["oth"]},"application/vnd.olpc-sugar":{extensions:["xo"]},"application/vnd.oma.dd2+xml":{extensions:["dd2"]},"application/vnd.openofficeorg.extension":{extensions:["oxt"]},"application/vnd.openxmlformats-officedocument.presentationml.presentation":{compressible:!1,extensions:["pptx"]},"application/vnd.openxmlformats-officedocument.presentationml.slide":{extensions:["sldx"]},"application/vnd.openxmlformats-officedocument.presentationml.slideshow":{extensions:["ppsx"]},"application/vnd.openxmlformats-officedocument.presentationml.template":{extensions:["potx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":{compressible:!1,extensions:["xlsx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.template":{extensions:["xltx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.document":{compressible:!1,extensions:["docx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.template":{extensions:["dotx"]},"application/vnd.osgeo.mapguide.package":{extensions:["mgp"]},"application/vnd.osgi.dp":{extensions:["dp"]},"application/vnd.osgi.subsystem":{extensions:["esa"]},"application/vnd.palm":{extensions:["pdb","pqa","oprc"]},"application/vnd.pawaafile":{extensions:["paw"]},"application/vnd.pg.format":{extensions:["str"]},"application/vnd.pg.osasli":{extensions:["ei6"]},"application/vnd.picsel":{extensions:["efif"]},"application/vnd.pmi.widget":{extensions:["wg"]},"application/vnd.pocketlearn":{extensions:["plf"]},"application/vnd.powerbuilder6":{extensions:["pbd"]},"application/vnd.previewsystems.box":{extensions:["box"]},"application/vnd.proteus.magazine":{extensions:["mgz"]},"application/vnd.publishare-delta-tree":{extensions:["qps"]},"application/vnd.pvi.ptid1":{extensions:["ptid"]},"application/vnd.quark.quarkxpress":{extensions:["qxd","qxt","qwd","qwt","qxl","qxb"]},"application/vnd.realvnc.bed":{extensions:["bed"]},"application/vnd.recordare.musicxml":{extensions:["mxl"]},"application/vnd.recordare.musicxml+xml":{extensions:["musicxml"]},"application/vnd.rig.cryptonote":{extensions:["cryptonote"]},"application/vnd.rim.cod":{extensions:["cod"]},"application/vnd.rn-realmedia":{extensions:["rm"]},"application/vnd.rn-realmedia-vbr":{extensions:["rmvb"]},"application/vnd.route66.link66+xml":{extensions:["link66"]},"application/vnd.sailingtracker.track":{extensions:["st"]},"application/vnd.seemail":{extensions:["see"]},"application/vnd.sema":{extensions:["sema"]},"application/vnd.semd":{extensions:["semd"]},"application/vnd.semf":{extensions:["semf"]},"application/vnd.shana.informed.formdata":{extensions:["ifm"]},"application/vnd.shana.informed.formtemplate":{extensions:["itp"]},"application/vnd.shana.informed.interchange":{extensions:["iif"]},"application/vnd.shana.informed.package":{extensions:["ipk"]},"application/vnd.simtech-mindmapper":{extensions:["twd","twds"]},"application/vnd.smaf":{extensions:["mmf"]},"application/vnd.smart.teacher":{extensions:["teacher"]},"application/vnd.solent.sdkm+xml":{extensions:["sdkm","sdkd"]},"application/vnd.spotfire.dxp":{extensions:["dxp"]},"application/vnd.spotfire.sfs":{extensions:["sfs"]},"application/vnd.stardivision.calc":{extensions:["sdc"]},"application/vnd.stardivision.draw":{extensions:["sda"]},"application/vnd.stardivision.impress":{extensions:["sdd"]},"application/vnd.stardivision.math":{extensions:["smf"]},"application/vnd.stardivision.writer":{extensions:["sdw","vor"]},"application/vnd.stardivision.writer-global":{extensions:["sgl"]},"application/vnd.stepmania.package":{extensions:["smzip"]},"application/vnd.stepmania.stepchart":{extensions:["sm"]},"application/vnd.sun.xml.calc":{extensions:["sxc"]},"application/vnd.sun.xml.calc.template":{extensions:["stc"]},"application/vnd.sun.xml.draw":{extensions:["sxd"]},"application/vnd.sun.xml.draw.template":{extensions:["std"]},"application/vnd.sun.xml.impress":{extensions:["sxi"]},"application/vnd.sun.xml.impress.template":{extensions:["sti"]},"application/vnd.sun.xml.math":{extensions:["sxm"]},"application/vnd.sun.xml.writer":{extensions:["sxw"]},"application/vnd.sun.xml.writer.global":{extensions:["sxg"]},"application/vnd.sun.xml.writer.template":{extensions:["stw"]},"application/vnd.sus-calendar":{extensions:["sus","susp"]},"application/vnd.svd":{extensions:["svd"]},"application/vnd.symbian.install":{extensions:["sis","sisx"]},"application/vnd.syncml+xml":{extensions:["xsm"]},"application/vnd.syncml.dm+wbxml":{extensions:["bdm"]},"application/vnd.syncml.dm+xml":{extensions:["xdm"]},"application/vnd.tao.intent-module-archive":{extensions:["tao"]},"application/vnd.tcpdump.pcap":{extensions:["pcap","cap","dmp"]},"application/vnd.tmobile-livetv":{extensions:["tmo"]},"application/vnd.trid.tpt":{extensions:["tpt"]},"application/vnd.triscape.mxs":{extensions:["mxs"]},"application/vnd.trueapp":{extensions:["tra"]},"application/vnd.ufdl":{extensions:["ufd","ufdl"]},"application/vnd.uiq.theme":{extensions:["utz"]},"application/vnd.umajin":{extensions:["umj"]},"application/vnd.unity":{extensions:["unityweb"]},"application/vnd.uoml+xml":{extensions:["uoml"]},"application/vnd.vcx":{extensions:["vcx"]},"application/vnd.visio":{extensions:["vsd","vst","vss","vsw"]},"application/vnd.visionary":{extensions:["vis"]},"application/vnd.vsf":{extensions:["vsf"]},"application/vnd.wap.wbxml":{extensions:["wbxml"]},"application/vnd.wap.wmlc":{extensions:["wmlc"]},"application/vnd.wap.wmlscriptc":{extensions:["wmlsc"]},"application/vnd.webturbo":{extensions:["wtb"]},"application/vnd.wolfram.player":{extensions:["nbp"]},"application/vnd.wordperfect":{extensions:["wpd"]},"application/vnd.wqd":{extensions:["wqd"]},"application/vnd.wt.stf":{extensions:["stf"]},"application/vnd.xara":{extensions:["xar"]},"application/vnd.xfdl":{extensions:["xfdl"]},"application/vnd.yamaha.hv-dic":{extensions:["hvd"]},"application/vnd.yamaha.hv-script":{extensions:["hvs"]},"application/vnd.yamaha.hv-voice":{extensions:["hvp"]},"application/vnd.yamaha.openscoreformat":{extensions:["osf"]},"application/vnd.yamaha.openscoreformat.osfpvg+xml":{extensions:["osfpvg"]},"application/vnd.yamaha.smaf-audio":{extensions:["saf"]},"application/vnd.yamaha.smaf-phrase":{extensions:["spf"]},"application/vnd.yellowriver-custom-menu":{extensions:["cmp"]},"application/vnd.zul":{extensions:["zir","zirz"]},"application/vnd.zzazz.deck+xml":{extensions:["zaz"]},"application/voicexml+xml":{extensions:["vxml"]},"application/widget":{extensions:["wgt"]},"application/winhlp":{extensions:["hlp"]},"application/wsdl+xml":{extensions:["wsdl"]},"application/wspolicy+xml":{extensions:["wspolicy"]},"application/x-7z-compressed":{compressible:!1,extensions:["7z"]},"application/x-abiword":{extensions:["abw"]},"application/x-ace-compressed":{ extensions:["ace"]},"application/x-apple-diskimage":{extensions:["dmg"]},"application/x-authorware-bin":{extensions:["aab","x32","u32","vox"]},"application/x-authorware-map":{extensions:["aam"]},"application/x-authorware-seg":{extensions:["aas"]},"application/x-bcpio":{extensions:["bcpio"]},"application/x-bdoc":{compressible:!1,extensions:["bdoc"]},"application/x-bittorrent":{extensions:["torrent"]},"application/x-blorb":{extensions:["blb","blorb"]},"application/x-bzip":{compressible:!1,extensions:["bz"]},"application/x-bzip2":{compressible:!1,extensions:["bz2","boz"]},"application/x-cbr":{extensions:["cbr","cba","cbt","cbz","cb7"]},"application/x-cdlink":{extensions:["vcd"]},"application/x-cfs-compressed":{extensions:["cfs"]},"application/x-chat":{extensions:["chat"]},"application/x-chess-pgn":{extensions:["pgn"]},"application/x-chrome-extension":{extensions:["crx"]},"application/x-cocoa":{source:"nginx",extensions:["cco"]},"application/x-conference":{extensions:["nsc"]},"application/x-cpio":{extensions:["cpio"]},"application/x-csh":{extensions:["csh"]},"application/x-debian-package":{extensions:["deb","udeb"]},"application/x-dgc-compressed":{extensions:["dgc"]},"application/x-director":{extensions:["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"]},"application/x-doom":{extensions:["wad"]},"application/x-dtbncx+xml":{extensions:["ncx"]},"application/x-dtbook+xml":{extensions:["dtb"]},"application/x-dtbresource+xml":{extensions:["res"]},"application/x-dvi":{compressible:!1,extensions:["dvi"]},"application/x-envoy":{extensions:["evy"]},"application/x-eva":{extensions:["eva"]},"application/x-font-bdf":{extensions:["bdf"]},"application/x-font-ghostscript":{extensions:["gsf"]},"application/x-font-linux-psf":{extensions:["psf"]},"application/x-font-otf":{compressible:!0,extensions:["otf"]},"application/x-font-pcf":{extensions:["pcf"]},"application/x-font-snf":{extensions:["snf"]},"application/x-font-ttf":{compressible:!0,extensions:["ttf","ttc"]},"application/x-font-type1":{extensions:["pfa","pfb","pfm","afm"]},"application/x-freearc":{extensions:["arc"]},"application/x-futuresplash":{extensions:["spl"]},"application/x-gca-compressed":{extensions:["gca"]},"application/x-glulx":{extensions:["ulx"]},"application/x-gnumeric":{extensions:["gnumeric"]},"application/x-gramps-xml":{extensions:["gramps"]},"application/x-gtar":{extensions:["gtar"]},"application/x-hdf":{extensions:["hdf"]},"application/x-httpd-php":{compressible:!0,extensions:["php"]},"application/x-install-instructions":{extensions:["install"]},"application/x-iso9660-image":{extensions:["iso"]},"application/x-java-archive-diff":{source:"nginx",extensions:["jardiff"]},"application/x-java-jnlp-file":{compressible:!1,extensions:["jnlp"]},"application/x-latex":{compressible:!1,extensions:["latex"]},"application/x-lua-bytecode":{extensions:["luac"]},"application/x-lzh-compressed":{extensions:["lzh","lha"]},"application/x-makeself":{source:"nginx",extensions:["run"]},"application/x-mie":{extensions:["mie"]},"application/x-mobipocket-ebook":{extensions:["prc","mobi"]},"application/x-ms-application":{extensions:["application"]},"application/x-ms-shortcut":{extensions:["lnk"]},"application/x-ms-wmd":{extensions:["wmd"]},"application/x-ms-wmz":{extensions:["wmz"]},"application/x-ms-xbap":{extensions:["xbap"]},"application/x-msaccess":{extensions:["mdb"]},"application/x-msbinder":{extensions:["obd"]},"application/x-mscardfile":{extensions:["crd"]},"application/x-msclip":{extensions:["clp"]},"application/x-msdos-program":{extensions:["exe"]},"application/x-msdownload":{extensions:["exe","dll","com","bat","msi"]},"application/x-msmediaview":{extensions:["mvb","m13","m14"]},"application/x-msmetafile":{extensions:["wmf","wmz","emf","emz"]},"application/x-msmoney":{extensions:["mny"]},"application/x-mspublisher":{extensions:["pub"]},"application/x-msschedule":{extensions:["scd"]},"application/x-msterminal":{extensions:["trm"]},"application/x-mswrite":{extensions:["wri"]},"application/x-netcdf":{extensions:["nc","cdf"]},"application/x-ns-proxy-autoconfig":{compressible:!0,extensions:["pac"]},"application/x-nzb":{extensions:["nzb"]},"application/x-perl":{source:"nginx",extensions:["pl","pm"]},"application/x-pilot":{source:"nginx",extensions:["prc","pdb"]},"application/x-pkcs12":{compressible:!1,extensions:["p12","pfx"]},"application/x-pkcs7-certificates":{extensions:["p7b","spc"]},"application/x-pkcs7-certreqresp":{extensions:["p7r"]},"application/x-rar-compressed":{compressible:!1,extensions:["rar"]},"application/x-redhat-package-manager":{source:"nginx",extensions:["rpm"]},"application/x-research-info-systems":{extensions:["ris"]},"application/x-sea":{source:"nginx",extensions:["sea"]},"application/x-sh":{compressible:!0,extensions:["sh"]},"application/x-shar":{extensions:["shar"]},"application/x-shockwave-flash":{compressible:!1,extensions:["swf"]},"application/x-silverlight-app":{extensions:["xap"]},"application/x-sql":{extensions:["sql"]},"application/x-stuffit":{compressible:!1,extensions:["sit"]},"application/x-stuffitx":{extensions:["sitx"]},"application/x-subrip":{extensions:["srt"]},"application/x-sv4cpio":{extensions:["sv4cpio"]},"application/x-sv4crc":{extensions:["sv4crc"]},"application/x-t3vm-image":{extensions:["t3"]},"application/x-tads":{extensions:["gam"]},"application/x-tar":{compressible:!0,extensions:["tar"]},"application/x-tcl":{extensions:["tcl","tk"]},"application/x-tex":{extensions:["tex"]},"application/x-tex-tfm":{extensions:["tfm"]},"application/x-texinfo":{extensions:["texinfo","texi"]},"application/x-tgif":{extensions:["obj"]},"application/x-ustar":{extensions:["ustar"]},"application/x-wais-source":{extensions:["src"]},"application/x-web-app-manifest+json":{compressible:!0,extensions:["webapp"]},"application/x-x509-ca-cert":{extensions:["der","crt","pem"]},"application/x-xfig":{extensions:["fig"]},"application/x-xliff+xml":{extensions:["xlf"]},"application/x-xpinstall":{compressible:!1,extensions:["xpi"]},"application/x-xz":{extensions:["xz"]},"application/x-zmachine":{extensions:["z1","z2","z3","z4","z5","z6","z7","z8"]},"application/xaml+xml":{extensions:["xaml"]},"application/xcap-diff+xml":{extensions:["xdf"]},"application/xenc+xml":{extensions:["xenc"]},"application/xhtml+xml":{compressible:!0,extensions:["xhtml","xht"]},"application/xml":{compressible:!0,extensions:["xml","xsl","xsd","rng"]},"application/xml-dtd":{compressible:!0,extensions:["dtd"]},"application/xop+xml":{compressible:!0,extensions:["xop"]},"application/xproc+xml":{extensions:["xpl"]},"application/xslt+xml":{extensions:["xslt"]},"application/xspf+xml":{extensions:["xspf"]},"application/xv+xml":{extensions:["mxml","xhvml","xvml","xvm"]},"application/yang":{extensions:["yang"]},"application/yin+xml":{extensions:["yin"]},"application/zip":{compressible:!1,extensions:["zip"]},"audio/3gpp":{compressible:!1,extensions:["3gpp"]},"audio/adpcm":{extensions:["adp"]},"audio/basic":{compressible:!1,extensions:["au","snd"]},"audio/midi":{extensions:["mid","midi","kar","rmi"]},"audio/mp4":{compressible:!1,extensions:["m4a","mp4a"]},"audio/mpeg":{compressible:!1,extensions:["mpga","mp2","mp2a","mp3","m2a","m3a"]},"audio/ogg":{compressible:!1,extensions:["oga","ogg","spx"]},"audio/s3m":{extensions:["s3m"]},"audio/silk":{extensions:["sil"]},"audio/vnd.dece.audio":{extensions:["uva","uvva"]},"audio/vnd.digital-winds":{extensions:["eol"]},"audio/vnd.dra":{extensions:["dra"]},"audio/vnd.dts":{extensions:["dts"]},"audio/vnd.dts.hd":{extensions:["dtshd"]},"audio/vnd.lucent.voice":{extensions:["lvp"]},"audio/vnd.ms-playready.media.pya":{extensions:["pya"]},"audio/vnd.nuera.ecelp4800":{extensions:["ecelp4800"]},"audio/vnd.nuera.ecelp7470":{extensions:["ecelp7470"]},"audio/vnd.nuera.ecelp9600":{extensions:["ecelp9600"]},"audio/vnd.rip":{extensions:["rip"]},"audio/wav":{compressible:!1,extensions:["wav"]},"audio/wave":{compressible:!1,extensions:["wav"]},"audio/webm":{compressible:!1,extensions:["weba"]},"audio/x-aac":{compressible:!1,extensions:["aac"]},"audio/x-aiff":{extensions:["aif","aiff","aifc"]},"audio/x-caf":{compressible:!1,extensions:["caf"]},"audio/x-flac":{extensions:["flac"]},"audio/x-m4a":{source:"nginx",extensions:["m4a"]},"audio/x-matroska":{extensions:["mka"]},"audio/x-mpegurl":{extensions:["m3u"]},"audio/x-ms-wax":{extensions:["wax"]},"audio/x-ms-wma":{extensions:["wma"]},"audio/x-pn-realaudio":{extensions:["ram","ra"]},"audio/x-pn-realaudio-plugin":{extensions:["rmp"]},"audio/x-realaudio":{source:"nginx",extensions:["ra"]},"audio/x-wav":{extensions:["wav"]},"audio/xm":{extensions:["xm"]},"chemical/x-cdx":{extensions:["cdx"]},"chemical/x-cif":{extensions:["cif"]},"chemical/x-cmdf":{extensions:["cmdf"]},"chemical/x-cml":{extensions:["cml"]},"chemical/x-csml":{extensions:["csml"]},"chemical/x-xyz":{extensions:["xyz"]},"font/opentype":{compressible:!0,extensions:["otf"]},"image/bmp":{compressible:!0,extensions:["bmp"]},"image/cgm":{extensions:["cgm"]},"image/g3fax":{extensions:["g3"]},"image/gif":{compressible:!1,extensions:["gif"]},"image/ief":{extensions:["ief"]},"image/jpeg":{compressible:!1,extensions:["jpeg","jpg","jpe"]},"image/ktx":{extensions:["ktx"]},"image/png":{compressible:!1,extensions:["png"]},"image/prs.btif":{extensions:["btif"]},"image/sgi":{extensions:["sgi"]},"image/svg+xml":{compressible:!0,extensions:["svg","svgz"]},"image/tiff":{compressible:!1,extensions:["tiff","tif"]},"image/vnd.adobe.photoshop":{compressible:!0,extensions:["psd"]},"image/vnd.dece.graphic":{extensions:["uvi","uvvi","uvg","uvvg"]},"image/vnd.djvu":{extensions:["djvu","djv"]},"image/vnd.dvb.subtitle":{extensions:["sub"]},"image/vnd.dwg":{extensions:["dwg"]},"image/vnd.dxf":{extensions:["dxf"]},"image/vnd.fastbidsheet":{extensions:["fbs"]},"image/vnd.fpx":{extensions:["fpx"]},"image/vnd.fst":{extensions:["fst"]},"image/vnd.fujixerox.edmics-mmr":{extensions:["mmr"]},"image/vnd.fujixerox.edmics-rlc":{extensions:["rlc"]},"image/vnd.ms-modi":{extensions:["mdi"]},"image/vnd.ms-photo":{extensions:["wdp"]},"image/vnd.net-fpx":{extensions:["npx"]},"image/vnd.wap.wbmp":{extensions:["wbmp"]},"image/vnd.xiff":{extensions:["xif"]},"image/webp":{extensions:["webp"]},"image/x-3ds":{extensions:["3ds"]},"image/x-cmu-raster":{extensions:["ras"]},"image/x-cmx":{extensions:["cmx"]},"image/x-freehand":{extensions:["fh","fhc","fh4","fh5","fh7"]},"image/x-icon":{compressible:!0,extensions:["ico"]},"image/x-jng":{source:"nginx",extensions:["jng"]},"image/x-mrsid-image":{extensions:["sid"]},"image/x-ms-bmp":{source:"nginx",compressible:!0,extensions:["bmp"]},"image/x-pcx":{extensions:["pcx"]},"image/x-pict":{extensions:["pic","pct"]},"image/x-portable-anymap":{extensions:["pnm"]},"image/x-portable-bitmap":{extensions:["pbm"]},"image/x-portable-graymap":{extensions:["pgm"]},"image/x-portable-pixmap":{extensions:["ppm"]},"image/x-rgb":{extensions:["rgb"]},"image/x-tga":{extensions:["tga"]},"image/x-xbitmap":{extensions:["xbm"]},"image/x-xpixmap":{extensions:["xpm"]},"image/x-xwindowdump":{extensions:["xwd"]},"message/rfc822":{compressible:!0,extensions:["eml","mime"]},"model/iges":{compressible:!1,extensions:["igs","iges"]},"model/mesh":{compressible:!1,extensions:["msh","mesh","silo"]},"model/vnd.collada+xml":{extensions:["dae"]},"model/vnd.dwf":{extensions:["dwf"]},"model/vnd.gdl":{extensions:["gdl"]},"model/vnd.gtw":{extensions:["gtw"]},"model/vnd.mts":{extensions:["mts"]},"model/vnd.vtu":{extensions:["vtu"]},"model/vrml":{compressible:!1,extensions:["wrl","vrml"]},"model/x3d+binary":{compressible:!1,extensions:["x3db","x3dbz"]},"model/x3d+vrml":{compressible:!1,extensions:["x3dv","x3dvz"]},"model/x3d+xml":{compressible:!0,extensions:["x3d","x3dz"]},"text/cache-manifest":{compressible:!0,extensions:["appcache","manifest"]},"text/calendar":{extensions:["ics","ifb"]},"text/coffeescript":{extensions:["coffee","litcoffee"]},"text/css":{compressible:!0,extensions:["css"]},"text/csv":{compressible:!0,extensions:["csv"]},"text/hjson":{extensions:["hjson"]},"text/html":{compressible:!0,extensions:["html","htm","shtml"]},"text/jade":{extensions:["jade"]},"text/jsx":{compressible:!0,extensions:["jsx"]},"text/less":{extensions:["less"]},"text/mathml":{source:"nginx",extensions:["mml"]},"text/n3":{compressible:!0,extensions:["n3"]},"text/plain":{compressible:!0,extensions:["txt","text","conf","def","list","log","in","ini"]},"text/prs.lines.tag":{extensions:["dsc"]},"text/richtext":{compressible:!0,extensions:["rtx"]},"text/rtf":{compressible:!0,extensions:["rtf"]},"text/sgml":{extensions:["sgml","sgm"]},"text/slim":{extensions:["slim","slm"]},"text/stylus":{extensions:["stylus","styl"]},"text/tab-separated-values":{compressible:!0,extensions:["tsv"]},"text/troff":{extensions:["t","tr","roff","man","me","ms"]},"text/turtle":{extensions:["ttl"]},"text/uri-list":{compressible:!0,extensions:["uri","uris","urls"]},"text/vcard":{compressible:!0,extensions:["vcard"]},"text/vnd.curl":{extensions:["curl"]},"text/vnd.curl.dcurl":{extensions:["dcurl"]},"text/vnd.curl.mcurl":{extensions:["mcurl"]},"text/vnd.curl.scurl":{extensions:["scurl"]},"text/vnd.dvb.subtitle":{extensions:["sub"]},"text/vnd.fly":{extensions:["fly"]},"text/vnd.fmi.flexstor":{extensions:["flx"]},"text/vnd.graphviz":{extensions:["gv"]},"text/vnd.in3d.3dml":{extensions:["3dml"]},"text/vnd.in3d.spot":{extensions:["spot"]},"text/vnd.sun.j2me.app-descriptor":{extensions:["jad"]},"text/vnd.wap.wml":{extensions:["wml"]},"text/vnd.wap.wmlscript":{extensions:["wmls"]},"text/vtt":{charset:"UTF-8",compressible:!0,extensions:["vtt"]},"text/x-asm":{extensions:["s","asm"]},"text/x-c":{extensions:["c","cc","cxx","cpp","h","hh","dic"]},"text/x-component":{source:"nginx",extensions:["htc"]},"text/x-fortran":{extensions:["f","for","f77","f90"]},"text/x-handlebars-template":{extensions:["hbs"]},"text/x-java-source":{extensions:["java"]},"text/x-lua":{extensions:["lua"]},"text/x-markdown":{compressible:!0,extensions:["markdown","md","mkd"]},"text/x-nfo":{extensions:["nfo"]},"text/x-opml":{extensions:["opml"]},"text/x-pascal":{extensions:["p","pas"]},"text/x-processing":{compressible:!0,extensions:["pde"]},"text/x-sass":{extensions:["sass"]},"text/x-scss":{extensions:["scss"]},"text/x-setext":{extensions:["etx"]},"text/x-sfv":{extensions:["sfv"]},"text/x-suse-ymp":{compressible:!0,extensions:["ymp"]},"text/x-uuencode":{extensions:["uu"]},"text/x-vcalendar":{extensions:["vcs"]},"text/x-vcard":{extensions:["vcf"]},"text/xml":{source:"iana",compressible:!0,extensions:["xml"]},"text/yaml":{extensions:["yaml","yml"]},"video/3gpp":{extensions:["3gp","3gpp"]},"video/3gpp2":{extensions:["3g2"]},"video/h261":{extensions:["h261"]},"video/h263":{extensions:["h263"]},"video/h264":{extensions:["h264"]},"video/jpeg":{extensions:["jpgv"]},"video/jpm":{extensions:["jpm","jpgm"]},"video/mj2":{extensions:["mj2","mjp2"]},"video/mp2t":{extensions:["ts"]},"video/mp4":{compressible:!1,extensions:["mp4","mp4v","mpg4"]},"video/mpeg":{compressible:!1,extensions:["mpeg","mpg","mpe","m1v","m2v"]},"video/ogg":{compressible:!1,extensions:["ogv"]},"video/quicktime":{compressible:!1,extensions:["qt","mov"]},"video/vnd.dece.hd":{extensions:["uvh","uvvh"]},"video/vnd.dece.mobile":{extensions:["uvm","uvvm"]},"video/vnd.dece.pd":{extensions:["uvp","uvvp"]},"video/vnd.dece.sd":{extensions:["uvs","uvvs"]},"video/vnd.dece.video":{extensions:["uvv","uvvv"]},"video/vnd.dvb.file":{extensions:["dvb"]},"video/vnd.fvt":{extensions:["fvt"]},"video/vnd.mpegurl":{extensions:["mxu","m4u"]},"video/vnd.ms-playready.media.pyv":{extensions:["pyv"]},"video/vnd.uvvu.mp4":{extensions:["uvu","uvvu"]},"video/vnd.vivo":{extensions:["viv"]},"video/webm":{compressible:!1,extensions:["webm"]},"video/x-f4v":{extensions:["f4v"]},"video/x-fli":{extensions:["fli"]},"video/x-flv":{compressible:!1,extensions:["flv"]},"video/x-m4v":{extensions:["m4v"]},"video/x-matroska":{compressible:!1,extensions:["mkv","mk3d","mks"]},"video/x-mng":{extensions:["mng"]},"video/x-ms-asf":{extensions:["asf","asx"]},"video/x-ms-vob":{extensions:["vob"]},"video/x-ms-wm":{extensions:["wm"]},"video/x-ms-wmv":{compressible:!1,extensions:["wmv"]},"video/x-ms-wmx":{extensions:["wmx"]},"video/x-ms-wvx":{extensions:["wvx"]},"video/x-msvideo":{extensions:["avi"]},"video/x-sgi-movie":{extensions:["movie"]},"video/x-smv":{extensions:["smv"]},"x-conference/x-cooltalk":{extensions:["ice"]}}},mime_lookup:{value:function(e){if(!e)return"application/octet-stream";e=e.toLowerCase();for(var t in this.mime_db)if(this.mime_db[t].extensions&&this.mime_db[t].extensions.indexOf(e)!=-1)return t;return"application/octet-stream"}}}),$p}); \ No newline at end of file diff --git a/gulpfile.js b/gulpfile.js index e5e975f17..99b7747e3 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -312,6 +312,7 @@ gulp.task('build--core', function(){ './packages/metadata-core/src/mngrs.js', './packages/metadata-core/src/objs.js', './packages/metadata-core/src/tabulars.js', + './packages/metadata-core/src/meta_sys.js', './packages/metadata-core/src/meta.js', './packages/metadata-core/lib/aes.js', './packages/metadata-core/src/common.js' diff --git a/history.md b/history.md index 15d7ab878..d9977d906 100644 --- a/history.md +++ b/history.md @@ -1,5 +1,8 @@ # v0.11.223 +### 03.12.2016 +- Методы подготовки системных метаданных (журнал регистрации, системные перечисления, настройки отчетов и динсписков) удалены из 1С и перемещены в конструктор _Meta_ + ### 02.12.2016 - Подключаемый обработчик нажатия кнопок панели инструментов формы _wnd_selection_ - В атрибутах метода _Pouch.save_obj_ учтено значение _db_, что позволяет сохранить текущий объект в другой базе. Например, зарегистрировать изменения объекта с типом кеширования _ram_ на сервере diff --git a/lib/metadata.core.js b/lib/metadata.core.js index 233890e92..661282cbc 100644 --- a/lib/metadata.core.js +++ b/lib/metadata.core.js @@ -1,5 +1,5 @@ /*! - metadata.js v0.11.223, built:2016-12-02 © Evgeniy Malyarov http://www.oknosoft.ru 2014-2016 + metadata.js v0.12.225, built:2016-12-03 © Evgeniy Malyarov http://www.oknosoft.ru 2014-2016 metadata.js may be freely distributed under the AGPL-3.0. To obtain _Oknosoft Commercial license_, contact info@oknosoft.ru */ (function(root, factory) { @@ -289,7 +289,7 @@ function MetaEngine() { this.__define({ version: { - value: "0.11.223", + value: "0.12.225", writable: false }, @@ -653,8 +653,8 @@ function MetaEngine() { */ record_log: { value: function (err) { - if($p.ireg && $p.ireg.$log) - $p.ireg.$log.record(err); + if($p.ireg && $p.ireg.log) + $p.ireg.log.record(err); console.log(err); } }, @@ -954,6 +954,18 @@ function MetaEngine() { value: LogManager }, + MetaObjManager: { + value: MetaObjManager + }, + + MetaFieldManager: { + value: MetaFieldManager + }, + + SchemeSettingsManager: { + value: SchemeSettingsManager + }, + AccumRegManager: { value: AccumRegManager }, @@ -1023,6 +1035,7 @@ function MetaEngine() { } }); + } /** @@ -1366,16 +1379,16 @@ function Ajax() { if(typeof auth == "object" && auth.username && auth.hasOwnProperty("password")){ username = auth.username; password = auth.password; - + }else{ if($p.ajax.username && $p.ajax.authorized){ username = $p.ajax.username; password = $p.aes.Ctr.decrypt($p.ajax.password); - + }else{ username = $p.wsql.get_user_param("user_name"); password = $p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd")); - + if(!username && $p.job_prm && $p.job_prm.guest_name){ username = $p.job_prm.guest_name; password = $p.aes.Ctr.decrypt($p.job_prm.guest_pwd); @@ -2973,11 +2986,419 @@ function Pouch(){ */ function Meta() { - var _m; + var _m = { + enm: { + accumulation_record_type: [ + { + order: 0, + name: "debit", + synonym: "Приход" + }, + { + order: 1, + name: "credit", + synonym: "Расход" + } + ], + comparison_types: [ + { + order: 0, + name: "gt", + synonym: "Больше" + }, + { + order: 1, + name: "gte", + synonym: "Больше или равно" + }, + { + order: 2, + name: "lt", + synonym: "Меньше" + }, + { + order: 3, + name: "lte", + synonym: "Меньше или равно " + }, + { + order: 4, + name: "eq", + synonym: "Равно" + }, + { + order: 5, + name: "ne", + synonym: "Не равно" + }, + { + "order": 6, + "name": "in", + "synonym": "В списке" + }, + { + order: 7, + name: "nin", + synonym: "Не в списке" + }, + { + order: 8, + name: "lke", + synonym: "Подобно " + }, + { + order: 9, + name: "nlk", + synonym: "Не подобно" + } + ] + }, + cat: { + meta_objs: {}, + meta_fields: {}, + scheme_settings: { + name: "scheme_settings", + splitted: true, + synonym: "Настройки отчетов и списков", + illustration: "", + obj_presentation: "", + list_presentation: "", + input_by_string: [ + "name" + ], + hierarchical: false, + has_owners: false, + group_hierarchy: true, + main_presentation_name: true, + code_length: 0, + fields: { + obj: { + "synonym": "Объект", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 250 + } + }, + user: { + "synonym": "Пользователь", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 50 + } + }, + predefined_name: { + "synonym": "", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 256 + } + } + }, + tabular_sections: { + available_fields: { + "name": "available_fields", + "synonym": "Доступные поля", + "tooltip": "Состав, порядок и ширина колонок", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "Для плоского списка, родитель пустой", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "use": { + "synonym": "Использование", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "boolean" + ] + } + }, + "field": { + "synonym": "Поле", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "width": { + "synonym": "Ширина", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "number" + ], + "digits": 6, + "fraction_figits": 0 + } + }, + "caption": { + "synonym": "Заголовок", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + sort_fields: { + "name": "sort_fields", + "synonym": "Поля сортировки", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "field": { + "synonym": "Поле", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + grouping_fields: { + "name": "grouping_fields", + "synonym": "Поля группировки", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "field": { + "synonym": "Поле", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + selection: { + "name": "selection", + "synonym": "Отбор", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "use": { + "synonym": "Использование", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "boolean" + ] + } + }, + "left_value": { + "synonym": "Левое значение", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "comparison_type": { + "synonym": "Вид сравнения", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "right_value": { + "synonym": "Правое значение", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + scheme: { + "name": "scheme", + "synonym": "Структура", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 10 + } + }, + "kind": { + "synonym": "Вид раздела отчета", + "multiline_mode": false, + "tooltip": "список, таблица, группировка строк, группировка колонок", + "type": { + "types": [ + "string" + ], + "str_len": 10 + } + } + } + } + }, + cachable: "doc" + } + }, + doc: {}, + ireg: { + "log": { + name: "log", + note: "", + synonym: "Журнал событий", + dimensions: { + date: { + synonym: "Дата", + multiline_mode: false, + tooltip: "Время события", + type: { + types: [ + "number" + ], + digits: 15, + fraction_figits: 0 + } + }, + sequence: { + synonym: "Порядок", + multiline_mode: false, + tooltip: "Порядок следования", + type: { + types: [ + "number" + ], + digits: 6, + fraction_figits: 0 + } + } + }, + resources: { + "class": { + synonym: "Класс", + multiline_mode: false, + tooltip: "Класс события", + type: { + types: [ + "string" + ], + str_len: 100 + } + }, + note: { + synonym: "Комментарий", + multiline_mode: true, + tooltip: "Текст события", + type: { + types: [ + "string" + ], + str_len: 0 + } + }, + obj: { + synonym: "Объект", + multiline_mode: true, + tooltip: "Объект, к которому относится событие", + type: { + types: [ + "string" + ], + str_len: 0 + } + } + } + } + }, + areg: {}, + dp: {}, + rep: {}, + cch: {}, + cacc: {} + }; _md = this; - // загружает метаданные из pouchdb function meta_from_pouch(meta_db){ @@ -2987,7 +3408,7 @@ function Meta() { }) .then(function (doc) { - _m = doc; + $p._patch(_m, doc); doc = null; return meta_db.get('meta_patch'); @@ -3024,7 +3445,7 @@ function Meta() { function do_init(){ if(meta_db && !is_local && !is_remote){ - _m = meta_db; + $p._patch(_m, meta_db); meta_db = null; _md.create_managers(); @@ -3055,7 +3476,7 @@ function Meta() { if(!_m) do_init(); - else{ + else if($p.iface && $p.iface.do_reload){ // если изменились метаданные, запланировать перезагрузку setTimeout(function () { @@ -3700,7 +4121,7 @@ function DataManager(class_name){ * ### После чтения объекта с сервера * Имеет смысл для объектов с типом кеширования ("doc", "doc_remote", "meta", "e1cib"). * т.к. структура _DataObj_ может отличаться от прототипа в базе-источнике, в обработчике можно дозаполнить или пересчитать реквизиты прочитанного объекта - * + * * @event after_load * @for DataManager */ @@ -4068,7 +4489,7 @@ DataManager.prototype.sync_grid = function(attr, grid){ if(typeof attr.custom_selection == "function"){ return attr.custom_selection(attr); - + }else if(mgr.cachable == "ram"){ // запрос к alasql @@ -4132,7 +4553,7 @@ DataManager.prototype.sync_grid = function(attr, grid){ }); } - + // TODO: переделать обработку catch() return request() .then(to_grid) @@ -4425,8 +4846,8 @@ DataManager.prototype.print = function(ref, model, wnd){ // если _printing_plates содержит ссылку на обрабочтик печати, используем его if(this._printing_plates[model] instanceof DataObj) - model = this._printing_plates[model]; - + model = this._printing_plates[model]; + // если существует локальный обработчик, используем его if(model instanceof DataObj && model.execute){ @@ -4439,7 +4860,7 @@ DataManager.prototype.print = function(ref, model, wnd){ .then(tune_wnd_print); }else{ - + // иначе - печатаем средствами 1С или иного сервера var rattr = {}; $p.ajax.default_attr(rattr, $p.job_prm.irest_url()); @@ -4499,9 +4920,9 @@ DataManager.prototype.printing_plates = function(){ * @param class_name {string} - имя типа менеджера объекта */ function RefDataManager(class_name) { - + RefDataManager.superclass.constructor.call(this, class_name); - + } RefDataManager._extend(DataManager); @@ -4736,7 +5157,7 @@ RefDataManager.prototype.__define({ return this.get(); } }, - + /** * Возаращает массив запросов для создания таблиц объекта и его табличных частей * @method get_sql_struct @@ -5531,10 +5952,10 @@ function RegisterManager(class_name){ attr = {}; else if(typeof attr == "string") attr = {ref: attr}; - + if(attr.ref && return_row) return force_promise ? Promise.resolve(this.by_ref[attr.ref]) : this.by_ref[attr.ref]; - + attr.action = "select"; var arr = $p.wsql.alasql(this.get_sql_struct(attr), attr._values), @@ -5552,7 +5973,7 @@ function RegisterManager(class_name){ res.push(this.by_ref[this.get_ref(arr[i])]); } } - + return force_promise ? Promise.resolve(res) : res; }; @@ -6050,83 +6471,295 @@ InfoRegManager.prototype.slice_last = function(filter){ }; + /** - * ### Журнал событий - * Хранит и накапливает события сеанса<br /> - * Является наследником регистра сведений - * @extends InfoRegManager - * @class LogManager - * @static + * ### Абстрактный менеджер регистра накопления + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "AccumRegs"}}{{/crossLink}} + * + * @class AccumRegManager + * @extends RegisterManager + * @constructor + * @param class_name {string} - имя типа менеджера объекта. например, "areg.goods_on_stores" */ -function LogManager(){ +function AccumRegManager(class_name){ + + AccumRegManager.superclass.constructor.call(this, class_name); +} +AccumRegManager._extend(RegisterManager); - LogManager.superclass.constructor.call(this, "ireg.$log"); - var smax; - this.__define({ +/** + * ### Абстрактный менеджер справочника + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Catalogs"}}{{/crossLink}} + * + * @class CatManager + * @extends RefDataManager + * @constructor + * @param class_name {string} + */ +function CatManager(class_name) { + + CatManager.superclass.constructor.call(this, class_name); + + // реквизиты по метаданным + if(this.metadata().hierarchical && this.metadata().group_hierarchy){ /** - * Добавляет запись в журнал - * @param msg {String|Object|Error} - текст + класс события - * @param [msg.obj] {Object} - дополнительный json объект + * ### Признак "это группа" + * @property is_folder + * @for CatObj + * @type {Boolean} */ - record: { - value: function(msg){ + $p[this.obj_constructor()].prototype.__define("is_folder", { + get : function(){ return this._obj.is_folder || false}, + set : function(v){ this._obj.is_folder = $p.utils.fix_boolean(v)}, + enumerable: true, + configurable: true + }); + } - if(msg instanceof Error){ - if(console) - console.log(msg); - msg = { - class: "error", - note: msg.toString() - } - }else if(typeof msg == "object" && !msg.class && !msg.obj){ - msg = { - class: "obj", - obj: msg, - note: msg.note - }; - }else if(typeof msg != "object") - msg = {note: msg}; +} +CatManager._extend(RefDataManager); - msg.date = Date.now() + $p.wsql.time_diff; +/** + * Возвращает объект по наименованию + * @method by_name + * @param name {String|Object} - искомое наименование + * @return {DataObj} + */ +CatManager.prototype.by_name = function(name){ - // уникальность ключа - if(!smax) - smax = alasql.compile("select MAX(`sequence`) as `sequence` from `ireg_$log` where `date` = ?"); - var res = smax([msg.date]); - if(!res.length || res[0].sequence === undefined) - msg.sequence = 0; - else - msg.sequence = parseInt(res[0].sequence) + 1; + var o; - // класс сообщения - if(!msg.class) - msg.class = "note"; + this.find_rows({name: name}, function (obj) { + o = obj; + return false; + }); - $p.wsql.alasql("insert into `ireg_$log` (`ref`, `date`, `sequence`, `class`, `note`, `obj`) values (?,?,?,?,?,?)", - [msg.date + "¶" + msg.sequence, msg.date, msg.sequence, msg.class, msg.note, msg.obj ? JSON.stringify(msg.obj) : ""]); + if(!o) + o = this.get(); - } - }, + return o; +}; - /** - * Сбрасывает события на сервер - * @method backup - * @param [dfrom] {Date} - * @param [dtill] {Date} - */ - backup: { - value: function(dfrom, dtill){ +/** + * Возвращает объект по коду + * @method by_id + * @param id {String|Object} - искомый код + * @return {DataObj} + */ +CatManager.prototype.by_id = function(id){ - } - }, + var o; - /** - * Восстанавливает события из архива на сервере - * @method restore - * @param [dfrom] {Date} + this.find_rows({id: id}, function (obj) { + o = obj; + return false; + }); + + if(!o) + o = this.get(); + + return o; +}; + +/** + * Для иерархических кешируемых справочников возвращает путь элемента + * @param ref {String|CatObj} - ссылка или объект данных + * @return {string} - строка пути элемента + */ +CatManager.prototype.path = function(ref){ + var res = [], tobj; + + if(ref instanceof DataObj) + tobj = ref; + else + tobj = this.get(ref, false, true); + if(tobj) + res.push({ref: tobj.ref, presentation: tobj.presentation}); + + if(tobj && this.metadata().hierarchical){ + while(true){ + tobj = tobj.parent; + if(tobj.empty()) + break; + res.push({ref: tobj.ref, presentation: tobj.presentation}); + } + } + return res; +}; + + + +/** + * ### Абстрактный менеджер плана видов характеристик + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "ChartsOfCharacteristics"}}{{/crossLink}} + * + * @class ChartOfCharacteristicManager + * @extends CatManager + * @constructor + * @param class_name {string} + */ +function ChartOfCharacteristicManager(class_name){ + + ChartOfCharacteristicManager.superclass.constructor.call(this, class_name); + +} +ChartOfCharacteristicManager._extend(CatManager); + + +/** + * ### Абстрактный менеджер плана счетов + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "ChartsOfAccounts"}}{{/crossLink}} + * + * @class ChartOfAccountManager + * @extends CatManager + * @constructor + * @param class_name {string} + */ +function ChartOfAccountManager(class_name){ + + ChartOfAccountManager.superclass.constructor.call(this, class_name); + +} +ChartOfAccountManager._extend(CatManager); + + +/** + * ### Абстрактный менеджер документов + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Documents"}}{{/crossLink}} + * + * @class DocManager + * @extends RefDataManager + * @constructor + * @param class_name {string} + */ +function DocManager(class_name) { + + + DocManager.superclass.constructor.call(this, class_name); + +} +DocManager._extend(RefDataManager); + +/** + * ### Абстрактный менеджер задач + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Tasks"}}{{/crossLink}} + * + * @class TaskManager + * @extends CatManager + * @constructor + * @param class_name {string} + */ +function TaskManager(class_name){ + + TaskManager.superclass.constructor.call(this, class_name); + +} +TaskManager._extend(CatManager); + +/** + * ### Абстрактный менеджер бизнес-процессов + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "BusinessProcesses"}}{{/crossLink}} + * + * @class BusinessProcessManager + * @extends CatManager + * @constructor + * @param class_name {string} + */ +function BusinessProcessManager(class_name){ + + BusinessProcessManager.superclass.constructor.call(this, class_name); + +} +BusinessProcessManager._extend(CatManager); + + +/** + * ### Журнал событий + * Хранит и накапливает события сеанса<br /> + * Является наследником регистра сведений + * @extends InfoRegManager + * @class LogManager + * @static + */ +function LogManager(){ + + LogManager.superclass.constructor.call(this, "ireg.log"); + + var smax; + + this.__define({ + + /** + * Добавляет запись в журнал + * @param msg {String|Object|Error} - текст + класс события + * @param [msg.obj] {Object} - дополнительный json объект + */ + record: { + value: function(msg){ + + if(msg instanceof Error){ + if(console) + console.log(msg); + msg = { + class: "error", + note: msg.toString() + } + }else if(typeof msg == "object" && !msg.class && !msg.obj){ + msg = { + class: "obj", + obj: msg, + note: msg.note + }; + }else if(typeof msg != "object") + msg = {note: msg}; + + msg.date = Date.now() + $p.wsql.time_diff; + + // уникальность ключа + if(!smax) + smax = alasql.compile("select MAX(`sequence`) as `sequence` from `ireg_log` where `date` = ?"); + var res = smax([msg.date]); + if(!res.length || res[0].sequence === undefined) + msg.sequence = 0; + else + msg.sequence = parseInt(res[0].sequence) + 1; + + // класс сообщения + if(!msg.class) + msg.class = "note"; + + $p.wsql.alasql("insert into `ireg_log` (`ref`, `date`, `sequence`, `class`, `note`, `obj`) values (?,?,?,?,?,?)", + [msg.date + "¶" + msg.sequence, msg.date, msg.sequence, msg.class, msg.note, msg.obj ? JSON.stringify(msg.obj) : ""]); + + } + }, + + /** + * Сбрасывает события на сервер + * @method backup + * @param [dfrom] {Date} + * @param [dtill] {Date} + */ + backup: { + value: function(dfrom, dtill){ + + } + }, + + /** + * Восстанавливает события из архива на сервере + * @method restore + * @param [dfrom] {Date} * @param [dtill] {Date} */ restore: { @@ -6165,7 +6798,7 @@ function LogManager(){ return undefined; var parts = ref.split("¶"); - $p.wsql.alasql("select * from `ireg_$log` where date=" + parts[0] + " and sequence=" + parts[1]).forEach(function (row) { + $p.wsql.alasql("select * from `ireg_log` where date=" + parts[0] + " and sequence=" + parts[1]).forEach(function (row) { new RegisterRow(row, this); }.bind(this)); } @@ -6178,7 +6811,7 @@ function LogManager(){ value: function(attr){ if(attr && attr.action == "get_selection"){ - var sql = "select * from `ireg_$log`"; + var sql = "select * from `ireg_log`"; if(attr.date_from){ if (attr.date_till) sql += " where `date` >= ? and `date` <= ?"; @@ -6237,223 +6870,45 @@ function LogManager(){ return xml + "</rows>"; } } + }); } LogManager._extend(InfoRegManager); - -/** - * ### Абстрактный менеджер регистра накопления - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "AccumRegs"}}{{/crossLink}} - * - * @class AccumRegManager - * @extends RegisterManager - * @constructor - * @param class_name {string} - имя типа менеджера объекта. например, "areg.goods_on_stores" - */ -function AccumRegManager(class_name){ - - AccumRegManager.superclass.constructor.call(this, class_name); -} -AccumRegManager._extend(RegisterManager); - - - - -/** - * ### Абстрактный менеджер справочника - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Catalogs"}}{{/crossLink}} - * - * @class CatManager - * @extends RefDataManager - * @constructor - * @param class_name {string} - */ -function CatManager(class_name) { - - CatManager.superclass.constructor.call(this, class_name); - - // реквизиты по метаданным - if(this.metadata().hierarchical && this.metadata().group_hierarchy){ - - /** - * ### Признак "это группа" - * @property is_folder - * @for CatObj - * @type {Boolean} - */ - $p[this.obj_constructor()].prototype.__define("is_folder", { - get : function(){ return this._obj.is_folder || false}, - set : function(v){ this._obj.is_folder = $p.utils.fix_boolean(v)}, - enumerable: true, - configurable: true - }); - } - -} -CatManager._extend(RefDataManager); - -/** - * Возвращает объект по наименованию - * @method by_name - * @param name {String|Object} - искомое наименование - * @return {DataObj} - */ -CatManager.prototype.by_name = function(name){ - - var o; - - this.find_rows({name: name}, function (obj) { - o = obj; - return false; - }); - - if(!o) - o = this.get(); - - return o; -}; - -/** - * Возвращает объект по коду - * @method by_id - * @param id {String|Object} - искомый код - * @return {DataObj} - */ -CatManager.prototype.by_id = function(id){ - - var o; - - this.find_rows({id: id}, function (obj) { - o = obj; - return false; - }); - - if(!o) - o = this.get(); - - return o; -}; - -/** - * Для иерархических кешируемых справочников возвращает путь элемента - * @param ref {String|CatObj} - ссылка или объект данных - * @return {string} - строка пути элемента - */ -CatManager.prototype.path = function(ref){ - var res = [], tobj; - - if(ref instanceof DataObj) - tobj = ref; - else - tobj = this.get(ref, false, true); - if(tobj) - res.push({ref: tobj.ref, presentation: tobj.presentation}); - - if(tobj && this.metadata().hierarchical){ - while(true){ - tobj = tobj.parent; - if(tobj.empty()) - break; - res.push({ref: tobj.ref, presentation: tobj.presentation}); - } - } - return res; -}; - - - /** - * ### Абстрактный менеджер плана видов характеристик - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "ChartsOfCharacteristics"}}{{/crossLink}} - * - * @class ChartOfCharacteristicManager - * @extends CatManager - * @constructor - * @param class_name {string} + * ### Менеджер объектов метаданных + * Используется для формирования списков типов документов, справочников и т.д. + * Например, при работе в интерфейсе с составными типами */ -function ChartOfCharacteristicManager(class_name){ - - ChartOfCharacteristicManager.superclass.constructor.call(this, class_name); +function MetaObjManager() { + MetaObjManager.superclass.constructor.call(this, "cat.meta_objs"); } -ChartOfCharacteristicManager._extend(CatManager); +MetaObjManager._extend(CatManager); /** - * ### Абстрактный менеджер плана счетов - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "ChartsOfAccounts"}}{{/crossLink}} - * - * @class ChartOfAccountManager - * @extends CatManager - * @constructor - * @param class_name {string} + * ### Менеджер доступных полей + * Используется при настройке отчетов и динамических списков */ -function ChartOfAccountManager(class_name){ - - ChartOfAccountManager.superclass.constructor.call(this, class_name); +function MetaFieldManager() { + MetaFieldManager.superclass.constructor.call(this, "cat.meta_fields"); } -ChartOfAccountManager._extend(CatManager); +MetaFieldManager._extend(CatManager); /** - * ### Абстрактный менеджер документов - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Documents"}}{{/crossLink}} - * - * @class DocManager - * @extends RefDataManager - * @constructor - * @param class_name {string} + * ### Менеджер настроек отчетов и динсписков */ -function DocManager(class_name) { - - - DocManager.superclass.constructor.call(this, class_name); +function SchemeSettingsManager() { + SchemeSettingsManager.superclass.constructor.call(this, "cat.scheme_settings"); } -DocManager._extend(RefDataManager); +SchemeSettingsManager._extend(CatManager); -/** - * ### Абстрактный менеджер задач - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Tasks"}}{{/crossLink}} - * - * @class TaskManager - * @extends CatManager - * @constructor - * @param class_name {string} - */ -function TaskManager(class_name){ - - TaskManager.superclass.constructor.call(this, class_name); - -} -TaskManager._extend(CatManager); - -/** - * ### Абстрактный менеджер бизнес-процессов - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "BusinessProcesses"}}{{/crossLink}} - * - * @class BusinessProcessManager - * @extends CatManager - * @constructor - * @param class_name {string} - */ -function BusinessProcessManager(class_name){ - - BusinessProcessManager.superclass.constructor.call(this, class_name); - -} -BusinessProcessManager._extend(CatManager); /** diff --git a/lib/metadata.js b/lib/metadata.js index 001f97551..bf6f81a7b 100644 --- a/lib/metadata.js +++ b/lib/metadata.js @@ -1,5 +1,5 @@ /*! - metadata.js v0.11.223, built:2016-12-02 © Evgeniy Malyarov http://www.oknosoft.ru 2014-2016 + metadata.js v0.12.225, built:2016-12-03 © Evgeniy Malyarov http://www.oknosoft.ru 2014-2016 metadata.js may be freely distributed under the AGPL-3.0. To obtain _Oknosoft Commercial license_, contact info@oknosoft.ru */ (function(root, factory) { @@ -473,7 +473,7 @@ function MetaEngine() { this.__define({ version: { - value: "0.11.223", + value: "0.12.225", writable: false }, @@ -837,8 +837,8 @@ function MetaEngine() { */ record_log: { value: function (err) { - if($p.ireg && $p.ireg.$log) - $p.ireg.$log.record(err); + if($p.ireg && $p.ireg.log) + $p.ireg.log.record(err); console.log(err); } }, @@ -1138,6 +1138,18 @@ function MetaEngine() { value: LogManager }, + MetaObjManager: { + value: MetaObjManager + }, + + MetaFieldManager: { + value: MetaFieldManager + }, + + SchemeSettingsManager: { + value: SchemeSettingsManager + }, + AccumRegManager: { value: AccumRegManager }, @@ -1207,6 +1219,7 @@ function MetaEngine() { } }); + } /** @@ -1550,16 +1563,16 @@ function Ajax() { if(typeof auth == "object" && auth.username && auth.hasOwnProperty("password")){ username = auth.username; password = auth.password; - + }else{ if($p.ajax.username && $p.ajax.authorized){ username = $p.ajax.username; password = $p.aes.Ctr.decrypt($p.ajax.password); - + }else{ username = $p.wsql.get_user_param("user_name"); password = $p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd")); - + if(!username && $p.job_prm && $p.job_prm.guest_name){ username = $p.job_prm.guest_name; password = $p.aes.Ctr.decrypt($p.job_prm.guest_pwd); @@ -2889,7 +2902,7 @@ $p.__define({ get_acl: { value: function(class_name) { var acn = class_name.split("."); - return this._acl && this._acl[acn[0]] ? this._acl[acn[0]][acn[1]] : "e"; + return this._acl && this._acl[acn[0]] && this._acl[acn[0]][acn[1]] ? this._acl[acn[0]][acn[1]] : "e"; } } @@ -3932,11 +3945,419 @@ $p.fias = function FIAS(){}; */ function Meta() { - var _m; + var _m = { + enm: { + accumulation_record_type: [ + { + order: 0, + name: "debit", + synonym: "Приход" + }, + { + order: 1, + name: "credit", + synonym: "Расход" + } + ], + comparison_types: [ + { + order: 0, + name: "gt", + synonym: "Больше" + }, + { + order: 1, + name: "gte", + synonym: "Больше или равно" + }, + { + order: 2, + name: "lt", + synonym: "Меньше" + }, + { + order: 3, + name: "lte", + synonym: "Меньше или равно " + }, + { + order: 4, + name: "eq", + synonym: "Равно" + }, + { + order: 5, + name: "ne", + synonym: "Не равно" + }, + { + "order": 6, + "name": "in", + "synonym": "В списке" + }, + { + order: 7, + name: "nin", + synonym: "Не в списке" + }, + { + order: 8, + name: "lke", + synonym: "Подобно " + }, + { + order: 9, + name: "nlk", + synonym: "Не подобно" + } + ] + }, + cat: { + meta_objs: {}, + meta_fields: {}, + scheme_settings: { + name: "scheme_settings", + splitted: true, + synonym: "Настройки отчетов и списков", + illustration: "", + obj_presentation: "", + list_presentation: "", + input_by_string: [ + "name" + ], + hierarchical: false, + has_owners: false, + group_hierarchy: true, + main_presentation_name: true, + code_length: 0, + fields: { + obj: { + "synonym": "Объект", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 250 + } + }, + user: { + "synonym": "Пользователь", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 50 + } + }, + predefined_name: { + "synonym": "", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 256 + } + } + }, + tabular_sections: { + available_fields: { + "name": "available_fields", + "synonym": "Доступные поля", + "tooltip": "Состав, порядок и ширина колонок", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "Для плоского списка, родитель пустой", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "use": { + "synonym": "Использование", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "boolean" + ] + } + }, + "field": { + "synonym": "Поле", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "width": { + "synonym": "Ширина", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "number" + ], + "digits": 6, + "fraction_figits": 0 + } + }, + "caption": { + "synonym": "Заголовок", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + sort_fields: { + "name": "sort_fields", + "synonym": "Поля сортировки", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "field": { + "synonym": "Поле", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + grouping_fields: { + "name": "grouping_fields", + "synonym": "Поля группировки", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "field": { + "synonym": "Поле", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + selection: { + "name": "selection", + "synonym": "Отбор", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "use": { + "synonym": "Использование", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "boolean" + ] + } + }, + "left_value": { + "synonym": "Левое значение", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "comparison_type": { + "synonym": "Вид сравнения", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "right_value": { + "synonym": "Правое значение", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + scheme: { + "name": "scheme", + "synonym": "Структура", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 10 + } + }, + "kind": { + "synonym": "Вид раздела отчета", + "multiline_mode": false, + "tooltip": "список, таблица, группировка строк, группировка колонок", + "type": { + "types": [ + "string" + ], + "str_len": 10 + } + } + } + } + }, + cachable: "doc" + } + }, + doc: {}, + ireg: { + "log": { + name: "log", + note: "", + synonym: "Журнал событий", + dimensions: { + date: { + synonym: "Дата", + multiline_mode: false, + tooltip: "Время события", + type: { + types: [ + "number" + ], + digits: 15, + fraction_figits: 0 + } + }, + sequence: { + synonym: "Порядок", + multiline_mode: false, + tooltip: "Порядок следования", + type: { + types: [ + "number" + ], + digits: 6, + fraction_figits: 0 + } + } + }, + resources: { + "class": { + synonym: "Класс", + multiline_mode: false, + tooltip: "Класс события", + type: { + types: [ + "string" + ], + str_len: 100 + } + }, + note: { + synonym: "Комментарий", + multiline_mode: true, + tooltip: "Текст события", + type: { + types: [ + "string" + ], + str_len: 0 + } + }, + obj: { + synonym: "Объект", + multiline_mode: true, + tooltip: "Объект, к которому относится событие", + type: { + types: [ + "string" + ], + str_len: 0 + } + } + } + } + }, + areg: {}, + dp: {}, + rep: {}, + cch: {}, + cacc: {} + }; _md = this; - // загружает метаданные из pouchdb function meta_from_pouch(meta_db){ @@ -3946,7 +4367,7 @@ function Meta() { }) .then(function (doc) { - _m = doc; + $p._patch(_m, doc); doc = null; return meta_db.get('meta_patch'); @@ -3983,7 +4404,7 @@ function Meta() { function do_init(){ if(meta_db && !is_local && !is_remote){ - _m = meta_db; + $p._patch(_m, meta_db); meta_db = null; _md.create_managers(); @@ -4014,7 +4435,7 @@ function Meta() { if(!_m) do_init(); - else{ + else if($p.iface && $p.iface.do_reload){ // если изменились метаданные, запланировать перезагрузку setTimeout(function () { @@ -4659,7 +5080,7 @@ function DataManager(class_name){ * ### После чтения объекта с сервера * Имеет смысл для объектов с типом кеширования ("doc", "doc_remote", "meta", "e1cib"). * т.к. структура _DataObj_ может отличаться от прототипа в базе-источнике, в обработчике можно дозаполнить или пересчитать реквизиты прочитанного объекта - * + * * @event after_load * @for DataManager */ @@ -5027,7 +5448,7 @@ DataManager.prototype.sync_grid = function(attr, grid){ if(typeof attr.custom_selection == "function"){ return attr.custom_selection(attr); - + }else if(mgr.cachable == "ram"){ // запрос к alasql @@ -5091,7 +5512,7 @@ DataManager.prototype.sync_grid = function(attr, grid){ }); } - + // TODO: переделать обработку catch() return request() .then(to_grid) @@ -5384,8 +5805,8 @@ DataManager.prototype.print = function(ref, model, wnd){ // если _printing_plates содержит ссылку на обрабочтик печати, используем его if(this._printing_plates[model] instanceof DataObj) - model = this._printing_plates[model]; - + model = this._printing_plates[model]; + // если существует локальный обработчик, используем его if(model instanceof DataObj && model.execute){ @@ -5398,7 +5819,7 @@ DataManager.prototype.print = function(ref, model, wnd){ .then(tune_wnd_print); }else{ - + // иначе - печатаем средствами 1С или иного сервера var rattr = {}; $p.ajax.default_attr(rattr, $p.job_prm.irest_url()); @@ -5458,9 +5879,9 @@ DataManager.prototype.printing_plates = function(){ * @param class_name {string} - имя типа менеджера объекта */ function RefDataManager(class_name) { - + RefDataManager.superclass.constructor.call(this, class_name); - + } RefDataManager._extend(DataManager); @@ -5695,7 +6116,7 @@ RefDataManager.prototype.__define({ return this.get(); } }, - + /** * Возаращает массив запросов для создания таблиц объекта и его табличных частей * @method get_sql_struct @@ -6490,10 +6911,10 @@ function RegisterManager(class_name){ attr = {}; else if(typeof attr == "string") attr = {ref: attr}; - + if(attr.ref && return_row) return force_promise ? Promise.resolve(this.by_ref[attr.ref]) : this.by_ref[attr.ref]; - + attr.action = "select"; var arr = $p.wsql.alasql(this.get_sql_struct(attr), attr._values), @@ -6511,7 +6932,7 @@ function RegisterManager(class_name){ res.push(this.by_ref[this.get_ref(arr[i])]); } } - + return force_promise ? Promise.resolve(res) : res; }; @@ -7009,74 +7430,286 @@ InfoRegManager.prototype.slice_last = function(filter){ }; + /** - * ### Журнал событий - * Хранит и накапливает события сеанса<br /> - * Является наследником регистра сведений - * @extends InfoRegManager - * @class LogManager - * @static + * ### Абстрактный менеджер регистра накопления + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "AccumRegs"}}{{/crossLink}} + * + * @class AccumRegManager + * @extends RegisterManager + * @constructor + * @param class_name {string} - имя типа менеджера объекта. например, "areg.goods_on_stores" */ -function LogManager(){ +function AccumRegManager(class_name){ - LogManager.superclass.constructor.call(this, "ireg.$log"); + AccumRegManager.superclass.constructor.call(this, class_name); +} +AccumRegManager._extend(RegisterManager); - var smax; - this.__define({ + +/** + * ### Абстрактный менеджер справочника + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Catalogs"}}{{/crossLink}} + * + * @class CatManager + * @extends RefDataManager + * @constructor + * @param class_name {string} + */ +function CatManager(class_name) { + + CatManager.superclass.constructor.call(this, class_name); + + // реквизиты по метаданным + if(this.metadata().hierarchical && this.metadata().group_hierarchy){ /** - * Добавляет запись в журнал - * @param msg {String|Object|Error} - текст + класс события - * @param [msg.obj] {Object} - дополнительный json объект + * ### Признак "это группа" + * @property is_folder + * @for CatObj + * @type {Boolean} */ - record: { - value: function(msg){ + $p[this.obj_constructor()].prototype.__define("is_folder", { + get : function(){ return this._obj.is_folder || false}, + set : function(v){ this._obj.is_folder = $p.utils.fix_boolean(v)}, + enumerable: true, + configurable: true + }); + } - if(msg instanceof Error){ - if(console) - console.log(msg); - msg = { - class: "error", - note: msg.toString() - } - }else if(typeof msg == "object" && !msg.class && !msg.obj){ - msg = { - class: "obj", - obj: msg, - note: msg.note - }; - }else if(typeof msg != "object") - msg = {note: msg}; +} +CatManager._extend(RefDataManager); - msg.date = Date.now() + $p.wsql.time_diff; +/** + * Возвращает объект по наименованию + * @method by_name + * @param name {String|Object} - искомое наименование + * @return {DataObj} + */ +CatManager.prototype.by_name = function(name){ - // уникальность ключа - if(!smax) - smax = alasql.compile("select MAX(`sequence`) as `sequence` from `ireg_$log` where `date` = ?"); - var res = smax([msg.date]); - if(!res.length || res[0].sequence === undefined) - msg.sequence = 0; - else - msg.sequence = parseInt(res[0].sequence) + 1; + var o; - // класс сообщения - if(!msg.class) - msg.class = "note"; + this.find_rows({name: name}, function (obj) { + o = obj; + return false; + }); - $p.wsql.alasql("insert into `ireg_$log` (`ref`, `date`, `sequence`, `class`, `note`, `obj`) values (?,?,?,?,?,?)", - [msg.date + "¶" + msg.sequence, msg.date, msg.sequence, msg.class, msg.note, msg.obj ? JSON.stringify(msg.obj) : ""]); + if(!o) + o = this.get(); - } - }, + return o; +}; - /** - * Сбрасывает события на сервер - * @method backup - * @param [dfrom] {Date} - * @param [dtill] {Date} - */ - backup: { +/** + * Возвращает объект по коду + * @method by_id + * @param id {String|Object} - искомый код + * @return {DataObj} + */ +CatManager.prototype.by_id = function(id){ + + var o; + + this.find_rows({id: id}, function (obj) { + o = obj; + return false; + }); + + if(!o) + o = this.get(); + + return o; +}; + +/** + * Для иерархических кешируемых справочников возвращает путь элемента + * @param ref {String|CatObj} - ссылка или объект данных + * @return {string} - строка пути элемента + */ +CatManager.prototype.path = function(ref){ + var res = [], tobj; + + if(ref instanceof DataObj) + tobj = ref; + else + tobj = this.get(ref, false, true); + if(tobj) + res.push({ref: tobj.ref, presentation: tobj.presentation}); + + if(tobj && this.metadata().hierarchical){ + while(true){ + tobj = tobj.parent; + if(tobj.empty()) + break; + res.push({ref: tobj.ref, presentation: tobj.presentation}); + } + } + return res; +}; + + + +/** + * ### Абстрактный менеджер плана видов характеристик + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "ChartsOfCharacteristics"}}{{/crossLink}} + * + * @class ChartOfCharacteristicManager + * @extends CatManager + * @constructor + * @param class_name {string} + */ +function ChartOfCharacteristicManager(class_name){ + + ChartOfCharacteristicManager.superclass.constructor.call(this, class_name); + +} +ChartOfCharacteristicManager._extend(CatManager); + + +/** + * ### Абстрактный менеджер плана счетов + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "ChartsOfAccounts"}}{{/crossLink}} + * + * @class ChartOfAccountManager + * @extends CatManager + * @constructor + * @param class_name {string} + */ +function ChartOfAccountManager(class_name){ + + ChartOfAccountManager.superclass.constructor.call(this, class_name); + +} +ChartOfAccountManager._extend(CatManager); + + +/** + * ### Абстрактный менеджер документов + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Documents"}}{{/crossLink}} + * + * @class DocManager + * @extends RefDataManager + * @constructor + * @param class_name {string} + */ +function DocManager(class_name) { + + + DocManager.superclass.constructor.call(this, class_name); + +} +DocManager._extend(RefDataManager); + +/** + * ### Абстрактный менеджер задач + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Tasks"}}{{/crossLink}} + * + * @class TaskManager + * @extends CatManager + * @constructor + * @param class_name {string} + */ +function TaskManager(class_name){ + + TaskManager.superclass.constructor.call(this, class_name); + +} +TaskManager._extend(CatManager); + +/** + * ### Абстрактный менеджер бизнес-процессов + * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} + * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "BusinessProcesses"}}{{/crossLink}} + * + * @class BusinessProcessManager + * @extends CatManager + * @constructor + * @param class_name {string} + */ +function BusinessProcessManager(class_name){ + + BusinessProcessManager.superclass.constructor.call(this, class_name); + +} +BusinessProcessManager._extend(CatManager); + + +/** + * ### Журнал событий + * Хранит и накапливает события сеанса<br /> + * Является наследником регистра сведений + * @extends InfoRegManager + * @class LogManager + * @static + */ +function LogManager(){ + + LogManager.superclass.constructor.call(this, "ireg.log"); + + var smax; + + this.__define({ + + /** + * Добавляет запись в журнал + * @param msg {String|Object|Error} - текст + класс события + * @param [msg.obj] {Object} - дополнительный json объект + */ + record: { + value: function(msg){ + + if(msg instanceof Error){ + if(console) + console.log(msg); + msg = { + class: "error", + note: msg.toString() + } + }else if(typeof msg == "object" && !msg.class && !msg.obj){ + msg = { + class: "obj", + obj: msg, + note: msg.note + }; + }else if(typeof msg != "object") + msg = {note: msg}; + + msg.date = Date.now() + $p.wsql.time_diff; + + // уникальность ключа + if(!smax) + smax = alasql.compile("select MAX(`sequence`) as `sequence` from `ireg_log` where `date` = ?"); + var res = smax([msg.date]); + if(!res.length || res[0].sequence === undefined) + msg.sequence = 0; + else + msg.sequence = parseInt(res[0].sequence) + 1; + + // класс сообщения + if(!msg.class) + msg.class = "note"; + + $p.wsql.alasql("insert into `ireg_log` (`ref`, `date`, `sequence`, `class`, `note`, `obj`) values (?,?,?,?,?,?)", + [msg.date + "¶" + msg.sequence, msg.date, msg.sequence, msg.class, msg.note, msg.obj ? JSON.stringify(msg.obj) : ""]); + + } + }, + + /** + * Сбрасывает события на сервер + * @method backup + * @param [dfrom] {Date} + * @param [dtill] {Date} + */ + backup: { value: function(dfrom, dtill){ } @@ -7124,7 +7757,7 @@ function LogManager(){ return undefined; var parts = ref.split("¶"); - $p.wsql.alasql("select * from `ireg_$log` where date=" + parts[0] + " and sequence=" + parts[1]).forEach(function (row) { + $p.wsql.alasql("select * from `ireg_log` where date=" + parts[0] + " and sequence=" + parts[1]).forEach(function (row) { new RegisterRow(row, this); }.bind(this)); } @@ -7137,7 +7770,7 @@ function LogManager(){ value: function(attr){ if(attr && attr.action == "get_selection"){ - var sql = "select * from `ireg_$log`"; + var sql = "select * from `ireg_log`"; if(attr.date_from){ if (attr.date_till) sql += " where `date` >= ? and `date` <= ?"; @@ -7196,224 +7829,46 @@ function LogManager(){ return xml + "</rows>"; } } + }); } LogManager._extend(InfoRegManager); - /** - * ### Абстрактный менеджер регистра накопления - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "AccumRegs"}}{{/crossLink}} - * - * @class AccumRegManager - * @extends RegisterManager - * @constructor - * @param class_name {string} - имя типа менеджера объекта. например, "areg.goods_on_stores" + * ### Менеджер объектов метаданных + * Используется для формирования списков типов документов, справочников и т.д. + * Например, при работе в интерфейсе с составными типами */ -function AccumRegManager(class_name){ +function MetaObjManager() { - AccumRegManager.superclass.constructor.call(this, class_name); + MetaObjManager.superclass.constructor.call(this, "cat.meta_objs"); } -AccumRegManager._extend(RegisterManager); - - +MetaObjManager._extend(CatManager); /** - * ### Абстрактный менеджер справочника - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Catalogs"}}{{/crossLink}} - * - * @class CatManager - * @extends RefDataManager - * @constructor - * @param class_name {string} + * ### Менеджер доступных полей + * Используется при настройке отчетов и динамических списков */ -function CatManager(class_name) { - - CatManager.superclass.constructor.call(this, class_name); - - // реквизиты по метаданным - if(this.metadata().hierarchical && this.metadata().group_hierarchy){ - - /** - * ### Признак "это группа" - * @property is_folder - * @for CatObj - * @type {Boolean} - */ - $p[this.obj_constructor()].prototype.__define("is_folder", { - get : function(){ return this._obj.is_folder || false}, - set : function(v){ this._obj.is_folder = $p.utils.fix_boolean(v)}, - enumerable: true, - configurable: true - }); - } +function MetaFieldManager() { + MetaFieldManager.superclass.constructor.call(this, "cat.meta_fields"); } -CatManager._extend(RefDataManager); - -/** - * Возвращает объект по наименованию - * @method by_name - * @param name {String|Object} - искомое наименование - * @return {DataObj} - */ -CatManager.prototype.by_name = function(name){ - - var o; - - this.find_rows({name: name}, function (obj) { - o = obj; - return false; - }); - - if(!o) - o = this.get(); - - return o; -}; - -/** - * Возвращает объект по коду - * @method by_id - * @param id {String|Object} - искомый код - * @return {DataObj} - */ -CatManager.prototype.by_id = function(id){ +MetaFieldManager._extend(CatManager); - var o; - - this.find_rows({id: id}, function (obj) { - o = obj; - return false; - }); - - if(!o) - o = this.get(); - - return o; -}; /** - * Для иерархических кешируемых справочников возвращает путь элемента - * @param ref {String|CatObj} - ссылка или объект данных - * @return {string} - строка пути элемента + * ### Менеджер настроек отчетов и динсписков */ -CatManager.prototype.path = function(ref){ - var res = [], tobj; - - if(ref instanceof DataObj) - tobj = ref; - else - tobj = this.get(ref, false, true); - if(tobj) - res.push({ref: tobj.ref, presentation: tobj.presentation}); - - if(tobj && this.metadata().hierarchical){ - while(true){ - tobj = tobj.parent; - if(tobj.empty()) - break; - res.push({ref: tobj.ref, presentation: tobj.presentation}); - } - } - return res; -}; - - - -/** - * ### Абстрактный менеджер плана видов характеристик - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "ChartsOfCharacteristics"}}{{/crossLink}} - * - * @class ChartOfCharacteristicManager - * @extends CatManager - * @constructor - * @param class_name {string} - */ -function ChartOfCharacteristicManager(class_name){ - - ChartOfCharacteristicManager.superclass.constructor.call(this, class_name); +function SchemeSettingsManager() { + SchemeSettingsManager.superclass.constructor.call(this, "cat.scheme_settings"); } -ChartOfCharacteristicManager._extend(CatManager); +SchemeSettingsManager._extend(CatManager); -/** - * ### Абстрактный менеджер плана счетов - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "ChartsOfAccounts"}}{{/crossLink}} - * - * @class ChartOfAccountManager - * @extends CatManager - * @constructor - * @param class_name {string} - */ -function ChartOfAccountManager(class_name){ - - ChartOfAccountManager.superclass.constructor.call(this, class_name); - -} -ChartOfAccountManager._extend(CatManager); - - -/** - * ### Абстрактный менеджер документов - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Documents"}}{{/crossLink}} - * - * @class DocManager - * @extends RefDataManager - * @constructor - * @param class_name {string} - */ -function DocManager(class_name) { - - - DocManager.superclass.constructor.call(this, class_name); - -} -DocManager._extend(RefDataManager); - -/** - * ### Абстрактный менеджер задач - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "Tasks"}}{{/crossLink}} - * - * @class TaskManager - * @extends CatManager - * @constructor - * @param class_name {string} - */ -function TaskManager(class_name){ - - TaskManager.superclass.constructor.call(this, class_name); - -} -TaskManager._extend(CatManager); - -/** - * ### Абстрактный менеджер бизнес-процессов - * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} - * в соответствии с описанием метаданных конфигурации и помещаются в коллекцию {{#crossLink "BusinessProcesses"}}{{/crossLink}} - * - * @class BusinessProcessManager - * @extends CatManager - * @constructor - * @param class_name {string} - */ -function BusinessProcessManager(class_name){ - - BusinessProcessManager.superclass.constructor.call(this, class_name); - -} -BusinessProcessManager._extend(CatManager); - /** * Конструкторы объектов данных diff --git a/lib/metadata.min.js b/lib/metadata.min.js index 506b4fc3f..42d544ff5 100644 --- a/lib/metadata.min.js +++ b/lib/metadata.min.js @@ -1,15 +1,16 @@ /*! - metadata.js v0.11.223, built:2016-12-02 © Evgeniy Malyarov http://www.oknosoft.ru 2014-2016 + metadata.js v0.12.225, built:2016-12-03 © Evgeniy Malyarov http://www.oknosoft.ru 2014-2016 metadata.js may be freely distributed under the AGPL-3.0. To obtain _Oknosoft Commercial license_, contact info@oknosoft.ru */ -!function(e,t){"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?module.exports=t():e.$p=t()}(this,function(){function MetaEngine(){this.__define({version:{value:"0.11.223",writable:!1},toString:{value:function(){return"Oknosoft data engine. v:"+this.version},writable:!1},utils:{value:new Utils},injected_data:{value:{},writable:!1},ajax:{value:new Ajax,writable:!1},msg:{value:new Messages,writable:!1},wsql:{value:new WSQL,writable:!1},eve:{value:new AppEvents,writable:!1},aes:{value:new Aes("metadata.js"),writable:!1},moment:{get:function(){return this.utils.moment}},_patch:{value:function(e,t){for(var n in t)"object"==typeof t[n]&&e[n]&&"object"==typeof e[n]?$p._patch(e[n],t[n]):e[n]=t[n];return e}},_find:{value:function(e,t,n){var a,i,s;if("object"!=typeof t)for(i in e){a=e[i];for(var o in a)if("function"!=typeof a[o]&&$p.utils.is_equal(a[o],t))return a}else for(i in e){a=e[i],s=!0;for(var o in t)if("function"!=typeof a[o]&&!$p.utils.is_equal(a[o],t[o])){s=!1;break}if(s)return a}}},_selection:{value:function(e,t){var n,a,i,s=!0;if(t)if("function"==typeof t)s=t.call(this,e);else for(n in t)if(a=t[n],i="object"==typeof a,"_"!=n.substr(0,1))if("function"==typeof a){if(s=a.call(this,e,n),!s)break}else if("or"==n&&Array.isArray(a)){if(s=a.some(function(t){var n=Object.keys(t)[0];return t[n].hasOwnProperty("like")?e[n]&&e[n].toLowerCase().indexOf(t[n].like.toLowerCase())!=-1:$p.utils.is_equal(e[n],t[n])}),!s)break}else if(i&&a.hasOwnProperty("like")){if(!e[n]||e[n].toLowerCase().indexOf(a.like.toLowerCase())==-1){s=!1;break}}else if(i&&a.hasOwnProperty("not")){if($p.utils.is_equal(e[n],a.not)){s=!1;break}}else if(i&&a.hasOwnProperty("in")){if(s=a.in.some(function(t){return $p.utils.is_equal(t,e[n])}),!s)break}else if(i&&a.hasOwnProperty("lt")){if(s=e[n]<a.lt,!s)break}else if(i&&a.hasOwnProperty("gt")){if(s=e[n]>a.gt,!s)break}else if(i&&a.hasOwnProperty("between")){var o=e[n];if("number"!=typeof o&&(o=$p.utils.fix_date(e[n])),s=o>=a.between[0]&&o<=a.between[1],!s)break}else if(!$p.utils.is_equal(e[n],a)){s=!1;break}return s}},_find_rows:{value:function(e,t,n){var a,i,s=[],o=0;t&&(t._top?(i=t._top,delete t._top):i=300);for(var r in e)if(a=e[r],$p._selection.call(this,a,t)){if(n){if(n.call(this,a)===!1)break}else s.push(a);if(i&&(o++,o>=i))break}return s}},on:{value:function(e,t){if("object"!=typeof e)return this.eve.attachEvent(e,t);for(var n in e)e[n]._evnts||(e[n]._evnts=[]),e[n]._evnts.push(this.eve.attachEvent(n,e[n]))}},off:{value:function(e){"function"==typeof e&&e._evnts?e._evnts.forEach(function(e){$p.eve.detachEvent(e)}):e?$p.eve.detachEvent(e):$p.eve.detachAllEvents()}},record_log:{value:function(e){$p.ireg&&$p.ireg.$log&&$p.ireg.$log.record(e),console.log(e)}},md:{value:new Meta},enm:{value:new function(){this.toString=function(){return $p.msg.meta_enn_mgr}}},cat:{value:new function(){this.toString=function(){return $p.msg.meta_cat_mgr}}},doc:{value:new function(){this.toString=function(){return $p.msg.meta_doc_mgr}}},ireg:{value:new function(){this.toString=function(){return $p.msg.meta_ireg_mgr}}},areg:{value:new function(){this.toString=function(){return $p.msg.meta_areg_mgr}}},accreg:{value:new function(){this.toString=function(){return $p.msg.meta_accreg_mgr}}},dp:{value:new function(){this.toString=function(){return $p.msg.meta_dp_mgr}}},rep:{value:new function(){this.toString=function(){return $p.msg.meta_reports_mgr}}},cacc:{value:new function(){this.toString=function(){return $p.msg.meta_charts_of_accounts_mgr}}},cch:{value:new function(){this.toString=function(){return $p.msg.meta_charts_of_characteristic_mgr}}},tsk:{value:new function(){this.toString=function(){return $p.msg.meta_task_mgr}}},bp:{value:new function(){this.toString=function(){return $p.msg.meta_bp_mgr}}},DataManager:{value:DataManager},RefDataManager:{value:RefDataManager},DataProcessorsManager:{value:DataProcessorsManager},EnumManager:{value:EnumManager},RegisterManager:{value:RegisterManager},InfoRegManager:{value:InfoRegManager},LogManager:{value:LogManager},AccumRegManager:{value:AccumRegManager},CatManager:{value:CatManager},ChartOfCharacteristicManager:{value:ChartOfCharacteristicManager},ChartOfAccountManager:{value:ChartOfAccountManager},DocManager:{value:DocManager},TaskManager:{value:TaskManager},BusinessProcessManager:{value:BusinessProcessManager},DataObj:{value:DataObj},CatObj:{value:CatObj},DocObj:{value:DocObj},DataProcessorObj:{value:DataProcessorObj},TaskObj:{value:TaskObj},BusinessProcessObj:{value:BusinessProcessObj},EnumObj:{value:EnumObj},RegisterRow:{value:RegisterRow},TabularSection:{value:TabularSection},TabularSectionRow:{value:TabularSectionRow}})}function Utils(){this.moment="function"==typeof moment?moment:require("moment"),this.moment._masks={date:"DD.MM.YY",date_time:"DD.MM.YYYY HH:mm",ldt:"DD MMMM YYYY, HH:mm",iso:"YYYY-MM-DDTHH:mm:ss"},this.fix_date=function(e,t){if(e instanceof Date)return e;var n=this.moment(e,["DD-MM-YYYY","DD-MM-YYYY HH:mm","DD-MM-YYYY HH:mm:ss","DD-MM-YY HH:mm","YYYYDDMMHHmmss",this.moment.ISO_8601]);return n.isValid()?n.toDate():t?this.blank.date:e},this.fix_guid=function(e,t){if(e&&"string"==typeof e);else{if(e instanceof DataObj)return e.ref;if(e&&"object"==typeof e)if(e.presentation){if(e.ref)return e.ref;if(e.name)return e.name}else e="object"==typeof e.ref&&e.ref.hasOwnProperty("ref")?e.ref.ref:e.ref}return this.is_guid(e)||t===!1?e:t?this.generate_guid():this.blank.guid},this.fix_number=function(e,t){var n=parseFloat(e);return isNaN(n)?t?0:e:n},this.fix_boolean=function(e){return"string"==typeof e?!(!e||"false"==e.toLowerCase()):!!e},this.blank={date:this.fix_date("0001-01-01T00:00:00"),guid:"00000000-0000-0000-0000-000000000000",by_type:function(e){var t;return t=e.is_ref?this.guid:e.date_part?this.date:e.digits?0:(!e.types||"boolean"!=e.types[0])&&""}},this.fetch_type=function(e,t){var n=e;return t.is_ref?n=this.fix_guid(e):t.date_part?n=this.fix_date(e,!0):t.digits?n=this.fix_number(e,!0):"boolean"==t.types[0]&&(n=this.fix_boolean(e)),n},this.date_add_day=function(e,t,n){var a=new Date(e);return a.setDate(e.getDate()+t),n&&a.setHours(0,-a.getTimezoneOffset(),0,0),a},this.generate_guid=function(){var e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var n=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?n:7&n|8).toString(16)})},this.is_guid=function(e){return!("string"!=typeof e||e.length<36)&&(e.length>36&&(e=e.substr(0,36)),/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(e))},this.is_empty_guid=function(e){return!e||e===this.blank.guid},this.is_data_obj=function(e){return e&&e instanceof DataObj},this.is_data_mgr=function(e){return e&&e instanceof DataManager},this.is_equal=function(e,t){return e==t||typeof e!=typeof t&&this.fix_guid(e,!1)==this.fix_guid(t,!1)},this.blob_as_text=function(e,t){return new Promise(function(n,a){var i=new FileReader;i.onload=function(e){n(i.result)},i.onerror=function(e){a(e)},"data_url"==t?i.readAsDataURL(e):i.readAsText(e)})}}function Ajax(){function e(e,t,n,a,i){return new Promise(function(s,o){if("undefined"==typeof window&&a&&a.request)a.request({url:encodeURI(t),headers:{Authorization:a.auth}},function(e,t,n){e?o(e):200!=t.statusCode?o({message:t.statusMessage,description:n,status:t.statusCode}):s({response:n})});else{var r=new XMLHttpRequest;if(window.dhx4&&window.dhx4.isIE&&(t=encodeURI(t)),a){var l,c;"object"==typeof a&&a.username&&a.hasOwnProperty("password")?(l=a.username,c=a.password):$p.ajax.username&&$p.ajax.authorized?(l=$p.ajax.username,c=$p.aes.Ctr.decrypt($p.ajax.password)):(l=$p.wsql.get_user_param("user_name"),c=$p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd")),!l&&$p.job_prm&&$p.job_prm.guest_name&&(l=$p.job_prm.guest_name,c=$p.aes.Ctr.decrypt($p.job_prm.guest_pwd))),r.open(e,t,!0,l,c),r.withCredentials=!0,r.setRequestHeader("Authorization","Basic "+btoa(unescape(encodeURIComponent(l+":"+c))))}else r.open(e,t,!0);i&&i.call(this,r),"GET"!=e?this.hide_headers||a.hide_headers||(r.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),r.setRequestHeader("X-Requested-With","XMLHttpRequest")):n=null,r.onload=function(){200==r.status&&(r.response instanceof Blob||"<!DOCTYPE"!==r.response.substr(0,9))?(void 0==r.responseURL&&(r.responseURL=t),s(r)):o(r.response?{message:r.statusText,description:r.response,status:r.status}:Error(r.statusText))},r.onerror=function(){o(Error("Network Error"))},r.send(n)}})}this.username="",this.password="",this.root=!0,this.authorized=!1,this.get=function(t){return e.call(this,"GET",t)},this.post=function(t,n){return 1==arguments.length?n="":2==arguments.length&&"function"==typeof n?(onLoad=n,n=""):n=String(n),e.call(this,"POST",t,n)},this.get_ex=function(t,n,a){return e.call(this,"GET",t,null,n,a)},this.post_ex=function(t,n,a,i){return e.call(this,"POST",t,n,a,i)},this.put_ex=function(t,n,a,i){return e.call(this,"PUT",t,n,a,i)},this.patch_ex=function(t,n,a,i){return e.call(this,"PATCH",t,n,a,i)},this.delete_ex=function(t,n,a){return e.call(this,"DELETE",t,null,n,a)},this.get_and_show_blob=function(e,t,n){function a(t){return e=window.URL.createObjectURL(t.response),i=window.open(e,"wnd_print",s),i.onload=function(t){window.URL.revokeObjectURL(e)},i}var i,s="menubar=no,toolbar=no,location=no,status=no,directories=no,resizable=yes,scrollbars=yes";return!n||"string"==typeof n&&n.toLowerCase().indexOf("post")!=-1?this.post_ex(e,"object"==typeof t?JSON.stringify(t):t,!0,function(e){e.responseType="blob"}).then(a):this.get_ex(e,!0,function(e){e.responseType="blob"}).then(a)},this.get_and_save_blob=function(e,t,n){return this.post_ex(e,"object"==typeof t?JSON.stringify(t):t,!0,function(e){e.responseType="blob"}).then(function(e){saveAs(e.response,n)})},this.default_attr=function(e,t){e.url||(e.url=t),e.username||(e.username=this.username),e.password||(e.password=this.password),e.hide_headers=!0,$p.job_prm["1c"]&&(e.auth=$p.job_prm["1c"].auth,e.request=$p.job_prm["1c"].request)}}function WSQL(){var e,t=this,n={};this.__define({js_time_diff:{value:-new Date("0001-01-01").valueOf()},time_diff:{get:function(){var e=this.get_user_param("time_diff","number");return!e||isNaN(e)||e<621355716e5||e>62135622e6?this.js_time_diff:e}},set_user_param:{value:function(t,a){var i=a;"object"==typeof a?i=JSON.stringify(a):a===!1&&(i=""),e.setItem($p.job_prm.local_storage_prefix+t,i),n[t]=a}},get_user_param:{value:function(t,a){return!n.hasOwnProperty(t)&&e&&(n[t]=this.fetch_type(e.getItem($p.job_prm.local_storage_prefix+t),a)),n[t]}},promise:{value:function(e,n){return new Promise(function(a,i){t.alasql(e,n||[],function(e,t){t?i(t):a(e)})})}},save_options:{value:function(e,n){return t.set_user_param(e+"_"+n.name,n)}},restore_options:{value:function(e,n){var a=t.get_user_param(e+"_"+n.name,"object");for(var i in a)if("object"!=typeof a[i])n[i]=a[i];else{n[i]||(n[i]={});for(var s in a[i])n[i][s]=a[i][s]}return n}},fetch_type:{value:function(e,t){if("object"==t){try{e=JSON.parse(e)}catch(t){e={}}return e}return"number"==t?$p.utils.fix_number(e,!0):"date"==t?$p.utils.fix_date(e,!0):"boolean"==t?$p.utils.fix_boolean(e):e}},alasql:{value:"undefined"!=typeof alasql?alasql:require("alasql")},init_params:{value:function(){if(!$p.job_prm.local_storage_prefix&&!$p.job_prm.create_tables)return Promise.resolve();e="undefined"==typeof localStorage?"undefined"==typeof WorkerGlobalScope?new require("node-localstorage").LocalStorage("./localstorage"):{setItem:function(e,t){},getItem:function(e){}}:localStorage;var n,a=[{p:"user_name",v:"",t:"string"},{p:"user_pwd",v:"",t:"string"},{p:"browser_uid",v:$p.utils.generate_guid(),t:"string"},{p:"zone",v:$p.job_prm.hasOwnProperty("zone")?$p.job_prm.zone:1,t:$p.job_prm.zone_is_string?"string":"number"},{p:"enable_save_pwd",v:$p.job_prm.enable_save_pwd,t:"boolean"},{p:"autologin",v:"",t:"boolean"},{p:"skin",v:"dhx_web",t:"string"},{p:"rest_path",v:"",t:"string"}];$p.job_prm.additional_params&&(a=a.concat($p.job_prm.additional_params)),e.getItem($p.job_prm.local_storage_prefix+"zone")||(n=$p.job_prm.hasOwnProperty("zone")?$p.job_prm.zone:1),$p.job_prm.url_prm.hasOwnProperty("zone")&&(n=$p.job_prm.zone_is_string?$p.job_prm.url_prm.zone:$p.utils.fix_number($p.job_prm.url_prm.zone,!0)),void 0!==n&&t.set_user_param("zone",n),a.forEach(function(e){(void 0==t.get_user_param(e.p,e.t)||!t.get_user_param(e.p,e.t)&&e.p.indexOf("url")!=-1)&&t.set_user_param(e.p,$p.job_prm.hasOwnProperty(e.p)?$p.job_prm[e.p]:e.v)});var i={path:t.get_user_param("couch_path","string")||$p.job_prm.couch_path||"",zone:t.get_user_param("zone","number"),prefix:$p.job_prm.local_storage_prefix,suffix:t.get_user_param("couch_suffix","string")||"",user_node:$p.job_prm.user_node,noreplicate:$p.job_prm.noreplicate};i.path&&(t.__define("pouch",{value:new Pouch}),t.pouch.init(i)),this.create_tables&&(this.alasq(this.create_tables,[]),this.create_tables="")}},drop_tables:{value:function(e){function n(){s--,s<=0?setTimeout(e,10):a()}function a(){var e=o[s-1].tableid;"_"==e.substr(0,1)?n():t.alasql("drop table IF EXISTS "+e,[],n)}function i(e){o=e,(s=e.length)?a():n()}var s=0,o=[];t.alasql("SHOW TABLES",[],i)}}}),this.__define({aladb:{value:new this.alasql.Database("md")}})}function Col_struct(e,t,n,a,i,s){this.id=e,this.width=t,this.type=n,this.align=a,this.sort=i,this.caption=s}function InterfaceObjs(){function e(e,t,n){if(this.layout=e.attachLayout({pattern:"2U",cells:[{id:"a",text:"Разделы",collapsed_text:"Разделы",width:220},{id:"b",text:"Раздел",header:!1}],offsets:{top:0,right:0,bottom:0,left:0}}),this.tree=this.layout.cells("a").attachTreeView(),this.tree.attachEvent("onSelect",function(e,t){if(t){var a=$p.md.mgr_by_class_name(e);a instanceof DataProcessorsManager?a.form_rep(this.layout.cells("b"),n||{hide_header:!0}):a&&a.form_list(this.layout.cells("b"),n||{hide_header:!0})}}.bind(this)),!t){var a=$p.md.get_classes();t=[];for(var i in a)a[i].length&&t.push(i)}1==t.length?$p.md.get_classes()[t[0]].forEach(function(e){var n=t[0]+"."+e,a=$p.md.get(n);a.hide||(this.tree.addItem(n,a.list_presentation||a.synonym),this.tree.setItemIcons(n,{file:"icon_1c_"+t[0]}))}.bind(this)):t.forEach(function(e){this.tree.addItem(e,$p.msg["meta_"+e]),this.tree.setItemIcons(e,{file:"icon_1c_"+e,folder_opened:"icon_1c_"+e,folder_closed:"icon_1c_"+e}),$p.md.get_classes()[e].forEach(function(t){var n=e+"."+t,a=$p.md.get(n);a.hide||(this.tree.addItem(n,a.list_presentation||a.synonym,e),this.tree.setItemIcons(n,{file:"icon_1c_"+e}))}.bind(this))}.bind(this))}function t(e){e.attachHTMLString($p.injected_data["view_settings.html"]),this.cont=e.cell.querySelector(".dhx_cell_cont_tabbar"),this.cont.style.overflow="auto",this.form2=function(e){var t=new dhtmlXForm(e,[{type:"settings",labelWidth:80,position:"label-left"},{type:"label",labelWidth:320,label:"Адрес CouchDB",className:"label_options"},{type:"input",inputWidth:220,name:"couch_path",label:"Путь:",validate:"NotEmpty"},{type:"template",label:"",value:"",note:{text:"Можно указать как относительный, так и абсолютный URL публикации CouchDB",width:320}},{type:"label",labelWidth:320,label:"Адрес http сервиса 1С",className:"label_options"},{type:"input",inputWidth:220,name:"rest_path",label:"Путь",validate:"NotEmpty"},{type:"template",label:"",value:"",note:{text:"Можно указать как относительный, так и абсолютный URL публикации 1С OData",width:320}},{type:"label",labelWidth:320,label:"Значение разделителя данных",className:"label_options"},{type:"input",inputWidth:220,name:"zone",label:"Зона:",numberFormat:["0","",""],validate:"NotEmpty,ValidInteger"},{type:"template",label:"",value:"",note:{text:"Для неразделенной публикации, зона = 0",width:320}},{type:"label",labelWidth:320,label:"Суффикс базы пользователя",className:"label_options"},{type:"input",inputWidth:220,name:"couch_suffix",label:"Суффикс:"},{type:"template",label:"",value:"",note:{text:"Назначается абоненту при регистрации",width:320}},{type:"block",blockOffset:0,name:"block_buttons",list:[{type:"button",name:"save",value:"<i class='fa fa-floppy-o fa-lg'></i>",tooltip:"Применить настройки и перезагрузить программу"},{type:"newcolumn"},{type:"button",offsetLeft:20,name:"reset",value:"<i class='fa fa-refresh fa-lg'></i>",tooltip:"Стереть справочники и перезаполнить данными сервера"}]}]);return t.cont.style.fontSize="100%",["zone","couch_path","couch_suffix","rest_path"].forEach(function(e){"zone"==e?t.setItemValue(e,$p.wsql.get_user_param(e)):t.setItemValue(e,$p.wsql.get_user_param(e)||$p.job_prm[e])}),t.attachEvent("onChange",function(e,t,n){$p.wsql.set_user_param(e,"enable_save_pwd"==e?n||"":t)}),t.disableItem("couch_suffix"),$p.job_prm.rest_path||t.disableItem("rest_path"),t.attachEvent("onButtonClick",function(e){"save"==e?($p.wsql.pouch.log_out(),setTimeout(function(){$p.eve.redirect=!0,location.reload(!0)},1e3)):"reset"==e&&dhtmlx.confirm({title:"Сброс данных",text:"Стереть справочники и перезаполнить данными сервера?",cancel:$p.msg.cancel,callback:function(e){e&&$p.wsql.pouch.reset_local_data()}})}),t}(this.cont.querySelector("[name=form2]").firstChild),this.form1=function(e){var t=new dhtmlXForm(e,[{type:"settings",labelWidth:320,position:"label-left"},{type:"label",label:"Тип устройства",className:"label_options"},{type:"block",blockOffset:0,name:"block_device_type",list:[{type:"settings",labelAlign:"left",position:"label-right"},{type:"radio",name:"device_type",labelWidth:120,label:'<i class="fa fa-desktop"></i> Компьютер',value:"desktop"},{type:"newcolumn"},{type:"radio",name:"device_type",labelWidth:150,label:'<i class="fa fa-mobile fa-lg"></i> Телефон, планшет',value:"phone"}]},{type:"template",label:"",value:"",note:{text:"Класс устройства определяется автоматически, но пользователь может задать его явно",width:320}},{type:"label",label:"Сохранять пароль пользователя",className:"label_options"},{type:"checkbox",name:"enable_save_pwd",label:"Разрешить:",labelWidth:90,checked:$p.wsql.get_user_param("enable_save_pwd","boolean")},{type:"template",label:"",value:"",note:{text:"Не рекомендуется, если к компьютеру имеют доступ посторонние лица",width:320}},{type:"template",label:"",value:"",note:{text:"",width:320}},{type:"label",label:"Подключаемые модули",className:"label_options"},{type:"input",position:"label-top",inputWidth:320,name:"modifiers",label:"Модификаторы:",value:$p.wsql.get_user_param("modifiers"),rows:3,style:"height:80px;"},{type:"template",label:"",value:"",note:{text:"Список дополнительных модулей",width:320}}]);return t.cont.style.fontSize="100%",t.checkItem("device_type",$p.job_prm.device_type),t.attachEvent("onChange",function(e,t,n){$p.wsql.set_user_param(e,"enable_save_pwd"==e?n||"":t)}),t.disableItem("modifiers"),t.getInput("modifiers").onchange=function(){$p.wsql.set_user_param("modifiers",this.value)},t}(this.cont.querySelector("[name=form1]").firstChild)}var n=this;this.clear_svgs=function(e){for("string"==typeof e&&(e=document.getElementById(e));e.firstChild;)e.removeChild(e.firstChild)},this.get_offset=function(e){var t={left:0,top:0};if(e.offsetParent)do t.left+=e.offsetLeft,t.top+=e.offsetTop;while(e=e.offsetParent);return t},this.normalize_xml=function(e){if(!e)return"";var t={"&":"&",'"':""","'":"'","<":"<",">":">"};return e.replace(/[&"'<>]/g,function(e){return t[e]})},this.scale_svg=function(e,t,n){var a,i,s,o,r,l,c,p,d,u={},f="number"==typeof t?t:t.height,m="number"==typeof t?(1.5*t).round(0):t.width,h="number"==typeof t?1/0:t.zoom||1/0;r=e.indexOf(">"),c=e.substring(5,r),s=c.split(" "),o=e.substr(r+1),o=o.substr(0,o.length-6);for(a in s)e=s[a].split("="),"width,height,x,y".indexOf(e[0])!=-1&&(e[1]=Number(e[1].replace(/"/g,"")),u[e[0]]=e[1]);(l=c.indexOf("viewBox="))!=-1?(p=c.substring(l+9),d='viewBox="'+p.substring(0,p.indexOf('"'))+'"'):d='viewBox="'+(u.x||0)+" "+(u.y||0)+" "+(u.width-n)+" "+(u.height-n)+'"';var _=u.height,g=u.width;return i=(f-n)/_,u.height=f,u.width=(g*i).round(0),u.width>m&&(i=(m-n)/g,u.height=(_*i).round(0),u.width=m),i>h&&(i=h,u.height=(_*i).round(0),u.width=(g*i).round(0)),u.x=(u.x*i).round(0),u.y=(u.y*i).round(0),'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="'+u.width+'" height="'+u.height+'" x="'+u.x+'" y="'+u.y+'" xml:space="preserve" '+d+">"+o+"</svg>"},this.bind_help=function(e,t){function n(e){if(!e.help_path)return void $p.msg.show_msg({title:"Справка",type:"alert-info",text:$p.msg.not_implemented})}e instanceof dhtmlXCellObject||(!e.help_path&&t&&(e.help_path=t),e.button("help").show(),e.button("help").enable(),e.attachEvent("onHelp",n))},this.set_hash=function(e,t,a,i){var s={},o=$p.job_prm.parse_url();1==arguments.length&&"object"==typeof e&&(s=e,s.hasOwnProperty("obj")&&(e=s.obj,delete s.obj),s.hasOwnProperty("ref")&&(t=s.ref,delete s.ref),s.hasOwnProperty("frm")&&(a=s.frm,delete s.frm),s.hasOwnProperty("view")&&(i=s.view,delete s.view)),void 0===e&&(e=o.obj||""),void 0===t&&(t=o.ref||""),void 0===a&&(a=o.frm||""),void 0===i&&(i=o.view||"");var r="obj="+e+"&ref="+t+"&frm="+a+"&view="+i;for(var l in s)r+="&"+l+"="+s[l];location.hash.substr(1)==r?n.hash_route():location.hash=r},this.hash_route=function(e){var t,a=$p.job_prm.parse_url(),i=$p.eve.callEvent("hash_route",[a]);if(i===!1||n.before_route&&n.before_route(e)===!1||$p.ajax.authorized&&(a.ref&&"undefined"!=typeof _md?(t=_md.mgr_by_class_name(a.obj),t&&t[a.frm||"form_obj"](n.docs,a.ref)):a.view&&n.swith_view&&n.swith_view(a.view)),e)return n.cancel_bubble(e)},this.cancel_bubble=function(e){var t=e||event;return t&&t.stopPropagation&&t.stopPropagation(),t&&!t.cancelBubble&&(t.cancelBubble=!0),!1},this.Col_struct=Col_struct,this.init_sidebar=function(e,t,a){n.btn_auth_sync=new n.OBtnAuthSync,n.btns_nav=function(e){return n.btn_auth_sync.bind(new n.OTooolBar({wrapper:e,class_name:"md_otbnav",width:"260px",height:"28px",top:"3px",right:"3px",name:"right",buttons:t,onclick:function(e){return n.main.cells(e).setActive(!0),!1}}))},n.main=new dhtmlXSideBar({parent:document.body,icons_path:a||"dist/imgs/",width:180,header:!0,template:"tiles",autohide:!0,items:e,offsets:{top:0,right:0,bottom:0,left:0}}),n.main.attachEvent("onSelect",function(e){var t=$p.job_prm.parse_url();t.view!=e&&n.set_hash(t.obj,t.ref,t.frm,e),n["view_"+e](n.main.cells(e))}),n.main.progressOn();var i=$p.job_prm.parse_url();i.view&&n.main.getAllItems().indexOf(i.view)!=-1?setTimeout(n.hash_route):n.set_hash(i.obj,i.ref,i.frm,"doc")},this.All_meta_objs=e,this.Setting2col=t,this.do_reload=function(){function e(){dhtmlx.confirm({title:$p.msg.file_new_date_title,text:$p.msg.file_new_date,ok:"Перезагрузка",cancel:"Продолжить",callback:function(n){n?($p.wsql.pouch.log_out(),setTimeout(function(){$p.eve.redirect=!0,location.reload(!0)},1e3)):(t++,setTimeout(e,3e4*t))}})}var t=0;e()}}function Pouch(){var e,t,n,a,i=this,s={};i.__define({DB:{value:"undefined"==typeof PouchDB?require("pouchdb-core").plugin(require("pouchdb-adapter-memory")).plugin(require("pouchdb-adapter-http")).plugin(require("pouchdb-replication")).plugin(require("pouchdb-mapreduce")):PouchDB},init:{value:function(e){s._mixin(e),s.path&&0!=s.path.indexOf("http")&&"undefined"!=typeof location&&(s.path=location.protocol+"//"+location.host+s.path)}},local:{get:function(){if(!e){var t={auto_compaction:!0,revs_limit:2};e={ram:new i.DB(s.prefix+s.zone+"_ram",t),doc:new i.DB(s.prefix+s.zone+"_doc",t),meta:new i.DB(s.prefix+"meta",t),sync:{}}}return s.path&&!e._meta&&(e._meta=new i.DB(s.path+"meta",{auth:{username:"guest",password:"meta"},skip_setup:!0}),i.run_sync(e.meta,e._meta,"meta")),e}},remote:{get:function(){return!t&&n&&(t={ram:new i.DB(s.path+s.zone+"_ram",{auth:{username:n.username,password:n.password},skip_setup:!0}),doc:new i.DB(s.path+s.zone+"_doc"+s.suffix,{auth:{username:n.username,password:n.password},skip_setup:!0})}),t}},log_in:{value:function(e,t){return void 0==e&&void 0==t&&(e=$p.job_prm.guest_name,t=$p.aes.Ctr.decrypt($p.job_prm.guest_pwd)),n?n.username==e?Promise.resolve():Promise.reject():$p.ajax.get_ex(s.path+s.zone+"_ram",{username:e,password:t}).then(function(a){return n={username:e,password:t},setTimeout(function(){dhx4.callEvent("log_in",[e])}),{ram:i.run_sync(i.local.ram,i.remote.ram,"ram"),doc:i.run_sync(i.local.doc,i.remote.doc,"doc")}})}},log_out:{value:function(){if(n){if(e.sync.doc)try{e.sync.doc.cancel()}catch(e){}if(e.sync.ram)try{e.sync.ram.cancel()}catch(e){}n=null}t&&t.ram&&delete t.ram,t&&t.doc&&delete t.doc,t=null,dhx4.callEvent("log_out")}},reset_local_data:{value:function(){var e=i.local.ram.destroy.bind(i.local.ram),t=i.local.doc.destroy.bind(i.local.doc),n=function(){setTimeout(function(){$p.eve.redirect=!0,location.reload(!0)},1e3)};i.log_out(),setTimeout(function(){e().then(t).catch(t).then(n).catch(n)},1e3)}},load_data:{value:function(){var e={limit:800,include_docs:!0},t={total_rows:0,limit:e.limit,page:0,start:Date.now()};return new Promise(function(n,s){function o(){i.local.ram.allDocs(e,function(r,l){l?(t.page++,t.total_rows=l.total_rows,t.duration=Date.now()-t.start,$p.eve.callEvent("pouch_load_data_page",[t]),i.load_changes(l,e)?o():(n(),a=!0,$p.eve.callEvent("pouch_load_data_loaded",[t]),t.note="pouch_load_data_loaded",$p.record_log(t))):r&&(s(r),$p.eve.callEvent("pouch_load_data_error",[r]))})}i.local.ram.info().then(function(e){e.doc_count>=($p.job_prm.pouch_ram_doc_count||10)?($p.eve.callEvent("pouch_load_data_start",[t]),o()):($p.eve.callEvent("pouch_load_data_error",[e]),s(e))})})}},authorized:{get:function(){return n&&n.username}},data_loaded:{get:function(){return!!a}},run_sync:{value:function(t,n,s){var o,r;return t.info().then(function(e){return o=e,n.info()}).then(function(e){return"ram"!=s?e:n.get("data_version").then(function(t){return t.version!=$p.wsql.get_user_param("couch_ram_data_version")&&($p.wsql.get_user_param("couch_ram_data_version")&&(e=i.reset_local_data()),$p.wsql.set_user_param("couch_ram_data_version",t.version)),e}).catch(function(e){$p.record_log(e)}).then(function(){return e})}).then(function(l){if(l){"ram"==s&&o.doc_count<($p.job_prm.pouch_ram_doc_count||10)?(r={total_rows:l.doc_count,local_rows:o.doc_count,docs_written:0,limit:200,page:0,start:Date.now()},$p.eve.callEvent("pouch_load_data_start",[r])):"doc"==s&&setTimeout(function(){$p.eve.callEvent("pouch_doc_sync_start")});var c={live:!0,retry:!0,batch_size:300,batches_limit:8};return"meta"==s?c.filter="auth/meta":$p.job_prm.pouch_filter&&$p.job_prm.pouch_filter[s]&&(c.filter=$p.job_prm.pouch_filter[s]),"ram"==s||"meta"==s||$p.wsql.get_user_param("zone")==$p.job_prm.zone_demo?e.sync[s]=t.replicate.from(n,c):e.sync[s]=t.sync(n,c),e.sync[s].on("change",function(e){"ram"==s?(i.load_changes(e),o.doc_count<($p.job_prm.pouch_ram_doc_count||10)&&(r.page++,r.docs_written=e.docs_written,r.duration=Date.now()-r.start,$p.eve.callEvent("pouch_load_data_page",[r]),r.docs_written>=r.total_rows&&(a=!0,$p.eve.callEvent("pouch_load_data_loaded",[r]),r.note="pouch_load_data_loaded",$p.record_log(r)))):(e.update_only=!0,i.load_changes(e)),$p.eve.callEvent("pouch_change",[s,e])}).on("paused",function(e){e&&$p.eve.callEvent("pouch_paused",[s,e])}).on("active",function(e){$p.eve.callEvent("pouch_active",[s,e])}).on("denied",function(e){$p.eve.callEvent("pouch_denied",[s,e])}).on("complete",function(e){$p.eve.callEvent("pouch_complete",[s,e])}).on("error",function(e){$p.eve.callEvent("pouch_error",[s,e])}),e.sync[s]}})}},load_obj:{value:function(e){return e._manager.pouch_db.get(e._manager.class_name+"|"+e.ref).then(function(t){delete t._id,delete t._rev,e._mixin(t)._set_loaded()}).catch(function(e){if(404!=e.status)throw e}).then(function(t){return e})}},save_obj:{value:function(e,t){var n=e._obj._clone(),a=t.db||e._manager.pouch_db;return n._id=e._manager.class_name+"|"+e.ref,delete n.ref,t.attachments&&(n._attachments=t.attachments),(e.is_new()?Promise.resolve():a.get(n._id)).then(function(e){if(e){n._rev=e._rev;for(var t in e._attachments)n._attachments||(n._attachments={}),n._attachments[t]||(n._attachments[t]=e._attachments[t])}}).catch(function(e){if(404!=e.status)throw e}).then(function(){return a.put(n)}).then(function(){if(e.is_new()&&e._set_loaded(e.ref),n._attachments){e._attachments||(e._attachments={});for(var a in n._attachments)e._attachments[a]&&n._attachments[a].stub||(e._attachments[a]=n._attachments[a])}return n=null,t=null,e})}},load_changes:{value:function(e,t){var n,a,i,s,o={};if(t)n=e.rows;else if(e.direction){if("pull"!=e.direction)return;n=e.change.docs}else n=e.docs;if(n.length>0){t&&(t.startkey=n[n.length-1].key,t.skip=1),n.forEach(function(e){if(a=t?e.doc:e,!a)if(e.value&&e.value.deleted)a={_id:e.id,_deleted:!0};else if(e.error)return;s=a._id.split("|"),i=s[0].split("."),a.ref=s[1],delete a._id,delete a._rev,o[i[0]]||(o[i[0]]={}),o[i[0]][i[1]]||(o[i[0]][i[1]]=[]),o[i[0]][i[1]].push(a)});for(var r in o)for(i in o[r])$p[r]&&$p[r][i]&&$p[r][i].load_array(o[r][i],!e.update_only||"update_only");return o=e=n=a=null,!0}return!1}},backup_database:{value:function(e){}},restore_database:{value:function(e){}}})}function Messages(){this.toString=function(){return"Интернационализация сообщений"},"undefined"!=typeof window&&"dhtmlx"in window&&(this.show_msg=function(e,t){if(e){if("string"==typeof e){if($p.iface.synctxt)return void $p.iface.synctxt.show_message(e);e={type:"info",text:e}}t&&"function"==typeof t.setText&&t.setText(e.text),dhtmlx.message(e)}},this.check_soap_result=function(e){return e?"limit_query"==e.error?($p.iface.docs.progressOff(),$p.msg.show_msg({type:"alert-warning",text:$p.msg.limit_query.replace("%1",e.queries).replace("%2",e.queries_avalable),title:$p.msg.srv_overload}),!0):"network"==e.error||"empty"==e.error?($p.iface.docs.progressOff(),$p.msg.show_msg({type:"alert-warning",text:$p.msg.error_network,title:$p.msg.error_critical}),!0):e.error&&e.error_description?($p.iface.docs.progressOff(),e.error_description.indexOf("Недостаточно прав")!=-1&&(e.error_type="alert-warning",e.error_title=$p.msg.error_rights),$p.msg.show_msg({type:e.error_type||"alert-error",text:e.error_description,title:e.error_title||$p.msg.error_critical}),!0):e.error&&!e.messages?($p.iface.docs.progressOff(),$p.msg.show_msg({type:"alert-error",title:$p.msg.error_critical,text:$p.msg.unknown_error.replace("%1","unknown_error")}),!0):void 0:($p.msg.show_msg({type:"alert-error",text:$p.msg.empty_response,title:$p.msg.error_critical}),!0)},this.show_not_implemented=function(){$p.msg.show_msg({type:"alert-warning",text:$p.msg.not_implemented,title:$p.msg.main_title})})}function Meta(){function e(e){return e.info().then(function(){return e.get("meta")}).then(function(n){return t=n,n=null,e.get("meta_patch")}).then(function(e){return $p._patch(t,e),e=null,delete t._id,delete t._rev,t})}var t;_md=this,_md.create_managers=function(){},_md.init=function(n){function a(){return!n||i||s?e(n||$p.wsql.pouch.local.meta).then(function(){return i?void _md.create_managers():t}).catch($p.record_log):(t=n,n=null,_md.create_managers(),void 0)}var i=!n||$p.wsql.pouch&&n==$p.wsql.pouch.local.meta,s=n&&$p.wsql.pouch&&n==$p.wsql.pouch.local._meta;return $p.on("pouch_change",function(e,n){"meta"==e&&(t?setTimeout(function(){$p.iface.do_reload()},3e3):a())}),a()},_md.get=function(e,n){var a=e.split(".");if(!n)return t[a[0]][a[1]];var i={multiline_mode:!1,note:"",synonym:"",tooltip:"",type:{is_ref:!1,types:["string"]}},s="doc,tsk,bp".indexOf(a[0])!=-1,o="cat,cch,cacc,tsk".indexOf(a[0])!=-1;return s&&"number_doc"==n?(i.synonym="Номер",i.tooltip="Номер документа",i.type.str_len=11):s&&"date"==n?(i.synonym="Дата",i.tooltip="Дата документа",i.type.date_part="date_time",i.type.types[0]="date"):s&&"posted"==n?(i.synonym="Проведен",i.type.types[0]="boolean"):o&&"id"==n?i.synonym="Код":o&&"name"==n?i.synonym="Наименование":"_deleted"==n?(i.synonym="Пометка удаления",i.type.types[0]="boolean"):"is_folder"==n?(i.synonym="Это группа",i.type.types[0]="boolean"):"ref"==n?(i.synonym="Ссылка",i.type.is_ref=!0,i.type.types[0]=e):i=n?t[a[0]][a[1]].fields[n]:t[a[0]][a[1]],i},_md.get_classes=function(){ -var e={};for(var n in t){e[n]=[];for(var a in t[n])e[n].push(a)}return e},_md.sql_type=function(e,t,n,a){var i;return i="type"==t&&"cch_properties"==e.table_name||"svg"==t&&"cat_production_params"==e.table_name?" JSON":n.is_ref||n.types.indexOf("guid")!=-1?a?n.types.every(function(e){return 0==e.indexOf("enm.")})?" character varying(100)":n.hasOwnProperty("str_len")?" character varying("+Math.max(36,n.str_len)+")":" uuid":" CHAR":n.hasOwnProperty("str_len")?a?n.str_len?" character varying("+n.str_len+")":" text":" CHAR":n.date_part?a&&"date"!=n.date_part?"date_time"==n.date_part?" timestamp with time zone":" time without time zone":" Date":n.hasOwnProperty("digits")?0==n.fraction_figits?a?n.digits<7?" integer":" bigint":" INT":a?" numeric("+n.digits+","+n.fraction_figits+")":" FLOAT":n.types.indexOf("boolean")!=-1?" BOOLEAN":n.types.indexOf("json")!=-1?" JSON":a?" character varying(255)":" CHAR"},_md.sql_composite=function(e,t,n,a){var i="";return e[t].type.types.length>1&&"type"!=t&&(n=n?n.substr(0,29)+"_T":t.substr(0,29)+"_T",i=a?', "'+n+'" character varying(255)':_md.sql_mask(n)+" CHAR"),i},_md.sql_mask=function(e,t){return", "+(t?"_t_.":"")+("`"+e+"`")},_md.mgr_by_class_name=function(e){if(e){var t=e.split(".");if(t[1]&&$p[t[0]])return $p[t[0]][t[1]]}},_md.value_mgr=function(e,t,n,a,i){function s(e){return e&&1==n.types.length&&(n._mgr=e),e}var o,r,l,c,p;if(n._mgr)return n._mgr;if(1==n.types.length){if(l=n.types[0].split("."),l.length>1&&$p[l[0]])return s($p[l[0]][l[1]])}else if(i&&i.type&&(l=i.type.split("."),l.length>1&&$p[l[0]]))return s($p[l[0]][l[1]]);if(o=e.property||e.param,"value"==t&&o){if($p.utils.is_data_obj(o))r=o;else{if(!$p.utils.is_guid(o))return;r=$p.cch.properties.get(o,!1)}if($p.utils.is_data_obj(r)){if(r.is_new())return $p.cat.property_values;if(c=[],r.type.types.forEach(function(e){l=e.split("."),l.length>1&&$p[l[0]][l[1]]&&c.push($p[l[0]][l[1]])}),1==c.length||e[t]==$p.utils.blank.guid)return s(c[0]);if(a)return c;if((o=e[t])instanceof DataObj)return o._manager;if($p.utils.is_guid(o)&&o!=$p.utils.blank.guid)for(var d in c)if(p=c[d],p.get(o,!1,!0))return p}}else{if(c=[],n.types.forEach(function(e){l=e.split("."),l.length>1&&$p[l[0]][l[1]]&&c.push($p[l[0]][l[1]])}),1==c.length||e[t]==$p.utils.blank.guid)return s(c[0]);if(a)return c;if((o=e[t])instanceof DataObj)return o._manager;if($p.utils.is_guid(o)&&o!=$p.utils.blank.guid)for(var d in c)if(p=c[d],p.get(o,!1,!0))return p}},_md.control_by_type=function(e,t){var n;return n="boolean"==typeof t&&e.types.indexOf("boolean")!=-1?"ch":"number"==typeof t&&e.digits?e.fraction_figits<5?"calck":"edn":t instanceof Date&&e.date_part?"dhxCalendar":e.is_ref?"ocombo":e.date_part?"dhxCalendar":e.digits?e.fraction_figits<5?"calck":"edn":"boolean"==e.types[0]?"ch":e.hasOwnProperty("str_len")&&(e.str_len>=100||0==e.str_len)?"txt":"ed"},_md.ts_captions=function(e,t,n){n||(n={});var a,i=_md.get(e).tabular_sections[t],s=_md.get(e).form,o=i.fields;if(s&&s.obj){if(!s.obj.tabular_sections[t])return;n._mixin(s.obj.tabular_sections[t])}else{"contact_information"===t&&(o={type:"",kind:"",presentation:""}),n.fields=["row"],n.headers="№",n.widths="40",n.min_widths="",n.aligns="",n.sortings="na",n.types="cntr";for(var r in o)a=i.fields[r],a.hide||(n.fields.push(r),n.headers+=","+(a.synonym?a.synonym.replace(/,/g," "):r),n.types+=","+_md.control_by_type(a.type),n.sortings+=",na")}return!0},_md.syns_js=function(e){var n={DeletionMark:"_deleted",Description:"name",DataVersion:"data_version",IsFolder:"is_folder",Number:"number_doc",Date:"date","Дата":"date",Posted:"posted",Code:"id",Parent_Key:"parent",Owner_Key:"owner",Owner:"owner",Ref_Key:"ref","Ссылка":"ref",LineNumber:"row"};return n[e]?n[e]:t.syns_js[t.syns_1с.indexOf(e)]||e},_md.syns_1с=function(e){var n={_deleted:"DeletionMark",name:"Description",is_folder:"IsFolder",number_doc:"Number",date:"Date",posted:"Posted",id:"Code",ref:"Ref_Key",parent:"Parent_Key",owner:"Owner_Key",row:"LineNumber"};return n[e]?n[e]:t.syns_1с[t.syns_js.indexOf(e)]||e},_md.printing_plates=function(e){if(e)for(var n in e.doc)t.doc[n].printing_plates=e.doc[n]},_md.class_name_from_1c=function(e){var t=e.split(".");return 1==t.length?"enm."+e:("Перечисление"==t[0]?e="enm.":"Справочник"==t[0]?e="cat.":"Документ"==t[0]?e="doc.":"РегистрСведений"==t[0]?e="ireg.":"РегистрНакопления"==t[0]?e="areg.":"РегистрБухгалтерии"==t[0]?e="accreg.":"ПланВидовХарактеристик"==t[0]?e="cch.":"ПланСчетов"==t[0]?e="cacc.":"Обработка"==t[0]?e="dp.":"Отчет"==t[0]&&(e="rep."),e+_md.syns_js(t[1]))},_md.class_name_to_1c=function(e){var t=e.split(".");return 1==t.length?"Перечисление."+e:("enm"==t[0]?e="Перечисление.":"cat"==t[0]?e="Справочник.":"doc"==t[0]?e="Документ.":"ireg"==t[0]?e="РегистрСведений.":"areg"==t[0]?e="РегистрНакопления.":"accreg"==t[0]?e="РегистрБухгалтерии.":"cch"==t[0]?e="ПланВидовХарактеристик.":"cacc"==t[0]?e="ПланСчетов.":"dp"==t[0]?e="Обработка.":"rep"==t[0]&&(e="Отчет."),e+_md.syns_1с(t[1]))},_md.create_tables=function(e,t){function n(){s--,0==s?e?e(l):alasql.utils.saveFile("create_tables.sql",l):a()}function a(){var e=o[s-1];l+=e.class[e.name].get_sql_struct(t)+"; ",n()}var i,s=0,o=[],r=_md.get_classes(),l=t&&t.postgres?"":"USE md; ";"enm,cch,cacc,cat,bp,tsk,doc,ireg,areg".split(",").forEach(function(e){for(i in r[e])o.push({class:$p[e],name:r[e][i]})}),s=o.length,a()}}function DataManager(e){var t=_md.get(e),n={after_create:[],after_load:[],before_save:[],after_save:[],value_change:[],add_row:[],del_row:[]};this.__define({cachable:{get:function(){return e.indexOf("enm.")!=-1?"ram":t.cachable?t.cachable:e.indexOf("doc.")!=-1||e.indexOf("dp.")!=-1||e.indexOf("rep.")!=-1?"doc":"ram"}},class_name:{value:e,writable:!1},alatable:{get:function(){return $p.wsql.aladb.tables[this.table_name]?$p.wsql.aladb.tables[this.table_name].data:[]}},metadata:{value:function(e){return e?t.fields[e]||t.tabular_sections[e]:t}},on:{value:function(e,t){if("object"==typeof e)for(var a in e)e.hasOwnProperty(a)&&n[a].push(e[a]);else n[e].push(t)}},off:{value:function(e,t){}},handle_event:{value:function(e,t,a){var i,s=[];return n[t].forEach(function(t){s!==!1&&(i=t.call(e,a),i===!1?s=i:i&&s.push(i))}),s===!1?s:s.length?1==s.length?s[0]:s.some(function(e){return"object"==typeof e&&e.then})?Promise.all(s):s:void 0}},by_ref:{value:{}}})}function RefDataManager(e){RefDataManager.superclass.constructor.call(this,e)}function DataProcessorsManager(e){DataProcessorsManager.superclass.constructor.call(this,e)}function EnumManager(e){EnumManager.superclass.constructor.call(this,e);var t=$p.md.get(e);for(var n in t)new EnumObj(t[n],this)}function RegisterManager(e){RegisterManager.superclass.constructor.call(this,e),this.push=function(e,t){t&&t!=e.ref?(delete this.by_ref[e.ref],this.by_ref[t]=e):this.by_ref[e.ref]=e},this.get=function(e,t,n){if(e?"string"==typeof e&&(e={ref:e}):e={},e.ref&&n)return t?Promise.resolve(this.by_ref[e.ref]):this.by_ref[e.ref];e.action="select";var a,i=$p.wsql.alasql(this.get_sql_struct(e),e._values);if(delete e.action,delete e._values,i.length)if(n)a=this.by_ref[this.get_ref(i[0])];else{a=[];for(var s in i)a.push(this.by_ref[this.get_ref(i[s])])}return t?Promise.resolve(a):a},this.unload_obj=function(e){delete this.by_ref[e],this.alatable.some(function(t,n,a){if(t.ref==e)return a.splice(n,1),!0})},this.load_array=function(e,t){for(var n,a,i=[],s=0;s<e.length;s++){if(n=this.get_ref(e[s]),a=this.by_ref[n],a||e[s]._deleted){if(a&&e[s]._deleted){a.unload();continue}(a.is_new()||t)&&(a._mixin(e[s]),a._set_loaded())}else a=new($p[this.obj_constructor()])(e[s],this),t&&a._set_loaded();i.push(a)}return i}}function InfoRegManager(e){InfoRegManager.superclass.constructor.call(this,e)}function LogManager(){LogManager.superclass.constructor.call(this,"ireg.$log");var e;this.__define({record:{value:function(t){t instanceof Error?(console&&console.log(t),t={class:"error",note:t.toString()}):"object"!=typeof t||t.class||t.obj?"object"!=typeof t&&(t={note:t}):t={class:"obj",obj:t,note:t.note},t.date=Date.now()+$p.wsql.time_diff,e||(e=alasql.compile("select MAX(`sequence`) as `sequence` from `ireg_$log` where `date` = ?"));var n=e([t.date]);n.length&&void 0!==n[0].sequence?t.sequence=parseInt(n[0].sequence)+1:t.sequence=0,t.class||(t.class="note"),$p.wsql.alasql("insert into `ireg_$log` (`ref`, `date`, `sequence`, `class`, `note`, `obj`) values (?,?,?,?,?,?)",[t.date+"¶"+t.sequence,t.date,t.sequence,t.class,t.note,t.obj?JSON.stringify(t.obj):""])}},backup:{value:function(e,t){}},restore:{value:function(e,t){}},clear:{value:function(e,t){}},show:{value:function(e){}},get:{value:function(e,t,n){if("object"==typeof e&&(e=e.ref||""),!this.by_ref[e]){if(t===!1)return;var a=e.split("¶");$p.wsql.alasql("select * from `ireg_$log` where date="+a[0]+" and sequence="+a[1]).forEach(function(e){new RegisterRow(e,this)}.bind(this))}return t?Promise.resolve(this.by_ref[e]):this.by_ref[e]}},get_sql_struct:{value:function(e){if(e&&"get_selection"==e.action){var t="select * from `ireg_$log`";return e.date_from?t+=e.date_till?" where `date` >= ? and `date` <= ?":" where `date` >= ?":e.date_till&&(t+=" where `date` <= ?"),t}return LogManager.superclass.get_sql_struct.call(this,e)}},caption_flds:{value:function(e){var t='<column id="%1" width="%2" type="%3" align="%4" sort="%5">%6</column>',n=[],a="";if(n.push(new Col_struct("date","200","ro","left","server","Дата")),n.push(new Col_struct("class","100","ro","left","server","Класс")),n.push(new Col_struct("note","*","ro","left","server","Событие")),e.get_header){a="<head>";for(var i in n)a+=t.replace("%1",n[i].id).replace("%2",n[i].width).replace("%3",n[i].type).replace("%4",n[i].align).replace("%5",n[i].sort).replace("%6",n[i].caption);a+="</head>"}return{head:a,acols:n}}},data_to_grid:{value:function(e,t){var n="<?xml version='1.0' encoding='UTF-8'?><rows total_count='%1' pos='%2' set_parent='%3'>".replace("%1",e.length).replace("%2",t.start).replace("%3",t.set_parent||""),a=this.caption_flds(t);return n+=a.head,e.forEach(function(e){n+='<row id="'+e.ref+'"><cell>'+$p.moment(e.date-$p.wsql.time_diff).format("DD.MM.YYYY HH:mm:ss")+"."+e.sequence+"</cell><cell>"+(e.class||"")+"</cell><cell>"+(e.note||"")+"</cell></row>"}),n+"</rows>"}}})}function AccumRegManager(e){AccumRegManager.superclass.constructor.call(this,e)}function CatManager(e){CatManager.superclass.constructor.call(this,e),this.metadata().hierarchical&&this.metadata().group_hierarchy&&$p[this.obj_constructor()].prototype.__define("is_folder",{get:function(){return this._obj.is_folder||!1},set:function(e){this._obj.is_folder=$p.utils.fix_boolean(e)},enumerable:!0,configurable:!0})}function ChartOfCharacteristicManager(e){ChartOfCharacteristicManager.superclass.constructor.call(this,e)}function ChartOfAccountManager(e){ChartOfAccountManager.superclass.constructor.call(this,e)}function DocManager(e){DocManager.superclass.constructor.call(this,e)}function TaskManager(e){TaskManager.superclass.constructor.call(this,e)}function BusinessProcessManager(e){BusinessProcessManager.superclass.constructor.call(this,e)}function DataObj(e,t){var n,a={},i={},s={_is_new:!(this instanceof EnumObj)};return t instanceof DataProcessorsManager||t instanceof EnumManager||(n=t.get(e,!1,!0)),n?(e=null,n):(t instanceof EnumManager?i.ref=e.name:t instanceof RegisterManager?i.ref=t.get_ref(e):i.ref=$p.utils.fix_guid(e),this.__define({_obj:{value:i,configurable:!0},_ts_:{value:function(e){return a[e]||(a[e]=new TabularSection(e,this)),a[e]},configurable:!0},_manager:{value:t},_data:{value:s,configurable:!0}}),t.alatable&&t.push&&(t.alatable.push(i),t.push(this,i.ref)),void(e=null))}function CatObj(e,t){var n="";CatObj.superclass.constructor.call(this,e,t),this.__define("presentation",{get:function(){return this.name||this.id?this.name||this.id||this._metadata.obj_presentation||this._metadata.synonym:n},set:function(e){e&&(n=String(e))}}),e&&"object"==typeof e&&(e._not_set_loaded?(delete e._not_set_loaded,this._mixin(e)):(this._mixin(e),$p.utils.is_empty_guid(this.ref)||!e.id&&!e.name||this._set_loaded(this.ref))),e=null}function DocObj(e,t){var n="";DocObj.superclass.constructor.call(this,e,t),this.__define("presentation",{get:function(){return this.number_doc?(this._metadata.obj_presentation||this._metadata.synonym)+" №"+this.number_doc+" от "+$p.moment(this.date).format($p.moment._masks.ldt):n},set:function(e){e&&(n=String(e))}}),e&&"object"==typeof e&&this._mixin(e),!$p.utils.is_empty_guid(this.ref)&&e.number_doc&&this._set_loaded(this.ref),e=null}function doc_props_date_number(e){e.__define({number_doc:{get:function(){return this._obj.number_doc||""},set:function(e){this.__notify("number_doc"),this._obj.number_doc=e},enumerable:!0},date:{get:function(){return this._obj.date||$p.utils.blank.date},set:function(e){this.__notify("date"),this._obj.date=$p.utils.fix_date(e,!0)},enumerable:!0}})}function DataProcessorObj(e,t){DataProcessorObj.superclass.constructor.call(this,e,t);var n,a=t.metadata();for(n in a.fields)e[n]=$p.utils.fetch_type("",a.fields[n].type);for(n in a.tabular_sections)e[n]=[];this._mixin(e)}function TaskObj(e,t){TaskObj.superclass.constructor.call(this,e,t)}function BusinessProcessObj(e,t){BusinessProcessObj.superclass.constructor.call(this,e,t)}function EnumObj(e,t){EnumObj.superclass.constructor.call(this,e,t),e&&"object"==typeof e&&this._mixin(e)}function RegisterRow(e,t){RegisterRow.superclass.constructor.call(this,e,t),e&&"object"==typeof e&&this._mixin(e);for(var n in t.metadata().dimensions)if(!e.hasOwnProperty(n)&&e.ref){var a=e.ref.split("¶");Object.keys(t.metadata().dimensions).forEach(function(e,t){this[e]=a[t]}.bind(this));break}}function TabularSection(e,t){t._obj[e]||(t._obj[e]=[]),this.__define("_name",{value:e,enumerable:!1}),this.__define("_owner",{value:t,enumerable:!1}),this.__define("_obj",{value:t._obj[e],writable:!1,enumerable:!1})}function TabularSectionRow(e){var t={};this.__define("_owner",{value:e,enumerable:!1}),this.__define("_obj",{value:t,writable:!1,enumerable:!1})}function Rest(){this.filter_date=function(e,t,n){t||(t=new Date("2015-01-01"));var a=e+" gt datetime'"+$p.moment(t).format($p.moment._masks.iso)+"'";return n&&(a+=" and "+e+" lt datetime'"+$p.moment(n).format($p.moment._masks.iso)+"'"),a},this.to_data=function(e,t){var n,a,i,s,o,r,l={},c=t.metadata(),p=c.fields,d=c.tabular_sections;t instanceof RefDataManager?(e.hasOwnProperty("DeletionMark")&&(l._deleted=e.DeletionMark),e.hasOwnProperty("DataVersion"),e.hasOwnProperty("Ref_Key")&&(l.ref=e.Ref_Key)):p={}._mixin(c.dimensions)._mixin(c.resources)._mixin(c.attributes),t instanceof DocManager?(e.hasOwnProperty("Number")?l.number_doc=e.Number||e.number_doc:e.hasOwnProperty("number_doc")&&(l.number_doc=e.number_doc),e.hasOwnProperty("Date")?l.date=e.Date:e.hasOwnProperty("date")&&(l.date=e.date),e.hasOwnProperty("Posted")?l.posted=e.Posted:e.hasOwnProperty("posted")&&(l.posted=e.posted)):(c.main_presentation_name&&(e.hasOwnProperty("Description")?l.name=e.Description:e.hasOwnProperty("name")&&(l.name=e.name)),c.code_length&&(e.hasOwnProperty("Code")?l.id=e.Code:e.hasOwnProperty("id")&&(l.id=e.id)));for(a in p)if(e.hasOwnProperty(a))l[a]=e[a];else{if(o=_md.syns_1с(a),o.indexOf("_Key")==-1&&p[a].type.is_ref&&e[o+"_Key"]&&(o+="_Key"),!e.hasOwnProperty(o))continue;l[a]=e[o]}for(n in d)r="extra_fields"==n||e.hasOwnProperty(n)?n:_md.syns_1с(n),e.hasOwnProperty(r)&&(l[n]=[],e[r]&&(e[r].sort(function(e,t){return(e.LineNumber||e.row)>(t.LineNumber||t.row)}),e[r].forEach(function(e){s={};for(i in d[n].fields)o=e.hasOwnProperty(i)||"extra_fields"==n&&("property"==i||"value"==i)?i:_md.syns_1с(i),o.indexOf("_Key")==-1&&d[n].fields[i].type.is_ref&&e[o+"_Key"]&&(o+="_Key"),s[i]=e[o];l[n].push(s)})));return l},this.ajax_to_data=function(e,t){return $p.ajax.get_ex(e.url,e).then(function(e){return JSON.parse(e.response)}).then(function(e){var n=[];return e.value.forEach(function(e){n.push(_rest.to_data(e,t))}),n})},this.build_select=function(e,t){function n(e,a){"function"==typeof a?s+=a(t,e):(o=_md.syns_1с(e),r=_md.get(t.class_name,e),r&&(r=r.type,r.is_ref&&o.indexOf("_Key")==-1&&r.types.length&&r.types[0].indexOf("enm.")==-1&&(o+="_Key"),r.types.length&&(["boolean","number"].indexOf(typeof a)!=-1?s+=o+" eq "+a:r.is_ref&&"object"!=typeof a||a instanceof DataObj?s+=o+" eq guid'"+a+"'":"string"==typeof a?s+=o+" eq '"+a+"'":"object"==typeof a&&(a.hasOwnProperty("like")?s+=o+" like '%"+a.like+"%'":a.hasOwnProperty("not")?s+=" not ("+n(e,a.not)+") ":a.hasOwnProperty("in")&&(s+=o+" in ("+(r.is_ref?a.in.map(function(e){return"guid'"+e+"'"}).join(","):a.in.join(","))+") ")))))}function a(e){for(var t in e)if(s?s+=" and ":s="&$filter=","or"==t&&Array.isArray(e[t])){var a=!0;e[t].forEach(function(e){a?(s+=" ( ",a=!1):s+=" or ";var t=Object.keys(e)[0];n(t,e[t])}),s+=" ) "}else n(t,e[t])}var i,s,o,r,l="";e||(e={}),e.fields&&(e.fields.forEach(function(e){"ref"==e?o="Ref_Key":(o=_md.syns_1с(e),r=_md.get(t.class_name,e).type,r.is_ref&&o.indexOf("_Key")==-1&&r.types.length&&r.types[0].indexOf("enm.")==-1&&(o+="_Key")),i?i+=",":i="&$select=",i+=o}),l+=i),e.selection&&("function"==typeof e.selection||(Array.isArray(e.selection)?e.selection.forEach(a):a(e.selection)),s&&(l+=s)),$p.job_prm.rest&&t.rest_name.indexOf("Module_")==-1&&t.rest_name.indexOf("DataProcessor_")==-1&&t.rest_name.indexOf("Report_")==-1&&l.indexOf(" like ")==-1&&l.indexOf(" in ")==-1&&!t.metadata().irest?$p.ajax.default_attr(e,$p.job_prm.rest_url()):$p.ajax.default_attr(e,$p.job_prm.irest_url()),e.url+=t.rest_name+"?allowedOnly=true&$format=json&$top="+(e.top||300)+l},this.load_array=function(e,t){return _rest.build_select(e,t),_rest.ajax_to_data(e,t)},this.load_obj=function(e){var t={};return $p.ajax.default_attr(t,!e._metadata.irest&&$p.job_prm.rest?$p.job_prm.rest_url():$p.job_prm.irest_url()),t.url+=e._manager.rest_name+"(guid'"+e.ref+"')?$format=json",$p.ajax.get_ex(t.url,t).then(function(e){return JSON.parse(e.response)}).then(function(t){return e._mixin(_rest.to_data(t,e._manager))._set_loaded(),e}).catch(function(t){return 404==t.status?e:void $p.record_log(t)})},this.save_irest=function(e,t){var n=JSON.stringify(e),a=(void 0!=t.post?",post="+t.post:"")+(void 0!=t.operational?",operational="+t.operational:"");return $p.ajax.default_attr(t,$p.job_prm.irest_url()),t.url+=e._manager.rest_name+"(guid'"+e.ref+"'"+a+")",$p.ajax.post_ex(t.url,n,t).then(function(e){return JSON.parse(e.response)}).then(function(t){return e._mixin(t)})},this.save_rest=function(e,t){var n,a=e.to_atom();return $p.ajax.default_attr(t,$p.job_prm.rest_url()),n=t.url+e._manager.rest_name,t.url=n+"(guid'"+e.ref+"')?$format=json&$select=Ref_Key,DeletionMark",$p.ajax.get_ex(t.url,t).catch(function(e){return 404==e.status?{response:JSON.stringify({is_new:!0})}:Promise.reject(e)}).then(function(e){return JSON.parse(e.response)}).then(function(i){return i.is_new?$p.ajax.post_ex(n,a,t):$p.ajax.patch_ex(n+"(guid'"+e.ref+"')",a,t)}).then(function(t){var n=xmlToJSON.parseString(t.response,{mergeCDATA:!1,grokAttr:!0,grokText:!1,normalize:!0,xmlns:!1,namespaceKey:"_ns",textKey:"_text",valueKey:"_value",attrKey:"_attr",cdataKey:"_cdata",attrsAsObject:!1,stripAttrPrefix:!0,stripElemPrefix:!0,childrenAsArray:!1});if(n.entry&&n.entry.content&&n.entry.updated){var a,i=n.entry.content.properties,s={};for(var o in i)if(0!=o.indexOf("_"))if(a=i[o].element)if(s[o]=[],Array.isArray(a))for(var r in a){s[o][r]={};for(var l in a[r])0!=l.indexOf("_")&&(s[o][r][l]="false"!==a[r][l]._text&&a[r][l]._text)}else{s[o][0]={};for(var l in a)0!=l.indexOf("_")&&(s[o][0][l]="false"!==a[l]._text&&a[l]._text)}else s[o]="false"!==i[o]._text&&i[o]._text;return _rest.to_data(s,e._manager)}}).then(function(t){return e._mixin(t)})}}function eXcell_ocombo(e){if(e){var t=this;t.cell=e,t.grid=e.parentNode.grid,t.setValue=function(e){t.setCValue(e instanceof DataObj?e.presentation:e||"")},t.getValue=function(){return t.grid.get_cell_value()},t.shiftNext=function(){t.grid.editStop()},t.edit=function(){t.combo||(t.val=t.getValue(),t.cell.innerHTML="",t.combo=new OCombo({parent:t.cell}._mixin(t.grid.get_cell_field())),t.combo.getInput().focus())},t.detach=function(){if(t.combo){if(t.combo.getComboText){t.setValue(t.combo.getComboText()),t.combo.getSelectedValue()||t.combo.callEvent("onChange");var e=!$p.utils.is_equal(t.val,t.getValue());return t.combo.unload(),e}t.combo.unload&&t.combo.unload()}return!0}}}function eXcell_pwd(e){var t;e&&(this.cell=e,this.grid=e.parentNode.grid,eXcell_ed.call(this),t=this.edit,this.edit=function(){t.call(this),this.obj.type="password"},this.setValue=function(){this.setCValue("*********")},this.getValue=function(){return this.grid.get_cell_value()},this.detach=function(){if(this.grid.get_cell_field){var e=this.grid.get_cell_field();e.obj[e.field]=this.obj.value}return this.setValue(),t=null,this.val!=this.getValue()})}function ODropdownList(e){function t(t){s.innerHTML=e.values[s.getAttribute("current")],e.event_name&&!t&&dhx4.callEvent(e.event_name,[s.getAttribute("current")])}function n(){i.classList.remove("open")}var a,i,s,o=document.createElement("ul");e.container.innerHTML='<div class="dropdown_list">'+e.title+'<a href="#" class="dropdown_list"></a></div>',i=e.container.firstChild,s=i.querySelector("a"),s.setAttribute("current",Array.isArray(e.values)?"0":Object.keys(e.values)[0]),i.onclick=function(e){if(i.classList.contains("open")){if("LI"==e.target.tagName)for(var a in o.childNodes)if(o.childNodes[a]==e.target){s.setAttribute("current",e.target.getAttribute("current")),t();break}n()}else i.classList.add("open");return $p.iface.cancel_bubble(e)},i.appendChild(o),o.className="dropdown_menu",e.class_name&&(i.classList.add(e.class_name),o.classList.add(e.class_name));for(var r in e.values){a=document.createElement("li");var l=e.values[r].indexOf("<i");a.innerHTML=e.values[r].substr(l)+" "+e.values[r].substr(0,l),a.setAttribute("current",r),o.appendChild(a)}document.body.addEventListener("keydown",function(e){27==e.keyCode&&i.classList.remove("open")}),document.body.addEventListener("click",n),this.unload=function(){for(var t;t=i.lastChild;)i.removeChild(t);e.container.removeChild(i),a=o=i=s=e=null},t(!0)}function OCombo(e){function t(e){var t={_top:30};return f&&f.metadata().hierarchical&&f.metadata().group_hierarchy&&("elm"==u.choice_groups_elm?t.is_folder=!1:"grp"!=u.choice_groups_elm&&"parent"!=d||(t.is_folder=!0)),u.choice_links&&u.choice_links.forEach(function(e){e.name&&"selection"==e.name[0]&&(p instanceof TabularSectionRow?e.path.length<2?t[e.name[1]]="function"==typeof e.path[0]?e.path[0]:p._owner._owner[e.path[0]]:t[e.name[1]]=p[e.path[1]]:t[e.name[1]]="function"==typeof e.path[0]?e.path[0]:p[e.path[0]])}),u.choice_params&&u.choice_params.forEach(function(e){var n=Array.isArray(e.path)?{in:e.path}:e.path;t[e.name]?Array.isArray(t[e.name])?t[e.name].push(n):(t[e.name]=[t[e.name]],t[e.name].push(n)):t[e.name]=n}),u._option_list_local&&(t._local=!0),e&&(t.presentation={like:e}),t}function n(a){if("select"==this.name)f?f.form_selection(g,{initial_value:p[d].ref,selection:[t()]}):n.call({name:"type"});else if("add"==this.name)f&&f.create({},!0).then(function(t){t._set_loaded(t.ref),t.form_obj(e.pwnd)});else if("open"==this.name)p&&p[d]&&!p[d].empty()&&p[d].form_obj(e.pwnd);else if("type"==this.name){var i,s,o=[],r=p,l=d;u.type.types.forEach(function(e){i=_md.mgr_by_class_name(e),s=i.metadata(),o.push({presentation:s.synonym||s.name,mgr:i,selected:f===i})}),$p.iface.select_from_list(o).then(function(e){r[l]&&(r[l].empty&&r[l].empty()||r[l]._manager!=e.mgr)&&(f=e.mgr,p=r,d=l,u=p._metadata.fields[d],f.form_selection({on_select:function(e){p[d]=e,p=null,d=null,u=null}},{selection:[t()]})),f=null,i=null,s=null,r=null,l=null})}if(a)return $p.iface.cancel_bubble(a)}function a(){h=!1,setTimeout(function(){h||($p.iface.popup.p&&$p.iface.popup.p.onmouseover&&($p.iface.popup.p.onmouseover=null),$p.iface.popup.p&&$p.iface.popup.p.onmouseout&&($p.iface.popup.p.onmouseout=null),$p.iface.popup.clear(),$p.iface.popup.hide())},300)}function i(){if(!(f instanceof EnumManager)){h=!0;var t=document.createElement("div"),i=e.hide_frm?"":"<a href='#' name='select' title='Форма выбора {F4}'>Показать все</a><a href='#' name='open' style='margin-left: 9px;' title='Открыть форму элемента {Ctrl+Shift+F4}'><i class='fa fa-external-link fa-fw'></i></a>";if(!e.hide_frm){var s=$p.current_acl.get_acl(f.class_name);s.indexOf("i")!=-1&&(i+=" <a href='#' name='add' title='Создать новый элемент {F8}'><i class='fa fa-plus fa-fwfa-fw'></i></a>")}if(u.type.types.length>1&&(i+=" <a href='#' name='type' title='Выбрать тип значения {Alt+T}'><i class='fa fa-level-up fa-fw'></i></a>"),i){t.innerHTML=i;for(var o=0;o<t.children.length;o++)t.children[o].onclick=n;$p.iface.popup.clear(),$p.iface.popup.attachObject(t),$p.iface.popup.show(dhx4.absLeft(_.getButton())-77,dhx4.absTop(_.getButton()),_.getButton().offsetWidth,_.getButton().offsetHeight),$p.iface.popup.p.onmouseover=function(){h=!0},$p.iface.popup.p.onmouseout=a}}}function s(e){return setTimeout(i,10),e.preventDefault(),!1}function o(n){if(!(f instanceof EnumManager))return 115==n.keyCode?(n.ctrlKey&&n.shiftKey?p[d].empty()||p[d].form_obj(e.pwnd):n.ctrlKey||n.shiftKey||f&&f.form_selection(g,{initial_value:p[d].ref,selection:[t()]}),$p.iface.cancel_bubble(n)):void 0}function r(e){setTimeout(function(){_&&_.getInput&&_.getInput().select()},50)}function l(e){_&&_.getBase&&(_.getBase().parentElement?p instanceof TabularSectionRow||e.forEach(function(e){e.name==d&&c(p[d])}):setTimeout(_.unload))}function c(e){if(e&&e instanceof DataObj&&!e.empty()){if(_.getOption(e.ref)||_.addOption(e.ref,e.presentation),_.getSelectedValue()==e.ref)return;_.setComboValue(e.ref)}else _.getSelectedValue()||(_.setComboValue(""),_.setComboText(""))}var p,d,u,f,m,h,_=this,g={on_select:e.on_select||function(e){p[d]=e}};e.pwnd&&e.pwnd.setModal&&(g.setModal=e.pwnd.setModal.bind(e.pwnd)),OCombo.superclass.constructor.call(_,e),e.on_select?(_.getBase().style.border="none",_.getInput().style.left="-3px",e.is_tabular||(_.getButton().style.right="9px")):_.getBase().style.marginBottom="4px",e.left&&(_.getBase().style.left=left+"px"),this.attachEvent("onChange",function(){p&&d&&(p[d]=this.getSelectedValue())}),this.attachEvent("onBlur",function(){!this.getSelectedValue()&&this.getComboText()&&this.setComboText("")}),this.attachEvent("onDynXLS",function(n){f||(f=_md.value_mgr(p,d,u.type)),f&&(_.clearAll(),(e.get_option_list||f.get_option_list).call(f,null,t(n)).then(function(e){_.addOption&&(_.addOption(e),_.openSelect())}))}),_.getButton().addEventListener("mouseover",i),_.getButton().addEventListener("mouseout",a),_.getBase().addEventListener("click",$p.iface.cancel_bubble),_.getBase().addEventListener("contextmenu",s),_.getInput().addEventListener("keyup",o),_.getInput().addEventListener("focus",r),this.attach=function(e){p&&(p instanceof TabularSectionRow?Object.unobserve(p._owner._owner,l):Object.unobserve(p,l)),p=e.obj,d=e.field,m=e.property,e.metadata?u=e.metadata:m?(u=p._metadata.fields[d]._clone(),u.type=m.type):u=p._metadata.fields[d],_.clearAll(),f=_md.value_mgr(p,d,u.type),(f||e.get_option_list)&&(e.get_option_list||f.get_option_list).call(f,p[d],t()).then(function(e){_.addOption&&(_.addOption(e),c(p[d]))}),p instanceof TabularSectionRow?Object.observe(p._owner._owner,l,["row"]):Object.observe(p,l,["update"])};var b=this.unload;this.unload=function(){a(),_.getButton().removeEventListener("mouseover",i),_.getButton().removeEventListener("mouseout",a),_.getBase().removeEventListener("click",$p.iface.cancel_bubble),_.getBase().removeEventListener("contextmenu",s),_.getInput().removeEventListener("keyup",o),_.getInput().removeEventListener("focus",r),p&&(p instanceof TabularSectionRow?Object.unobserve(p._owner._owner,l):Object.unobserve(p,l)),_.conf&&_.conf.tm_confirm_blur&&clearTimeout(_.conf.tm_confirm_blur),p=null,d=null,u=null,f=null,g=null;try{b.call(_)}catch(e){}},e.obj&&e.field&&this.attach(e),this.enableFilteringMode("between","dummy",!1,!1),this.__define({value:{get:function(){if(p)return p[d]}}})}function ODateRangePicker(e,t){var n=this._cont=document.createElement("div");e instanceof dhtmlXCellObject?e.appendObject(this._cont):e.appendChild(this._cont),this._cont.className="odaterangepicker",this._cont.innerHTML='<i class="fa fa-calendar"></i>  <span></span>  <i class="fa fa-caret-down"></i>',this.__define({set_text:{value:function(){$("span",n).html(this.date_from.format("DD MMM YY")+" - "+this.date_till.format("DD MMM YY"))}},on:{value:function(e,t){return $(n).on(e,t)}},date_from:{get:function(){return $(n).data("daterangepicker").startDate},set:function(e){$(n).data("daterangepicker").setStartDate(e),this.set_text()}},date_till:{get:function(){return $(n).data("daterangepicker").endDate},set:function(e){$(n).data("daterangepicker").setEndDate(e),this.set_text()}}}),$(n).daterangepicker({startDate:t.date_from?moment(t.date_from):moment().subtract(29,"days"),endDate:moment(t.date_till),showDropdowns:!0,alwaysShowCalendars:!0,opens:"left",ranges:{"Сегодня":[moment(),moment()],"Вчера":[moment().subtract(1,"days"),moment().subtract(1,"days")],"Последние 7 дней":[moment().subtract(6,"days"),moment()],"Последние 30 дней":[moment().subtract(29,"days"),moment()],"Этот месяц":[moment().startOf("month"),moment().endOf("month")],"Прошлый месяц":[moment().subtract(1,"month").startOf("month"),moment().subtract(1,"month").endOf("month")]}},this.set_text.bind(this)),this.set_text()}function _clear_all(){$p.iface.docs.__define({clear_all:{value:function(){this.detachToolbar(),this.detachStatusBar(),this.detachObject(!0)},enumerable:!1},"Очистить":{get:function(){return this.clear_all},enumerable:!1},"Контейнер":{get:function(){return this.cell.querySelector(".dhx_cell_cont_layout")},enumerable:!1}})}function OTooolBar(e){function t(e){for(var t=0;t<c.children.length;t++)c.children[t].classList.remove("selected");e&&!this.classList.contains("selected")&&this.classList.add("selected")}function n(){s=!1,setTimeout(function(){s||$p.iface.popup.hide()},300)}function a(){e.onclick&&e.onclick.call(l,this.name.replace(e.name+"_",""),e.name)}var i,s,o,r,l=this,c=document.createElement("div");e.image_path||(e.image_path=dhtmlx.image_path),e.hasOwnProperty("class_name")?c.className=e.class_name:c.className="md_otooolbar",l.cell=c,l.buttons={},this.add=function(t){function p(e){if(e||(e=d),e.subdiv&&!o&&!r){for(;e.subdiv.firstChild;)e.subdiv.removeChild(e.subdiv.firstChild);e.subdiv.parentNode.removeChild(e.subdiv),e.subdiv=null}}var d=$p.iface.add_button(c,e,t);d.onclick=a,d.onmouseover=function(){t.title&&!t.sub&&(s=!0,$p.iface.popup.clear(),$p.iface.popup.attachHTML(t.title),$p.iface.popup.show(dhx4.absLeft(d),dhx4.absTop(d),d.offsetWidth,d.offsetHeight),$p.iface.popup.p.onmouseover=function(){s=!0},$p.iface.popup.p.onmouseout=n,e.on_popup&&e.on_popup($p.iface.popup,d))},d.onmouseout=n,l.buttons[t.name]=d,t.sub&&(d.onmouseover=function(){for(var n=0;n<d.parentNode.children.length;n++)if(d.parentNode.children[n]!=d&&d.parentNode.children[n].subdiv){p(d.parentNode.children[n]);break}if(r=!0,!this.subdiv){this.subdiv=document.createElement("div"),this.subdiv.className="md_otooolbar",i=$p.iface.get_offset(d),"right"==t.sub.align?this.subdiv.style.left=i.left+d.offsetWidth-(parseInt(t.sub.width.replace(/\D+/g,""))||56)+"px":this.subdiv.style.left=i.left+"px",this.subdiv.style.top=i.top+c.offsetHeight+"px",this.subdiv.style.height=t.sub.height||"198px",this.subdiv.style.width=t.sub.width||"56px";for(var n in t.sub.buttons){var s=$p.iface.add_button(this.subdiv,e,t.sub.buttons[n]);s.onclick=a}e.wrapper.appendChild(this.subdiv),this.subdiv.onmouseover=function(){o=!0},this.subdiv.onmouseout=function(){o=!1,setTimeout(p,500)},t.title&&$p.iface.popup.show(dhx4.absLeft(this.subdiv),dhx4.absTop(this.subdiv),this.subdiv.offsetWidth,this.subdiv.offsetHeight)}},d.onmouseout=function(){r=!1,setTimeout(p,500)})},this.select=function(n){for(var a=0;a<c.children.length;a++){var i=c.children[a];if(i.name==e.name+"_"+n)return void t.call(i,!0); -}},this.get_selected=function(){for(var e=0;e<c.children.length;e++){var t=c.children[e];if(t.classList.contains("selected"))return t.name}},this.unload=function(){for(;c.firstChild;)c.removeChild(c.firstChild);e.wrapper.removeChild(c)},e.wrapper.appendChild(c),c.style.width=e.width||"28px",c.style.height=e.height||"150px",c.style.position="absolute",e.top&&(c.style.top=e.top),e.left&&(c.style.left=e.left),e.bottom&&(c.style.bottom=e.bottom),e.right&&(c.style.right=e.right),e.paddingRight&&(c.style.paddingRight=e.paddingRight),e.paddingLeft&&(c.style.paddingLeft=e.paddingLeft),e.buttons&&e.buttons.forEach(function(e){l.add(e)})}function eXcell_addr(e){if(e){var t,n=this,a=function(e){return eXcell_proto.input_keydown(e,n)},i=function(e){var t={grid:n.grid}._mixin(n.grid.get_cell_field());return wnd_address(t),$p.iface.cancel_bubble(e)};n.cell=e,n.grid=n.cell.parentNode.grid,n.open_selection=i,n.setValue=function(e){n.setCValue(e)},n.getValue=function(){return n.grid.get_cell_value()},n.edit=function(){var e;n.val=n.getValue(),n.cell.innerHTML='<div class="ref_div21"><input type="text" class="dhx_combo_edit" style="height: 20px;"><div class="ref_field21"> </div></div>',t=n.cell.firstChild,e=t.childNodes[0],e.value=n.val,e.onclick=$p.iface.cancel_bubble,e.readOnly=!0,e.focus(),e.onkeydown=a,t.childNodes[1].onclick=i},n.detach=function(){return n.setValue(n.getValue()),!$p.utils.is_equal(n.val,n.getValue())}}}function wnd_address(e){function t(){var e={name:"wnd_addr",wnd:{id:"wnd_addr",top:130,left:200,width:800,height:560,modal:!0,center:!0,pwnd:g,allow_close:!0,allow_minmax:!0,on_close:m,caption:_.shipping_address}};g&&g.getHeight&&e.wnd.height>g.getHeight()&&(e.wnd.height=g.getHeight()),h=$p.iface.dat_blank(null,e.wnd),h.elmnts.layout=h.attachLayout("2E"),h.elmnts.cell_frm=h.elmnts.layout.cells("a"),h.elmnts.cell_frm.setHeight("110"),h.elmnts.cell_frm.hideHeader(),h.elmnts.cell_frm.fixSize(0,1),h.elmnts.pgrid=h.elmnts.cell_frm.attachPropertyGrid(),h.elmnts.pgrid.setDateFormat("%d.%m.%Y %H:%i"),h.elmnts.pgrid.init(),h.elmnts.pgrid.parse(_._manager.get_property_grid_xml({" ":[{id:"delivery_area",path:"o.delivery_area",synonym:"Район доставки",type:"ref",txt:v.delivery_area.presentation},{id:"region",path:"o.region",synonym:"Регион",type:"ro",txt:v.region},{id:"city",path:"o.city",synonym:"Населенный пункт",type:"ed",txt:v.city},{id:"street",path:"o.street",synonym:"Улица, дом, корпус, литера, квартира",type:"ed",txt:v.street}]},v),function(){h.elmnts.pgrid.enableAutoHeight(!0),h.elmnts.pgrid.setInitWidthsP("40,60"),h.elmnts.pgrid.setSizes(),h.elmnts.pgrid.attachEvent("onPropertyChanged",f)},"xml"),h.elmnts.pgrid.get_cell_field=function(){return{obj:v,field:"delivery_area",on_select:a,pwnd:h,metadata:{synonym:"Район",tooltip:"Район (зона, направление) доставки для группировки при планировании и оптимизации маршрута геокодером",choice_groups_elm:"elm",type:{types:["cat.delivery_areas"],is_ref:!0}}}},h.elmnts.toolbar=h.attachToolbar({icons_path:dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()}),h.elmnts.toolbar.loadStruct('<toolbar><item id="btn_select" type="button" title="Установить адрес" text="<b>Выбрать</b>" /></toolbar>',function(){this.attachEvent("onclick",n)}),h.elmnts.cell_map=h.elmnts.layout.cells("b"),h.elmnts.cell_map.hideHeader();var t={center:new google.maps.LatLng(v.latitude,v.longitude),zoom:v.street?15:12,mapTypeId:google.maps.MapTypeId.ROADMAP};h.elmnts.map=h.elmnts.cell_map.attachMap(t),v.marker=new google.maps.Marker({map:h.elmnts.map,draggable:!0,animation:google.maps.Animation.DROP,position:t.center}),google.maps.event.addListener(v.marker,"click",d),google.maps.event.addListener(v.marker,"dragend",u),s()}function n(e){"btn_select"==e&&(_.delivery_area=v.delivery_area,l(),_.coordinates=JSON.stringify([v.latitude,v.longitude])),h.close()}function a(e){if(void 0!==e){var t,n=b;b=$p.utils.is_data_obj(e)?e:$p.cat.delivery_areas.get(e,!1),t=n!=b,$p.utils.is_data_obj(b)||(b=$p.cat.delivery_areas.get()),h.elmnts.pgrid.cells().setValue(e.presentation),i(t)}}function i(e){if(!v.delivery_area.empty()&&e&&(v.street=""),v.delivery_area.region?(v.region=v.delivery_area.region,h.elmnts.pgrid.cells("region",1).setValue(v.region)):e&&(v.region=""),v.delivery_area.city?(v.city=v.delivery_area.city,h.elmnts.pgrid.cells("city",1).setValue(v.city)):e&&(v.city=""),v.delivery_area.latitude&&v.delivery_area.longitude){var t=new google.maps.LatLng(v.delivery_area.latitude,v.delivery_area.longitude);h.elmnts.map.setCenter(t),v.marker.setPosition(t)}s()}function s(){h.elmnts.pgrid.cells("region",1).setValue(v.region),h.elmnts.pgrid.cells("city",1).setValue(v.city),h.elmnts.pgrid.cells("street",1).setValue(v.street)}function o(){var e=v.street?15:12;h.elmnts.map.getZoom()!=e&&h.elmnts.map.setZoom(e),p(function(e,t){if(t==google.maps.GeocoderStatus.OK){var n=e[0].geometry.location;h.elmnts.map.setCenter(n),v.marker.setPosition(n),v.latitude=n.lat(),v.longitude=n.lng(),v.postal_code=$p.ipinfo.components({},e[0].address_components).postal_code||""}})}function r(){return(v.street?v.street.replace(/,/g," ")+", ":"")+(v.city?v.city+", ":"")+(v.region?v.region+", ":"")+v.country+(v.postal_code?", "+v.postal_code:"")}function l(){_.shipping_address=r();var e='<КонтактнаяИнформация \t\t\t\txmlns="http://www.v8.1c.ru/ssl/contactinfo" \t\t\t\txmlns:xs="http://www.w3.org/2001/XMLSchema" \t\t\t\txmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" \t\t\t\tПредставление="%1"> \t\t\t\t\t<Комментарий/> \t\t\t\t\t<Состав xsi:type="Адрес" Страна="РОССИЯ"> \t\t\t\t\t\t<Состав xsi:type="АдресРФ">'.replace("%1",_.shipping_address);if(v.region&&(e+="\n<СубъектРФ>"+v.region+"</СубъектРФ>"),v.city&&(e+=v.city.indexOf("г.")!=-1||v.city.indexOf("г ")!=-1||v.city.indexOf(" г")!=-1?"\n<Город>"+v.city+"</Город>":"\n<НаселПункт>"+v.city+"</НаселПункт>"),v.street){var t,n,a,i,s,o=v.street.replace(/,/g," ");for(var l in $p.fias){if(1==$p.fias[l].type)for(var c in $p.fias[l].syn)if((n=o.indexOf($p.fias[l].syn[c]))!=-1){i=l,t=o.substr(n+$p.fias[l].syn[c].length).trim(),o=o.substr(0,n).trim();break}if(i)break}if(i||(i="1010",(n=o.indexOf(" "))!=-1&&(t=o.substr(n),o=o.substr(0,n))),e+="\n<Улица>"+o.trim()+"</Улица>",t){a=t.toLowerCase(),t="";for(var l in $p.fias){if(3==$p.fias[l].type)for(var c in $p.fias[l].syn)if((n=a.indexOf($p.fias[l].syn[c]))!=-1){s=l,t=a.substr(n+$p.fias[l].syn[c].length),a=a.substr(0,n);break}if(s)break}s||(s="2010",(n=a.indexOf(" "))!=-1&&(t=a.substr(n),a=a.substr(0,n))),e+='\n<ДопАдрЭл><Номер Тип="'+i+'" Значение="'+a.trim()+'"/></ДопАдрЭл>'}t&&(e+='\n<ДопАдрЭл><Номер Тип="'+s+'" Значение="'+t.trim()+'"/></ДопАдрЭл>')}v.postal_code&&(e+='<ДопАдрЭл ТипАдрЭл="10100000" Значение="'+v.postal_code+'"/>'),e+="</Состав> \t\t\t\t\t</Состав></КонтактнаяИнформация>",_.address_fields=e}function c(){function e(e){if(e.attributes&&2==e.attributes.length){var t={};return t[e.attributes[0].value]=e.attributes[1].value,t}}if(_.address_fields){v.xml=(new DOMParser).parseFromString(_.address_fields,"text/xml");var t,n={},a={building_room:""},i=[],s="СубъектРФ,Округ,СвРайМО,СвРайМО,ВнутригРайон,НаселПункт,Улица,Город,ДопАдрЭл,Адрес_по_документу,Местоположение".split(",");for(var o in s)n[s[o]]=v.xml.getElementsByTagName(s[o]);for(var o in n)for(var r in n[o])if("length"!=r&&n[o].hasOwnProperty(r))if(t=e(n[o][r]))a[o]||(a[o]=[]),a[o].push(t);else if(n[o][r].childNodes.length)for(var l in n[o][r].childNodes)"length"!=l&&n[o][r].childNodes.hasOwnProperty(l)&&((t=e(n[o][r].childNodes[l]))?(a[o]||(a[o]=[]),a[o].push(t)):n[o][r].childNodes[l].nodeValue&&(a[o]?a[o]+=" "+n[o][r].childNodes[l].nodeValue:a[o]=n[o][r].childNodes[l].nodeValue));for(var o in a["ДопАдрЭл"]){for(var r in $p.fias)4==r.length&&a["ДопАдрЭл"][o][r]&&(i[$p.fias[r].type]=$p.fias[r].name+" "+a["ДопАдрЭл"][o][r]);a["ДопАдрЭл"][o][101e5]&&(v.postal_code=a["ДопАдрЭл"][o][101e5])}v.address_fields=a,v.region=a["СубъектРФ"]||a["Округ"]||"",v.city=a["Город"]||a["НаселПункт"]||"",v.street=a["Улица"]||"";for(var o in i)v.street+=" "+i[o]}return new Promise(function(e,t){if($p.ipinfo||($p.ipinfo=new IPInfo),window.google&&window.google.maps)e();else{$p.load_script("//maps.google.com/maps/api/js?callback=$p.ipinfo.location_callback","script",function(){});var n=$p.eve.attachEvent("geo_google_ready",function(){a&&clearTimeout(a),n&&($p.eve.detachEvent(n),n=null,e())}),a=setTimeout(function(){n&&($p.eve.detachEvent(n),n=null),$p.msg.show_msg({type:"alert-warning",text:$p.msg.error_geocoding+" Google",title:$p.msg.main_title}),e()},1e4)}}).then(function(){v.coordinates.length?(v.latitude=v.coordinates[0],v.longitude=v.coordinates[1]):_.shipping_address?p(function(e,t){t==google.maps.GeocoderStatus.OK&&(v.latitude=e[0].geometry.location.lat(),v.longitude=e[0].geometry.location.lng())}):$p.ipinfo.latitude&&$p.ipinfo.longitude?(v.latitude=$p.ipinfo.latitude,v.longitude=$p.ipinfo.longitude):(v.latitude=55.635924,v.longitude=37.6066379,$p.msg.show_msg($p.msg.empty_geocoding))})}function p(e){var t=r();$p.ipinfo.ggeocoder.geocode({address:t},e)}function d(){null!=v.marker.getAnimation()?v.marker.setAnimation(null):(v.marker.setAnimation(google.maps.Animation.BOUNCE),setTimeout(function(){v.marker.setAnimation(null)},1500))}function u(e){$p.ipinfo.ggeocoder.geocode({latLng:e.latLng},function(t,n){if(n==google.maps.GeocoderStatus.OK&&t[0]){var a=t[0];h.setText(a.formatted_address),$p.ipinfo.components(v,a.address_components),s();var i=v.street?15:12;h.elmnts.map.getZoom()!=i&&(h.elmnts.map.setZoom(i),h.elmnts.map.setCenter(e.latLng)),v.latitude=e.latLng.lat(),v.longitude=e.latLng.lng()}})}function f(e,t,n){e&&(v.delivery_area.empty()?(t=n,$p.msg.show_msg({type:"alert",text:$p.msg.delivery_area_empty,title:$p.msg.addr_title}),setTimeout(function(){h.elmnts.pgrid.selectRowById("delivery_area")},50)):"delivery_area"==e?a(t):(v[h.elmnts.pgrid.getSelectedRowId()]=t,o()))}function m(t){return e.grid.editStop(),!t.error}var h,_=e.obj,g=e.pwnd,b=_.delivery_area,v={coordinates:_.coordinates?JSON.parse(_.coordinates):[],country:"Россия",region:"",city:"",street:"",postal_code:"",marker:{}};return v.__define("delivery_area",{get:function(){return b},set:function(e){a(e)}}),c().then(t),h}function AppEvents(){if(this.__define({init:{value:function(){$p.__define("job_prm",{value:new JobPrm,writable:!1}),$p.wsql.init_params()}},do_eventable:{value:function(e){function t(e,t){e=String(e).toLowerCase(),this._evnts.data[e]||(this._evnts.data[e]={});var n=$p.utils.generate_guid();return this._evnts.data[e][n]=t,n}function n(e){if(!e)return a.call(this);for(var t in this._evnts.data){var n=0;for(var i in this._evnts.data[t])i==e?(this._evnts.data[t][i]=null,delete this._evnts.data[t][i]):n++;0==n&&(this._evnts.data[t]=null,delete this._evnts.data[t])}}function a(){for(var e in this._evnts.data){for(var t in this._evnts.data[e])this._evnts.data[e][t]=null,delete this._evnts.data[e][t];this._evnts.data[e]=null,delete this._evnts.data[e]}}function i(e,t){if(e=String(e).toLowerCase(),null==this._evnts.data[e])return!0;var n=!0;for(var a in this._evnts.data[e])n=this._evnts.data[e][a].apply(this,t)&&n;return n}function s(){for(var e in this._evnts.evnts){var t=this._evnts.evnts[e].length;if(t){for(var n=0;n<t;n++)this.emit(e,this._evnts.evnts[e][n]);this._evnts.evnts[e].length=0}}this._evnts.timer=0}e.__define({_evnts:{value:{data:{},timer:0,evnts:{}}},on:{value:t},attachEvent:{value:t},off:{value:n},detachEvent:{value:n},detachAllEvents:{value:a},checkEvent:{value:function(e){return e=String(e).toLowerCase(),null!=this._evnts.data[e]}},callEvent:{value:i},emit:{value:i},emit_async:{value:function(e,t){this._evnts.evnts[e]||(this._evnts.evnts[e]=[]),this._evnts.evnts[e].push(t),this._evnts.timer&&clearTimeout(this._evnts.timer),this._evnts.timer=setTimeout(s.bind(this),4)}}})}}}),"undefined"!=typeof window&&window.dhx4){for(var e in dhx4)this[e]=dhx4[e],delete dhx4[e];window.dhx4=this}else"undefined"==typeof WorkerGlobalScope&&this.do_eventable(this)}function JobPrm(){function e(){return $p.wsql.get_user_param("rest_path")||$p.job_prm.rest_path||"/a/zd/%1/odata/standard.odata/"}function t(){function e(e){var t,n={},a=[];if("#"!==e.substr(0,1)&&"?"!==e.substr(0,1)||(e=e.substr(1)),e.length>2){t=decodeURI(e).split("&");for(var i in t)if(a=t[i].split("="),"m"==a[0])try{n[a[0]]=JSON.parse(a[1])}catch(e){n[a[0]]={}}else n[a[0]]=a[1]||""}return n}return e(location.search)._mixin(e(location.hash))}this.__define({parse_url:{value:t},offline:{value:!1,writable:!0},local_storage_prefix:{value:"",writable:!0},create_tables:{value:!0,writable:!0},url_prm:{value:"undefined"!=typeof window?t():{}},rest_url:{value:function(){var t=e(),n=$p.wsql.get_user_param("zone",$p.job_prm.zone_is_string?"string":"number");return n?t.replace("%1",n):t.replace("%1/","")}},irest_url:{value:function(){var t=e(),n=$p.wsql.get_user_param("zone",$p.job_prm.zone_is_string?"string":"number");return t=t.replace("odata/standard.odata","hs/rest"),n?t.replace("%1",n):t.replace("%1/","")}}}),$p.eve.callEvent("settings",[this]);for(var n in this)"url_prm"!==n&&"function"!=typeof this[n]&&this.url_prm.hasOwnProperty[n]&&(this[n]=this.url_prm[n])}function Modifiers(){var e=[];this.push=function(t){e.push(t)},this.detache=function(t){var n=e.indexOf(t);n!=-1&&e.splice(n,1)},this.clear=function(){e.length=0},this.execute=function(t){var n,a;return e.forEach(function(e){a="function"==typeof e?e(t):$p.injected_data[e](t),n!==!1&&(n=a)}),n},this.execute_external=function(e){var t=$p.wsql.get_user_param("modifiers");return t=t?t.split("\n").map(function(e){return e?new Promise(function(t,n){$p.load_script(e,"script",t)}):Promise.resolve()}):[],Promise.all(t).then(function(){this.execute(e)}.bind(this))}}function IPInfo(){function e(){this.geocode=function(e){return Promise.resolve(!1)}}var t,n,a,i="";this.__define({ipgeo:{value:function(){return $p.ajax.get("//api.sypexgeo.net/").then(function(e){return JSON.parse(e.response)}).catch($p.record_log)}},yageocoder:{get:function(){return t||(t=new e),t},enumerable:!1,configurable:!1},ggeocoder:{get:function(){return n},enumerable:!1,configurable:!1},addr:{get:function(){return i}},parts:{get:function(){return a}},components:{value:function(e,t){var n,a,i,s="",o="",r="";for(n in t){a=t[n];for(i in a.types)switch(a.types[i]){case"route":a.short_name.indexOf("Unnamed")==-1&&(s=a.short_name+(s?" "+s:""),o=a.long_name.replace("улица","").trim());break;case"administrative_area_level_1":e.region=a.long_name;break;case"administrative_area_level_2":e.city=a.short_name,e.city_long=a.long_name;break;case"locality":r=(r?r+" ":"")+a.short_name;break;case"street_number":s=(s?s+" ":"")+a.short_name;break;case"postal_code":e.postal_code=a.short_name}}return e.region&&e.region==e.city_long?e.city.indexOf(r)==-1?e.city=r:e.city="":r&&e.city.indexOf(r)==-1&&e.region.indexOf(r)==-1&&(s=r+", "+s),e.street&&e.street.indexOf(o)!=-1||(e.street=s),e}},location_callback:{value:function(){n=new google.maps.Geocoder,$p.eve.callEvent("geo_google_ready"),navigator.geolocation&&navigator.geolocation.getCurrentPosition(function(e){$p.ipinfo.latitude=e.coords.latitude,$p.ipinfo.longitude=e.coords.longitude;var t=new google.maps.LatLng($p.ipinfo.latitude,$p.ipinfo.longitude);n.geocode({latLng:t},function(e,t){t==google.maps.GeocoderStatus.OK&&(a=!e[1]||e[0].address_components.length>=e[1].address_components.length?e[0]:e[1],i=a.formatted_address,$p.eve.callEvent("geo_current_position",[$p.ipinfo.components({},a.address_components)]))})},$p.record_log,{timeout:3e4})}}})}function SpreadsheetDocument(e){this._attr={orientation:"portrait",title:"",content:document.createElement("DIV")},e&&"string"==typeof e?this.content=e:"object"==typeof e&&this._mixin(e),e=null}function HandsontableDocument(e,t){var n=function(){this._then&&this._then(this)}.bind(this);this._online=t&&t.allow_offline||navigator.onLine&&$p.wsql.pouch.authorized,e instanceof dhtmlXCellObject?(this._cont=document.createElement("div"),e.detachObject(!0),e.attachObject(this._cont)):this._cont=e,this._cont.classList.add("handsontable_wrapper"),this._online?this._cont.innerHTML=t.autorun?$p.msg.report_prepare:$p.msg.report_need_prepare:this._cont.innerHTML=$p.msg.report_need_online,this.then=function(e){return this._then=e,this},this.requery=function(e){this.hot&&this.hot.destroy(),e instanceof Error?this._cont.innerHTML=$p.msg.report_error+(e.name?" <b>"+e.name+"</b>":"")+(e.message?" "+e.message:""):(this._cont.innerHTML="",this.hot=new Handsontable(this._cont,e))},"function"!=typeof Handsontable&&this._online?$p.load_script("https://cdnjs.cloudflare.com/ajax/libs/pikaday/1.4.0/pikaday.min.js","script").then(function(){return $p.load_script("https://cdnjs.cloudflare.com/ajax/libs/numbro/1.9.2/numbro.min.js","script")}).then(function(){return $p.load_script("https://cdn.jsdelivr.net/g/zeroclipboard,handsontable@0.26(handsontable.min.js)","script")}).then(function(){return Promise.all([$p.load_script("https://cdn.jsdelivr.net/handsontable/0.26/handsontable.min.css","link"),$p.load_script("https://cdnjs.cloudflare.com/ajax/libs/numbro/1.9.2/languages/ru-RU.min.js","script")])}).then(n):setTimeout(n)}function Aes(e){"use strict";function t(e){return encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode("0x"+t)})}function n(e){try{return decodeURIComponent(escape(e))}catch(t){return e}}function a(e){if("undefined"!=typeof btoa)return btoa(e);if("undefined"!=typeof Buffer)return new Buffer(e,"binary").toString("base64");throw new Error("No Base64 Encode")}function i(e){if("undefined"!=typeof atob)return atob(e);if("undefined"!=typeof Buffer)return new Buffer(e,"base64").toString("binary");throw new Error("No Base64 Decode")}var s=this;s.cipher=function(e,t){for(var n=4,a=t.length/n-1,i=[[],[],[],[]],o=0;o<4*n;o++)i[o%4][Math.floor(o/4)]=e[o];i=s.addRoundKey(i,t,0,n);for(var r=1;r<a;r++)i=s.subBytes(i,n),i=s.shiftRows(i,n),i=s.mixColumns(i,n),i=s.addRoundKey(i,t,r,n);i=s.subBytes(i,n),i=s.shiftRows(i,n),i=s.addRoundKey(i,t,a,n);for(var l=new Array(4*n),o=0;o<4*n;o++)l[o]=i[o%4][Math.floor(o/4)];return l},s.keyExpansion=function(e){for(var t=4,n=e.length/4,a=n+6,i=new Array(t*(a+1)),o=new Array(4),r=0;r<n;r++){var l=[e[4*r],e[4*r+1],e[4*r+2],e[4*r+3]];i[r]=l}for(var r=n;r<t*(a+1);r++){i[r]=new Array(4);for(var c=0;c<4;c++)o[c]=i[r-1][c];if(r%n==0){o=s.subWord(s.rotWord(o));for(var c=0;c<4;c++)o[c]^=s.rCon[r/n][c]}else n>6&&r%n==4&&(o=s.subWord(o));for(var c=0;c<4;c++)i[r][c]=i[r-n][c]^o[c]}return i},s.subBytes=function(e,t){for(var n=0;n<4;n++)for(var a=0;a<t;a++)e[n][a]=s.sBox[e[n][a]];return e},s.shiftRows=function(e,t){for(var n=new Array(4),a=1;a<4;a++){for(var i=0;i<4;i++)n[i]=e[a][(i+a)%t];for(var i=0;i<4;i++)e[a][i]=n[i]}return e},s.mixColumns=function(e,t){for(var n=0;n<4;n++){for(var a=new Array(4),i=new Array(4),s=0;s<4;s++)a[s]=e[s][n],i[s]=128&e[s][n]?e[s][n]<<1^283:e[s][n]<<1;e[0][n]=i[0]^a[1]^i[1]^a[2]^a[3],e[1][n]=a[0]^i[1]^a[2]^i[2]^a[3],e[2][n]=a[0]^a[1]^i[2]^a[3]^i[3],e[3][n]=a[0]^i[0]^a[1]^a[2]^i[3]}return e},s.addRoundKey=function(e,t,n,a){for(var i=0;i<4;i++)for(var s=0;s<a;s++)e[i][s]^=t[4*n+s][i];return e},s.subWord=function(e){for(var t=0;t<4;t++)e[t]=s.sBox[e[t]];return e},s.rotWord=function(e){for(var t=e[0],n=0;n<3;n++)e[n]=e[n+1];return e[3]=t,e},s.sBox=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],s.rCon=[[0,0,0,0],[1,0,0,0],[2,0,0,0],[4,0,0,0],[8,0,0,0],[16,0,0,0],[32,0,0,0],[64,0,0,0],[128,0,0,0],[27,0,0,0],[54,0,0,0]],s.Ctr={},s.Ctr.encrypt=function(n,i,o){var r=16;128!=o&&192!=o&&256!=o&&(o=128),n=t(n),i=t(i||e);for(var l=o/8,c=new Array(l),p=0;p<l;p++)c[p]=p<i.length?i.charCodeAt(p):0;var d=s.cipher(c,s.keyExpansion(c));d=d.concat(d.slice(0,l-16));for(var u=new Array(r),f=(new Date).getTime(),m=f%1e3,h=Math.floor(f/1e3),_=Math.floor(65535*Math.random()),p=0;p<2;p++)u[p]=m>>>8*p&255;for(var p=0;p<2;p++)u[p+2]=_>>>8*p&255;for(var p=0;p<4;p++)u[p+4]=h>>>8*p&255;for(var g="",p=0;p<8;p++)g+=String.fromCharCode(u[p]);for(var b=s.keyExpansion(d),v=Math.ceil(n.length/r),x="",y=0;y<v;y++){for(var w=0;w<4;w++)u[15-w]=y>>>8*w&255;for(var w=0;w<4;w++)u[15-w-4]=y/4294967296>>>8*w;for(var k=s.cipher(u,b),$=y<v-1?r:(n.length-1)%r+1,j=new Array($),p=0;p<$;p++)j[p]=k[p]^n.charCodeAt(y*r+p),j[p]=String.fromCharCode(j[p]);x+=j.join(""),"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&y%1e3==0&&self.postMessage({progress:y/v})}return x=a(g+x)},s.Ctr.decrypt=function(a,o,r){var l=16;128!=r&&192!=r&&256!=r&&(r=128),a=i(a),o=t(o||e);for(var c=r/8,p=new Array(c),d=0;d<c;d++)p[d]=d<o.length?o.charCodeAt(d):0;var u=s.cipher(p,s.keyExpansion(p));u=u.concat(u.slice(0,c-16));for(var f=new Array(8),m=a.slice(0,8),d=0;d<8;d++)f[d]=m.charCodeAt(d);for(var h=s.keyExpansion(u),_=Math.ceil((a.length-8)/l),g=new Array(_),b=0;b<_;b++)g[b]=a.slice(8+b*l,8+b*l+l);a=g;for(var v="",b=0;b<_;b++){for(var x=0;x<4;x++)f[15-x]=b>>>8*x&255;for(var x=0;x<4;x++)f[15-x-4]=(b+1)/4294967296-1>>>8*x&255;for(var y=s.cipher(f,h),w=new Array(a[b].length),d=0;d<a[b].length;d++)w[d]=y[d]^a[b].charCodeAt(d),w[d]=String.fromCharCode(w[d]);v+=w.join(""),"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&b%1e3==0&&self.postMessage({progress:b/_})}return v=n(v)}}!function(e,t){"object"==typeof exports&&"undefined"!=typeof module&&"function"==typeof require?t(require("../moment")):"function"==typeof define&&define.amd?define(["../moment"],t):t(e.moment)}(this,function(e){"use strict";function t(e,t){var n=e.split("_");return t%10===1&&t%100!==11?n[0]:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?n[1]:n[2]}function n(e,n,a){var i={mm:n?"минута_минуты_минут":"минуту_минуты_минут",hh:"час_часа_часов",dd:"день_дня_дней",MM:"месяц_месяца_месяцев",yy:"год_года_лет"};return"m"===a?n?"минута":"минуту":e+" "+t(i[a],+e)}var a=[/^янв/i,/^фев/i,/^мар/i,/^апр/i,/^ма[йя]/i,/^июн/i,/^июл/i,/^авг/i,/^сен/i,/^окт/i,/^ноя/i,/^дек/i],i=e.defineLocale("ru",{months:{format:"января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря".split("_"),standalone:"январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_")},monthsShort:{format:"янв._февр._мар._апр._мая_июня_июля_авг._сент._окт._нояб._дек.".split("_"),standalone:"янв._февр._март_апр._май_июнь_июль_авг._сент._окт._нояб._дек.".split("_")},weekdays:{standalone:"воскресенье_понедельник_вторник_среда_четверг_пятница_суббота".split("_"),format:"воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу".split("_"),isFormat:/\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/},weekdaysShort:"вс_пн_вт_ср_чт_пт_сб".split("_"),weekdaysMin:"вс_пн_вт_ср_чт_пт_сб".split("_"),monthsParse:a,longMonthsParse:a,shortMonthsParse:a,monthsRegex:/^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i,monthsShortRegex:/^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i,monthsStrictRegex:/^(январ[яь]|феврал[яь]|марта?|апрел[яь]|ма[яй]|июн[яь]|июл[яь]|августа?|сентябр[яь]|октябр[яь]|ноябр[яь]|декабр[яь])/i,monthsShortStrictRegex:/^(янв\.|февр?\.|мар[т.]|апр\.|ма[яй]|июн[ья.]|июл[ья.]|авг\.|сент?\.|окт\.|нояб?\.|дек\.)/i,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY г.",LLL:"D MMMM YYYY г., HH:mm",LLLL:"dddd, D MMMM YYYY г., HH:mm"},calendar:{sameDay:"[Сегодня в] LT",nextDay:"[Завтра в] LT",lastDay:"[Вчера в] LT",nextWeek:function(e){if(e.week()===this.week())return 2===this.day()?"[Во] dddd [в] LT":"[В] dddd [в] LT";switch(this.day()){case 0:return"[В следующее] dddd [в] LT";case 1:case 2:case 4:return"[В следующий] dddd [в] LT";case 3:case 5:case 6:return"[В следующую] dddd [в] LT"}},lastWeek:function(e){if(e.week()===this.week())return 2===this.day()?"[Во] dddd [в] LT":"[В] dddd [в] LT";switch(this.day()){case 0:return"[В прошлое] dddd [в] LT";case 1:case 2:case 4:return"[В прошлый] dddd [в] LT";case 3:case 5:case 6:return"[В прошлую] dddd [в] LT"}},sameElse:"L"},relativeTime:{future:"через %s",past:"%s назад",s:"несколько секунд",m:n,mm:n,h:"час",hh:n,d:"день",dd:n,M:"месяц",MM:n,y:"год",yy:n},meridiemParse:/ночи|утра|дня|вечера/i,isPM:function(e){return/^(дня|вечера)$/.test(e)},meridiem:function(e,t,n){return e<4?"ночи":e<12?"утра":e<17?"дня":"вечера"},ordinalParse:/\d{1,2}-(й|го|я)/,ordinal:function(e,t){switch(t){case"M":case"d":case"DDD":return e+"-й";case"D":return e+"-го";case"w":case"W":return e+"-я";default:return e}},week:{dow:1,doy:7}});return i}),Object.defineProperties(Object.prototype,{__define:{value:function(e,t){return t?Object.defineProperty(this,e,t):Object.defineProperties(this,e),this}},_extend:{value:function(e){var t=function(){};t.prototype=e.prototype,this.prototype=new t,this.prototype.constructor=this,this.__define("superclass",{value:e.prototype,enumerable:!1})}},_mixin:{value:function(e,t,n){var a,i,s={};if(t&&t.length)for(a=0;a<t.length;a++)i=t[a],n&&n.indexOf(i)!=-1||"undefined"!=typeof s[i]&&s[i]==e[i]||(this[i]=e[i]);else for(i in e)n&&n.indexOf(i)!=-1||"undefined"!=typeof s[i]&&s[i]==e[i]||(this[i]=e[i]);return this}},_clone:{value:function(){if(!this||"object"!=typeof this)return this;var e,t,n="function"==typeof this.pop?[]:{};for(e in this)this.hasOwnProperty(e)&&(t=this[e],t?"function"==typeof t||t instanceof DataObj||t instanceof DataManager||t instanceof Date?n[e]=t:"object"==typeof t?n[e]=t._clone():n[e]=t:n[e]=t);return n}}}),Number.prototype.round||(Number.prototype.round=function(e){var t=Math.pow(10,e);return Math.round(this*t)/t}),Number.prototype.pad||(Number.prototype.pad=function(e){for(var t=String(this);t.length<(e||2);)t="0"+t;return t}),Object.observe||Object.unobserve||Object.getNotifier||Object.prototype.__define({observe:{value:function(e,t){e._observers||e.__define({_observers:{value:[],enumerable:!1},_notis:{value:[],enumerable:!1}}),e._observers.push(t)},enumerable:!1},unobserve:{value:function(e,t){if(e._observers){t||(e._observers.length=0);for(var n=0;n<e._observers.length;n++)if(e._observers[n]===t){e._observers.splice(n,1);break}}},enumerable:!1},getNotifier:{value:function(e){var t;return{notify:function(n){e._observers&&n&&(n.object||(n.object=e),e._notis.push(n),n=null,t&&clearTimeout(t),t=setTimeout(function(){e._notis.length&&(e._observers.forEach(function(t){t(e._notis)}),e._notis.length=0),t=!1},4))}}},enumerable:!1}});var $p=new MetaEngine;$p.__define({iface:{value:new InterfaceObjs,writable:!1},current_user:{get:function(){return $p.cat&&$p.cat.users?$p.cat.users.by_id($p.wsql.get_user_param("user_name")):$p.utils.blank.guid}},current_acl:{get:function(){var e,t;return $p.cat&&$p.cat.users_acl&&($p.cat.users_acl.find_rows({owner:$p.current_user},function(t){return e=t,!1}),t=$p.CatUsers_acl.prototype),t||(t={}),e||(this.utils.blank.users_acl?e=this.utils.blank.users_acl:(e=this.utils.blank.users_acl=Object.create(t),e.__define({acl_objs:{value:{_obj:[],each:function(){},find_rows:function(){}}}}))),t.hasOwnProperty("role_available")||t.__define({role_available:{value:function(e){return this.acl_objs._obj.some(function(t){return t.type==e})}},get_acl:{value:function(e){var t=e.split(".");return this._acl&&this._acl[t[0]]?this._acl[t[0]][t[1]]:"e"}}}),e}},load_script:{value:function(e,t,n){return new Promise(function(a,i){var s=document.createElement(t);"script"==t?(s.type="text/javascript",s.src=e,s.async=!0,s.addEventListener("load",n?function(){n(),a()}:a,!1)):(s.type="text/css",s.rel="stylesheet",s.href=e),document.head.appendChild(s),"script"!=t&&a()})}}}),"undefined"!=typeof window&&window.dhx4&&(dhx4.dateFormat.ru="%d.%m.%Y",dhx4.dateLang="ru",dhx4.dateStrings={ru:{monthFullName:["Январь","Февраль","Март","Апрель","Maй","Июнь","Июль","Август","Сентябрь","Oктябрь","Ноябрь","Декабрь"],monthShortName:["Янв","Фев","Maр","Aпр","Maй","Июн","Июл","Aвг","Сен","Окт","Ноя","Дек"],dayFullName:["Воскресенье","Понедельник","Вторник","Среда","Четверг","Пятница","Суббота"],dayShortName:["Вс","Пн","Вт","Ср","Чт","Пт","Сб"]}}),$p.fias=function(){},function(e){e.toString=function(){return"Коды адресного классификатора"},e.types=["владение","здание","помещение"],e[1010]={name:"дом",type:1,order:1,fid:2,syn:[" д."," д "," дом"]},e[1020]={name:"владение",type:1,order:2,fid:1,syn:[" вл."," вл "," влад."," влад "," владен."," владен "," владение"]},e[1030]={name:"домовладение",type:1,order:3,fid:3},e[1050]={name:"корпус",type:2,order:1,syn:[" к."," к "," корп."," корп ","корпус"]},e[1060]={name:"строение",type:2,order:2,fid:1,syn:[" стр."," стр "," строен."," строен ","строение"]},e[1080]={name:"литера",type:2,order:3,fid:3,syn:[" л."," л "," лит."," лит ","литера"]},e[1070]={name:"сооружение",type:2,order:4,fid:2,syn:[" соор."," соор "," сооруж."," сооруж ","сооружение"]},e[1040]={name:"участок",type:2,order:5,syn:[" уч."," уч ","участок"]},e[2010]={name:"квартира",type:3,order:1,syn:["кв.","кв ","кварт.","кварт ","квартира","-"]},e[2030]={name:"офис",type:3,order:2,syn:["оф.","оф ","офис","-"]},e[2040]={name:"бокс",type:3,order:3},e[2020]={name:"помещение",type:3,order:4},e[2050]={name:"комната",type:3,order:5,syn:["комн.","комн ","комната"]},e[101e5]={name:"Почтовый индекс"},e[102e5]={name:"Адресная точка"},e[103e5]={name:"Садовое товарищество"},e[104e5]={name:"Элемент улично-дорожной сети, планировочной структуры дополнительного адресного элемента"},e[105e5]={name:"Промышленная зона"},e[106e5]={name:"Гаражно-строительный кооператив"},e[107e5]={name:"Территория"}}($p.fias),function(e){e.store_url_od="https://chrome.google.com/webstore/detail/hcncallbdlondnoadgjomnhifopfaage",e.argument_is_not_ref="Аргумент не является ссылкой",e.addr_title="Ввод адреса",e.cache_update_title="Обновление кеша браузера",e.cache_update="Выполняется загрузка измененных файлов<br/>и их кеширование в хранилище браузера",e.cancel="Отмена",e.delivery_area_empty="Укажите район доставки",e.empty_login_password="Не указаны имя пользователя или пароль",e.empty_response="Пустой ответ сервера",e.empty_geocoding="Пустой ответ геокодера. Вероятно, отслеживание адреса запрещено в настройках браузера",e.error_geocoding="Ошибка геокодера",e.error_auth="Авторизация пользователя не выполнена",e.error_critical="Критическая ошибка",e.error_metadata="Ошибка загрузки метаданных конфигурации",e.error_network="Ошибка сети или сервера - запрос отклонен",e.error_rights="Ограничение доступа",e.error_low_acl="Недостаточно прав для выполнения операции",e.file_size="Запрещена загрузка файлов<br/>размером более ",e.file_confirm_delete="Подтвердите удаление файла ",e.file_new_date="Файлы на сервере обновлены<br /> Рекомендуется закрыть браузер и войти<br />повторно для применения обновления",e.file_new_date_title="Версия файлов",e.init_catalogues="Загрузка справочников с сервера",e.init_catalogues_meta=": Метаданные объектов",e.init_catalogues_tables=": Реструктуризация таблиц",e.init_catalogues_nom=": Базовые типы + номенклатура",e.init_catalogues_sys=": Технологические справочники", -e.init_login="Укажите имя пользователя и пароль",e.requery="Повторите попытку через 1-2 минуты",e.limit_query="Превышено число обращений к серверу<br/>Запросов за минуту:%1<br/>Лимит запросов:%2<br/>"+e.requery,e.long_operation="Длительная операция",e.logged_in="Авторизован под именем: ",e.log_out_title="Отключиться от сервера?",e.log_out_break="<br/>Завершить синхронизацию?",e.sync_title="Обмен с сервером",e.sync_complite="Синхронизация завершена",e.main_title="Окнософт: заказ дилера ",e.mark_delete_confirm="Пометить объект %1 на удаление?",e.mark_undelete_confirm="Снять пометку удаления с объекта %1?",e.meta={cat:"Справочник",doc:"Документ",cch:"План видов характеристик",cacc:"Планы счетов",tsk:"Задача",ireg:"Регистр сведений",areg:"Регистр накопления",bp:"Бизнес процесс",ts_row:"Строка табличной части",dp:"Обработка",rep:"Отчет"},e.meta_cat="Справочники",e.meta_doc="Документы",e.meta_cch="Планы видов характеристик",e.meta_cacc="Планы счетов",e.meta_tsk="Задачи",e.meta_ireg="Регистры сведений",e.meta_areg="Регистры накопления",e.meta_mgr="Менеджер",e.meta_cat_mgr="Менеджер справочников",e.meta_doc_mgr="Менеджер документов",e.meta_enn_mgr="Менеджер перечислений",e.meta_ireg_mgr="Менеджер регистров сведений",e.meta_areg_mgr="Менеджер регистров накопления",e.meta_accreg_mgr="Менеджер регистров бухгалтерии",e.meta_dp_mgr="Менеджер обработок",e.meta_task_mgr="Менеджер задач",e.meta_bp_mgr="Менеджер бизнес-процессов",e.meta_reports_mgr="Менеджер отчетов",e.meta_charts_of_accounts_mgr="Менеджер планов счетов",e.meta_charts_of_characteristic_mgr="Менеджер планов видов характеристик",e.meta_extender="Модификаторы объектов и менеджеров",e.modified_close="Объект изменен<br/>Закрыть без сохранения?",e.mandatory_title="Обязательный реквизит",e.mandatory_field="Укажите значение реквизита '%1'",e.no_metadata="Не найдены метаданные объекта '%1'",e.no_selected_row="Не выбрана строка табличной части '%1'",e.no_dhtmlx="Библиотека dhtmlx не загружена",e.not_implemented="Не реализовано в текущей версии",e.offline_request="Запрос к серверу в автономном режиме",e.onbeforeunload="Окнософт: легкий клиент. Закрыть программу?",e.order_sent_title="Подтвердите отправку заказа",e.order_sent_message="Отправленный заказ нельзя изменить.<br/>После проверки менеджером<br/>он будет запущен в работу",e.report_error="<i class='fa fa-exclamation-circle fa-2x fa-fw'></i> Ошибка",e.report_prepare="<i class='fa fa-spinner fa-spin fa-2x fa-fw'></i> Подготовка отчета",e.report_need_prepare="<i class='fa fa-info fa-2x fa-fw'></i> Нажмите 'Сформировать' для получения отчета",e.report_need_online="<i class='fa fa-plug fa-2x fa-fw'></i> Нет подключения. Отчет недоступен в автономном режиме",e.request_title="Запрос регистрации",e.request_message="Заявка зарегистрирована. После обработки менеджером будет сформировано ответное письмо",e.select_from_list="Выбор из списка",e.select_grp="Укажите группу, а не элемент",e.select_elm="Укажите элемент, а не группу",e.select_file_import="Укажите файл для импорта",e.srv_overload="Сервер перегружен",e.sub_row_change_disabled="Текущая строка подчинена продукции.<br/>Строку нельзя изменить-удалить в документе<br/>только через построитель",e.sync_script="Обновление скриптов приложения:",e.sync_data="Синхронизация с сервером выполняется:<br />* при первом старте программы<br /> * при обновлении метаданных<br /> * при изменении цен или технологических справочников",e.sync_break="Прервать синхронизацию",e.sync_no_data="Файл не содержит подходящих элементов для загрузки",e.tabular_will_cleared="Табличная часть '%1' будет очищена. Продолжить?",e.unsupported_browser_title="Браузер не поддерживается",e.unsupported_browser="Несовместимая версия браузера<br/>Рекомендуется Google Chrome",e.supported_browsers="Рекомендуется Chrome, Safari или Opera",e.unsupported_mode_title="Режим не поддерживается",e.unsupported_mode="Программа не установлена<br/> в <a href='"+e.store_url_od+"'>приложениях Google Chrome</a>",e.unknown_error="Неизвестная ошибка в функции '%1'",e.value="Значение"}($p.msg),DataManager.prototype.__define({family_name:{get:function(){return $p.msg["meta_"+this.class_name.split(".")[0]+"_mgr"].replace($p.msg.meta_mgr+" ","")}},table_name:{get:function(){return this.class_name.replace(".","_")}},find_rows:{value:function(e,t){return $p._find_rows.call(this,this.by_ref,e,t)}},extra_fields:{value:function(e){var t=$p.cat.destinations||$p.cch.destinations,n=_md.class_name_to_1c(this.class_name).replace(".","_"),a=[];return t&&t.find_rows({predefined_name:n},function(e){var t=e.extra_fields||e.ДополнительныеРеквизиты;return t&&t.each(function(e){e._deleted||e.ПометкаУдаления||a.push(e.property||e.Свойство)}),!1}),a}},extra_properties:{value:function(e){return[]}},obj_constructor:{value:function(e){var t=this.class_name.split("."),n=t[0].charAt(0).toUpperCase()+t[0].substr(1)+t[1].charAt(0).toUpperCase()+t[1].substr(1);return e?n+e.charAt(0).toUpperCase()+e.substr(1)+"Row":n}}}),DataManager.prototype.sync_grid=function(e,t){function n(){if("function"==typeof e.custom_selection)return e.custom_selection(e);if("ram"==i.cachable){if("get_tree"==e.action)return $p.wsql.promise(i.get_sql_struct(e),[]).then($p.iface.data_to_tree);if("get_selection"==e.action)return $p.wsql.promise(i.get_sql_struct(e),[]).then(function(t){return $p.iface.data_to_grid.call(i,t,e)})}else if(0==i.cachable.indexOf("doc")){if("get_tree"==e.action)return i.pouch_tree(e);if("get_selection"==e.action)return i.pouch_selection(e)}else{if("get_tree"==e.action)return i.rest_tree(e);if("get_selection"==e.action)return i.rest_selection(e)}}function a(e){return new Promise(function(n,a){"string"==typeof e?("{"==e.substr(0,1)&&(e=JSON.parse(e)),t&&t.parse?(t.xmlFileUrl="exec",t.parse(e,function(){n(e)},"xml")):n(e)):t instanceof dhtmlXTreeView&&t.loadStruct?t.loadStruct(e,function(){n(e)}):n(e)})}var i=this;return n().then(a).catch($p.record_log)},DataManager.prototype.get_option_list=function(e,t){function n(t){return $p.utils.is_equal(t.value,e)&&(t.selected=!0),t}var a,i,s,o=this,r=[];if(t.presentation&&(a=o.metadata().input_by_string)&&(i=t.presentation.like,delete t.presentation,t.or=[],a.forEach(function(e){s={},s[e]={like:i},t.or.push(s)})),"ram"==o.cachable||t&&t._local)return o.find_rows(t,function(e){r.push(n({text:e.presentation,value:e.ref}))}),Promise.resolve(r);if("e1cib"!=o.cachable)return o.pouch_find_rows(t).then(function(e){return e.forEach(function(e){r.push(n({text:e.presentation,value:e.ref}))}),r});var l={selection:t,top:t._top},c=o instanceof DocManager||o instanceof BusinessProcessManager;return delete t._top,c?l.fields=["ref","date","number_doc"]:o.metadata().main_presentation_name?l.fields=["ref","name"]:l.fields=["ref","id"],_rest.load_array(l,o).then(function(e){return e.forEach(function(e){r.push(n({text:c?e.number_doc+" от "+$p.moment(e.date).format($p.moment._masks.ldt):e.name||e.id,value:e.ref}))}),r})},DataManager.prototype.tabular_captions=function(e,t){},DataManager.prototype.get_property_grid_xml=function(e,t,n){var a,i,s,o,r,l,c,p=this,d="<rows>",u=function(){if(!e)if(s=p.metadata(),s.form&&s.form.obj&&s.form.obj.head)e=s.form.obj.head;else{if(e={" ":[]},t instanceof CatObj?(s.code_length&&e[" "].push("id"),s.main_presentation_name&&e[" "].push("name")):t instanceof DocObj&&(e[" "].push("number_doc"),e[" "].push("date")),!t.is_folder)for(a in s.fields)"predefined_name"==a||s.fields[a].hide||e[" "].push(a);s.tabular_sections&&s.tabular_sections.extra_fields&&(e["Дополнительные реквизиты"]=[])}},f=function(e,t){l=$p.utils.is_data_obj(e)?e.presentation:e,t.type.is_ref||(t.type.date_part?l=$p.moment(l).format($p.moment._masks[t.type.date_part]):"boolean"==t.type.types[0]&&(l=l?"1":"0"))},m=function(e){r=_md.control_by_type(s.type,e),f(e,s)},h=function(e,a){if(a){var i=e.property||e.param||e.Параметр||e.Свойство,u=void 0!=e.value?e.value:e.Значение;i.empty()?(c=a+"|empty",r="ro",l="",s={synonym:"?"}):(s={synonym:i.presentation,type:i.type},c=a+"|"+i.ref,m(u),"edn"==r&&(r="calck"),i.mandatory&&(r+='" class="cell_mandatory'))}else if("object"==typeof e)c=e.id,s=n&&n.metadata&&n.metadata[c],s?e.synonym&&(s.synonym=e.synonym):s={synonym:e.synonym},r=e.type,l="",e.hasOwnProperty("txt")?l=e.txt:void 0!==(o=t[c])&&f(o,s.type?s:_md.get(p.class_name,c));else if(n&&n.metadata&&void 0!==(s=n.metadata[e]))c=e,m(o=t[e]);else{if(void 0===(o=t[e]))return;s=_md.get(p.class_name,c=e),m(o)}d+='<row id="'+c+'"><cell>'+(s.synonym||s.name)+'</cell><cell type="'+r+'">'+l+"</cell></row>"};u();for(a in e){" "!=a&&(d+='<row open="1"><cell>'+a+"</cell>");for(i in e[a])h(e[a][i]);if(n&&a==n.title&&t[n.ts]){var _,g=p.extra_fields(t),b="property,param,Свойство,Параметр".split(","),v=t[n.ts]._owner._metadata.tabular_sections[t[n.ts]._name].fields;b.some(function(e){if(v[e])return _=e,!0})&&(t[n.ts].forEach(function(e){var t=g.indexOf(e[_]);t!=-1&&g.splice(t,1)}),g.forEach(function(e){var a=t[n.ts].add();a[_]=e})),t[n.ts].find_rows(n.selection,function(e){h(e,n.ts)})}" "!=a&&(d+="</row>")}return d+="</rows>"},DataManager.prototype.print=function(e,t,n){function a(e){n&&n.progressOff&&n.progressOff(),e&&e.focus()}if(n&&n.progressOn&&n.progressOn(),setTimeout(a,3e3),this._printing_plates[t]instanceof DataObj&&(t=this._printing_plates[t]),t instanceof DataObj&&t.execute)return e instanceof DataObj?t.execute(e).then(a):this.get(e,!0,!0).then(t.execute.bind(t)).then(a);var i={};return $p.ajax.default_attr(i,$p.job_prm.irest_url()),i.url+=this.rest_name+"(guid'"+$p.utils.fix_guid(e)+"')/Print(model="+t+", browser_uid="+$p.wsql.get_user_param("browser_uid")+")",$p.ajax.get_and_show_blob(i.url,i,"get").then(a)},DataManager.prototype.printing_plates=function(){var e={},t=this;return t._printing_plates||(t.metadata().printing_plates?t._printing_plates=t.metadata().printing_plates:("ram"==t.metadata().cachable||t.metadata().cachable&&0==t.metadata().cachable.indexOf("doc"))&&(t._printing_plates={})),!t._printing_plates&&$p.ajax.authorized?($p.ajax.default_attr(e,$p.job_prm.irest_url()),e.url+=t.rest_name+"/Print()",$p.ajax.get_ex(e.url,e).then(function(e){return t._printing_plates=JSON.parse(e.response),t._printing_plates}).catch(function(){}).then(function(e){return e||(t._printing_plates={})})):Promise.resolve(t._printing_plates)},RefDataManager._extend(DataManager),RefDataManager.prototype.__define({push:{value:function(e,t){t&&t!=e.ref?(delete this.by_ref[e.ref],this.by_ref[t]=e):this.by_ref[e.ref]=e}},each:{value:function(e){for(var t in this.by_ref)if(t&&t!=$p.utils.blank.guid&&1==e.call(this,this.by_ref[t]))break}},forEach:{value:function(e){return this.each.call(this,e)}},get:{value:function(e,t,n){var a=this.by_ref[e]||this.by_ref[e=$p.utils.fix_guid(e)];if(!a){if(n&&!t)return;a=new($p[this.obj_constructor()])(e,this,(!0))}return t===!1?a:void 0===t&&e===$p.utils.blank.guid?a:a.is_new()?a.load():t?Promise.resolve(a):a}},create:{value:function(e,t,n){e&&"object"==typeof e||(e={}),e.ref&&$p.utils.is_guid(e.ref)&&!$p.utils.is_empty_guid(e.ref)||(e.ref=$p.utils.generate_guid());var a=this.by_ref[e.ref];if(!a)if(a=new($p[this.obj_constructor()])(e,this),!t&&e.ref&&e.presentation&&2==Object.keys(e).length);else{a instanceof DocObj&&a.date==$p.utils.blank.date&&(a.date=new Date);var i=this.handle_event(a,"after_create");if(this instanceof DocManager||this instanceof TaskManager||this instanceof BusinessProcessManager?a.number_doc||a.new_number_doc():!a.id&&a._metadata.code_length&&a.new_number_doc(),i===!1)return Promise.resolve(a);if("object"==typeof i&&i.then)return i;if("e1cib"==this.cachable&&t){var s={};return $p.ajax.default_attr(s,$p.job_prm.irest_url()),s.url+=this.rest_name+"/Create()",$p.ajax.get_ex(s.url,s).then(function(e){return a._mixin(JSON.parse(e.response),void 0,["ref"])})}}return n?a:Promise.resolve(a)}},unload_obj:{value:function(e){delete this.by_ref[e],this.alatable.some(function(t,n,a){if(t.ref==e)return a.splice(n,1),!0})}},find:{value:function(e,t){return $p._find(this.by_ref,e,t)}},load_array:{value:function(e,t){for(var n,a,i=[],s=0;s<e.length;s++){if(n=$p.utils.fix_guid(e[s]),a=this.by_ref[n])(a.is_new()||t)&&(a._mixin(e[s]),a._set_loaded());else{if("update_only"==t)continue;a=new($p[this.obj_constructor()])(e[s],this),t&&a._set_loaded()}i.push(a)}return i}},first_folder:{value:function(e){for(var t in this.by_ref){var n=this.by_ref[t];if(n.is_folder&&(!e||$p.utils.is_equal(e,n.owner)))return n}return this.get()}},get_sql_struct:{value:function(e){function t(){function t(){var e=[],t="_t_.ref, _t_.`_deleted`";return r.form&&r.form.selection?r.form.selection.fields.forEach(function(t){e.push(t)}):o instanceof DocManager?(e.push("posted"),e.push("date"),e.push("number_doc")):(r.hierarchical&&r.group_hierarchy?e.push("is_folder"):e.push("0 as is_folder"),o instanceof ChartOfAccountManager?(e.push("id"),e.push("name as presentation")):r.main_presentation_name?e.push("name as presentation"):r.code_length?e.push("id as presentation"):e.push("'...' as presentation"),r.has_owners&&e.push("owner"),r.code_length&&e.push("id")),e.forEach(function(e){t+=e.indexOf(" as ")!=-1?", "+e:_md.sql_mask(e,!0)}),t}function n(){var e,t="";if(r.form&&r.form.selection)for(var n in r.form.selection.fields)r.form.selection.fields[n].indexOf(" as ")!=-1&&r.form.selection.fields[n].indexOf("_t_.")==-1&&(e=r.form.selection.fields[n].split(" as "),e[0]=e[0].split("."),e[0].length>1&&(t&&(t+="\n"),t+="left outer join "+e[0][0]+" on "+e[0][0]+".ref = _t_."+e[1]));return t}function a(){var t;return t=o instanceof ChartOfAccountManager?" WHERE ("+(u?0:1):r.hierarchical?r.has_owners?" WHERE ("+(c||u?1:0)+" OR _t_.parent = '"+p+"') AND ("+(l==$p.utils.blank.guid?1:0)+" OR _t_.owner = '"+l+"') AND ("+(u?0:1):" WHERE ("+(c||u?1:0)+" OR _t_.parent = '"+p+"') AND ("+(u?0:1):r.has_owners?" WHERE ("+(l==$p.utils.blank.guid?1:0)+" OR _t_.owner = '"+l+"') AND ("+(u?0:1):" WHERE ("+(u?0:1),o.sql_selection_where_flds?t+=o.sql_selection_where_flds(u):o instanceof DocManager?t+=" OR _t_.number_doc LIKE '"+u+"'":((r.main_presentation_name||o instanceof ChartOfAccountManager)&&(t+=" OR _t_.name LIKE '"+u+"'"),r.code_length&&(t+=" OR _t_.id LIKE '"+u+"'")),t+=") AND (_t_.ref != '"+$p.utils.blank.guid+"')",e.selection&&("function"==typeof e.selection||e.selection.forEach(function(e){for(var n in e)if("function"==typeof e[n])t+="\n AND "+e[n](o,n)+" ";else if(r.fields.hasOwnProperty(n)||"ref"===n)if(e[n]===!0)t+="\n AND _t_."+n+" ";else if(e[n]===!1)t+="\n AND (not _t_."+n+") ";else if("object"==typeof e[n])if($p.utils.is_data_obj(e[n])||$p.utils.is_guid(e[n]))t+="\n AND (_t_."+n+" = '"+e[n]+"') ";else{var a,i=Object.keys(e[n]),s=e[n][i[0]],l=r.fields[n];l&&l.type.is_ref&&(a=_md.value_mgr({},n,l.type,!0,s)),t+="not"==i[0]?"\n AND (not _t_."+n+" = '"+s+"') ":"in"==i[0]?"\n AND (_t_."+n+" in ("+e[n].in.reduce(function(e,t){return e&&(e+=","),e+="number"==typeof t?t.toString():"'"+t+"'"},"")+")) ":"\n AND (_t_."+n+" = '"+s+"') "}else t+="string"==typeof e[n]?"\n AND (_t_."+n+" = '"+e[n]+"') ":"\n AND (_t_."+n+" = "+e[n]+") ";else"is_folder"==n&&r.hierarchical&&r.group_hierarchy})),t}function i(){return o instanceof ChartOfAccountManager?"ORDER BY id":r.hierarchical?r.group_hierarchy?"ORDER BY _t_.is_folder desc, is_initial_value, presentation":"ORDER BY _t_.parent desc, is_initial_value, presentation":"ORDER BY is_initial_value, presentation"}function s(){function t(t){t&&(f=e.set_parent=t.parent.ref,p=f,c=!1),u&&u.indexOf("%")==-1&&(u="%"+u+"%")}r.has_owners&&(l=e.owner,e.selection&&"function"!=typeof e.selection&&e.selection.forEach(function(e){e.owner&&(l="object"==typeof e.owner?e.owner.valueOf():e.owner,delete e.owner)}),l||(l=$p.utils.blank.guid)),d!=$p.utils.blank.guid&&c&&r.hierarchical?t(o.get(d,!1)):t()}var l,c=!e.parent,p=e.parent||$p.utils.blank.guid,d=e.initial_value||$p.utils.blank.guid,u=e.filter||"",f=$p.utils.blank.guid;s();var m;return m=o.sql_selection_list_flds?o.sql_selection_list_flds(d):("SELECT %2, case when _t_.ref = '"+d+"' then 0 else 1 end as is_initial_value FROM `"+o.table_name+"` AS _t_ %j %3 %4 LIMIT 300").replace("%2",t()).replace("%j",n()),m.replace("%3",a()).replace("%4",i())}function n(){var t="CREATE TABLE IF NOT EXISTS ";if(e&&e.postgres){t+=o.table_name+" (ref uuid PRIMARY KEY NOT NULL, _deleted boolean",o instanceof DocManager?t+=", posted boolean, date timestamp with time zone, number_doc character(11)":(r.code_length&&(t+=", id character("+r.code_length+")"),t+=", name character varying(50), is_folder boolean");for(i in r.fields)i.length>30?r.fields[i].short_name?s=r.fields[i].short_name:(c++,s=i[0]+c+i.substr(i.length-27)):s=i,t+=", "+s+_md.sql_type(o,i,r.fields[i].type,!0)+_md.sql_composite(r.fields,i,s,!0);for(i in r.tabular_sections)t+=", ts_"+i+" JSON"}else{t+="`"+o.table_name+"` (ref CHAR PRIMARY KEY NOT NULL, `_deleted` BOOLEAN",t+=o instanceof DocManager?", posted boolean, date Date, number_doc CHAR":", id CHAR, name CHAR, is_folder BOOLEAN";for(i in r.fields)t+=_md.sql_mask(i)+_md.sql_type(o,i,r.fields[i].type)+_md.sql_composite(r.fields,i);for(i in r.tabular_sections)t+=", `ts_"+i+"` JSON"}return t+=")"}function a(){var e=["ref","_deleted"],t="INSERT INTO `"+o.table_name+"` (ref, `_deleted`",n="(?";"cat"==o.class_name.substr(0,3)?(t+=", id, name, is_folder",e.push("id"),e.push("name"),e.push("is_folder")):"doc"==o.class_name.substr(0,3)&&(t+=", posted, date, number_doc",e.push("posted"),e.push("date"),e.push("number_doc"));for(i in r.fields)t+=_md.sql_mask(i),e.push(i);for(i in r.tabular_sections)t+=", `ts_"+i+"`",e.push("ts_"+i);for(t+=") VALUES ",i=1;i<e.length;i++)n+=", ?";return n+=")",t+=n,{sql:t,fields:e,values:n}}var i,s,o=this,r=o.metadata(),l={},c=0,p=e&&e.action?e.action:"create_table";return"create_table"==p?l=n():["insert","update","replace"].indexOf(p)!=-1?l[o.table_name]=a():"select"==p?l="SELECT * FROM `"+o.table_name+"` WHERE ref = ?":"select_all"==p?l="SELECT * FROM `"+o.table_name+"`":"delete"==p?l="DELETE FROM `"+o.table_name+"` WHERE ref = ?":"drop"==p?l="DROP TABLE IF EXISTS `"+o.table_name+"`":"get_tree"==p?l=!e.filter||e.filter.is_folder?"SELECT ref, parent, name as presentation FROM `"+o.table_name+"` WHERE is_folder order by parent, name":"SELECT ref, parent, name as presentation FROM `"+o.table_name+"` order by parent, name":"get_selection"==p&&(l=t()),l}},caption_flds:{value:function(e){var t=e.metadata||this.metadata(),n='<column id="%1" width="%2" type="%3" align="%4" sort="%5">%6</column>',a=[],i="";if(t.form&&t.form.selection?a=t.form.selection.cols:this instanceof DocManager?(a.push(new Col_struct("date","160","ro","left","server","Дата")),a.push(new Col_struct("number_doc","140","ro","left","server","Номер")),t.fields.note&&a.push(new Col_struct("note","*","ro","left","server",t.fields.note.synonym)),t.fields.responsible&&a.push(new Col_struct("responsible","*","ro","left","server",t.fields.responsible.synonym))):this instanceof ChartOfAccountManager?(a.push(new Col_struct("id","140","ro","left","server","Код")),a.push(new Col_struct("presentation","*","ro","left","server","Наименование"))):a.push(new Col_struct("presentation","*","ro","left","server","Наименование")),e.get_header&&a.length){i="<head>";for(var s in a)i+=n.replace("%1",a[s].id).replace("%2",a[s].width).replace("%3",a[s].type).replace("%4",a[s].align).replace("%5",a[s].sort).replace("%6",a[s].caption);i+="</head>"}return{head:i,acols:a}}},load_cached_server_array:{value:function(e,t){var n,a=[],i=this,s=t?{class_name:i.class_name,rest_name:t}:i,o=!t;if(e.forEach(function(e){n=i.get(e.ref||e,!1,!0),(!n||o&&n.is_new())&&a.push(e.ref||e)}),a.length){var r={url:"",selection:{ref:{in:a}}};return o&&(r.fields=["ref"]),$p.rest.build_select(r,s),$p.ajax.get_ex(r.url,r).then(function(t){var n=JSON.parse(t.response);if(o)n=n.value;else{n=n.data;for(var a in n)!n[a].ref&&n[a].id&&(n[a].ref=n[a].id),n[a].Код&&(n[a].id=n[a].Код,delete n[a].Код),n[a]._not_set_loaded=!0}return i.load_array(n),e})}return Promise.resolve(e)}},predefined:{value:function(e){return this._predefined||(this._predefined={}),this._predefined[e]||(this._predefined[e]=this.get(),this.find_rows({predefined_name:e},function(t){return this._predefined[e]=t,!1})),this._predefined[e]}}}),DataProcessorsManager._extend(DataManager),DataProcessorsManager.prototype.__define({create:{value:function(){return new($p[this.obj_constructor()])({},this)}},unload_obj:{value:function(){}}}),EnumManager._extend(RefDataManager),EnumManager.prototype.__define({get:{value:function(e){if(e instanceof EnumObj)return e;e&&e!=$p.utils.blank.guid||(e="_");var t=this[e];return t||(t=new EnumObj({name:e},this)),t}},push:{value:function(e,t){this.__define(t,{value:e})}},each:{value:function(e){this.alatable.forEach(function(t){t.ref&&"_"!=t.ref&&t.ref!=$p.utils.blank.guid&&e.call(this[t.ref])}.bind(this))}}}),EnumManager.prototype.get_sql_struct=function(e){var t="CREATE TABLE IF NOT EXISTS ",n=e&&e.action?e.action:"create_table";return e&&e.postgres?"create_table"==n?t+=this.table_name+" (ref character varying(255) PRIMARY KEY NOT NULL, sequence INT, synonym character varying(255))":["insert","update","replace"].indexOf(n)!=-1?(t={},t[this.table_name]={sql:"INSERT INTO "+this.table_name+" (ref, sequence, synonym) VALUES ($1, $2, $3)",fields:["ref","sequence","synonym"],values:"($1, $2, $3)"}):"delete"==n&&(t="DELETE FROM "+this.table_name+" WHERE ref = $1"):"create_table"==n?t+="`"+this.table_name+"` (ref CHAR PRIMARY KEY NOT NULL, sequence INT, synonym CHAR)":["insert","update","replace"].indexOf(n)!=-1?(t={},t[this.table_name]={sql:"INSERT INTO `"+this.table_name+"` (ref, sequence, synonym) VALUES (?, ?, ?)",fields:["ref","sequence","synonym"],values:"(?, ?, ?)"}):"delete"==n&&(t="DELETE FROM `"+this.table_name+"` WHERE ref = ?"),t},EnumManager.prototype.get_option_list=function(e,t){function n(t){return $p.utils.is_equal(t.value,e)&&(t.selected=!0),t}var a,i=[],s="";if(t)for(var o in t)"_"!=o.substr(0,1)&&("ref"==o?a=t[o].hasOwnProperty("in")?t[o].in:t[o]:s=t[o]);return"object"==typeof s&&(s=s.like?s.like:""),s=s.toLowerCase(),this.alatable.forEach(function(e){if(!s||e.synonym&&e.synonym.toLowerCase().indexOf(s)!=-1){if(a)if(Array.isArray(a)){if(!a.some(function(t){return t.name==e.ref||t.ref==e.ref||t==e.ref}))return}else if(a.name!=e.ref&&a.ref!=e.ref&&a!=e.ref)return;i.push(n({text:e.synonym||"",value:e.ref}))}}),Promise.resolve(i)},RegisterManager._extend(DataManager),RegisterManager.prototype.__define({get_sql_struct:{value:function(e){function t(){function t(){var e=[],t="_t_.ref";if(r.form&&r.form.selection)r.form.selection.fields.forEach(function(t){e.push(t)});else for(var n in r.dimensions)e.push(n);return e.forEach(function(e){t+=e.indexOf(" as ")!=-1?", "+e:_md.sql_mask(e,!0)}),t}function n(){var e,t="";if(r.form&&r.form.selection)for(var n in r.form.selection.fields)r.form.selection.fields[n].indexOf(" as ")!=-1&&r.form.selection.fields[n].indexOf("_t_.")==-1&&(e=r.form.selection.fields[n].split(" as "),e[0]=e[0].split("."),e[0].length>1&&(t&&(t+="\n"),t+="left outer join "+e[0][0]+" on "+e[0][0]+".ref = _t_."+e[1]));return t}function a(){var t=" WHERE ("+(s?0:1);return o.sql_selection_where_flds&&(t+=o.sql_selection_where_flds(s)),t+=")",e.selection&&("function"==typeof e.selection||e.selection.forEach(function(e){for(var n in e)if("function"==typeof e[n])t+="\n AND "+e[n](o,n)+" ";else if(r.fields.hasOwnProperty(n))if(e[n]===!0)t+="\n AND _t_."+n+" ";else if(e[n]===!1)t+="\n AND (not _t_."+n+") ";else if("object"==typeof e[n])if($p.utils.is_data_obj(e[n]))t+="\n AND (_t_."+n+" = '"+e[n]+"') ";else{var a,i=Object.keys(e[n]),s=e[n][i[0]],l=r.fields[n];l&&l.type.is_ref&&(a=_md.value_mgr({},n,l.type,!0,s)),t+="not"==i[0]?"\n AND (not _t_."+n+" = '"+s+"') ":"\n AND (_t_."+n+" = '"+s+"') "}else t+="string"==typeof e[n]?"\n AND (_t_."+n+" = '"+e[n]+"') ":"\n AND (_t_."+n+" = "+e[n]+") ";else"is_folder"==n&&r.hierarchical&&r.group_hierarchy})),t}function i(){return""}var s=e.filter||"";s&&s.indexOf("%")==-1&&(s="%"+s+"%");var l;return l=o.sql_selection_list_flds?o.sql_selection_list_flds():("SELECT %2 FROM `"+o.table_name+"` AS _t_ %j %3 %4 LIMIT 300").replace("%2",t()).replace("%j",n()),l.replace("%3",a()).replace("%4",i())}function n(){var t="CREATE TABLE IF NOT EXISTS ",n=!0;if(e&&e.postgres){t+=o.table_name+" (",r.splitted&&(t+="zone integer",n=!1);for(s in r.dimensions)n?(t+=s,n=!1):t+=", "+s,t+=_md.sql_type(o,s,r.dimensions[s].type,!0)+_md.sql_composite(r.dimensions,s,"",!0);for(s in r.resources)t+=", "+s+_md.sql_type(o,s,r.resources[s].type,!0)+_md.sql_composite(r.resources,s,"",!0);for(s in r.attributes)t+=", "+s+_md.sql_type(o,s,r.attributes[s].type,!0)+_md.sql_composite(r.attributes,s,"",!0);t+=", PRIMARY KEY (",n=!0,r.splitted&&(t+="zone",n=!1);for(s in r.dimensions)n?(t+=s,n=!1):t+=", "+s}else{t+="`"+o.table_name+"` (ref CHAR PRIMARY KEY NOT NULL, `_deleted` BOOLEAN";for(s in r.dimensions)t+=_md.sql_mask(s)+_md.sql_type(o,s,r.dimensions[s].type);for(s in r.resources)t+=_md.sql_mask(s)+_md.sql_type(o,s,r.resources[s].type);for(s in r.attributes)t+=_md.sql_mask(s)+_md.sql_type(o,s,r.attributes[s].type)}return t+=")"}function a(){var e="INSERT OR REPLACE INTO `"+o.table_name+"` (",t=[],n=!0;for(s in r.dimensions)n?(e+=s,n=!1):e+=", "+s,t.push(s);for(s in r.resources)e+=", "+s,t.push(s);for(s in r.attributes)e+=", "+s,t.push(s);for(e+=") VALUES (?",s=1;s<t.length;s++)e+=", ?";return e+=")",{sql:e,fields:t}}function i(){var t="SELECT * FROM `"+o.table_name+"` WHERE ",n=!0;e._values=[];for(var a in r.dimensions)n?n=!1:t+=" and ",t+="`"+a+"`=?",e._values.push(e[a]);return n&&(t+="1"),t}var s,o=this,r=o.metadata(),l={},c=e&&e.action?e.action:"create_table";return"create_table"==c?l=n():c in{insert:"",update:"",replace:""}?l[o.table_name]=a():"select"==c?l=i():"select_all"==c?l=i():"delete"==c?l="DELETE FROM `"+o.table_name+"` WHERE ref = ?":"drop"==c?l="DROP TABLE IF EXISTS `"+o.table_name+"`":"get_selection"==c&&(l=t()),l}},get_ref:{value:function(e){if(e instanceof RegisterRow&&(e=e._obj),e.ref)return e.ref;var t="",n=this.metadata().dimensions;for(var a in n)t+=t?"¶":"",t+=n[a].type.is_ref?$p.utils.fix_guid(e[a]):!e[a]&&n[a].type.digits?"0":n[a].date_part?$p.moment(e[a]||$p.utils.blank.date).format($p.moment.defaultFormatUtc):void 0!=e[a]?String(e[a]):"$";return t}},caption_flds:{value:function(e){var t=e.metadata||this.metadata(),n='<column id="%1" width="%2" type="%3" align="%4" sort="%5">%6</column>',a=[],i="";if(t.form&&t.form.selection)a=t.form.selection.cols;else for(var s in t.dimensions)a.push(new Col_struct(s,"*","ro","left","server",t.dimensions[s].synonym));if(e.get_header&&a.length){i="<head>";for(var o in a)i+=n.replace("%1",a[o].id).replace("%2",a[o].width).replace("%3",a[o].type).replace("%4",a[o].align).replace("%5",a[o].sort).replace("%6",a[o].caption);i+="</head>"}return{head:i,acols:a}}},create:{value:function(e){e&&"object"==typeof e||(e={});var t=this.by_ref[e.ref];if(!t){t=new($p[this.obj_constructor()])(e,this);var n=this.handle_event(t,"after_create");if(n===!1)return Promise.resolve(t);if("object"==typeof n&&n.then)return n}return Promise.resolve(t)}}}),InfoRegManager._extend(RegisterManager),InfoRegManager.prototype.slice_first=function(e){},InfoRegManager.prototype.slice_last=function(e){},LogManager._extend(InfoRegManager),AccumRegManager._extend(RegisterManager),CatManager._extend(RefDataManager),CatManager.prototype.by_name=function(e){var t;return this.find_rows({name:e},function(e){return t=e,!1}),t||(t=this.get()),t},CatManager.prototype.by_id=function(e){var t;return this.find_rows({id:e},function(e){return t=e,!1}),t||(t=this.get()),t},CatManager.prototype.path=function(e){var t,n=[];if(t=e instanceof DataObj?e:this.get(e,!1,!0),t&&n.push({ref:t.ref,presentation:t.presentation}),t&&this.metadata().hierarchical)for(;;){if(t=t.parent,t.empty())break;n.push({ref:t.ref,presentation:t.presentation})}return n},ChartOfCharacteristicManager._extend(CatManager),ChartOfAccountManager._extend(CatManager),DocManager._extend(RefDataManager),TaskManager._extend(CatManager),BusinessProcessManager._extend(CatManager),DataObj.prototype._getter=function(e){var t,n=this._metadata.fields[e].type,a=this._obj?this._obj[e]:"";return"type"==e&&"object"==typeof a?a:"ref"==e?a:n.is_ref?n.digits&&"number"==typeof a?a:n.hasOwnProperty("str_len")&&!$p.utils.is_guid(a)?a:(t=_md.value_mgr(this._obj,e,n))?$p.utils.is_data_mgr(t)?t.get(a,!1):$p.utils.fetch_type(a,t):a?(console.log([e,n,this._obj]),null):void 0:n.date_part?$p.utils.fix_date(this._obj[e],!0):n.digits?$p.utils.fix_number(this._obj[e],!n.hasOwnProperty("str_len")):"boolean"==n.types[0]?$p.utils.fix_boolean(this._obj[e]):this._obj[e]||""},DataObj.prototype.__setter=function(e,t){var n,a=this._metadata.fields[e].type;"type"==e&&t.types?this._obj[e]=t:"ref"==e?this._obj[e]=$p.utils.fix_guid(t):a.is_ref?a.digits&&"number"==typeof t||a.hasOwnProperty("str_len")&&"string"==typeof t&&!$p.utils.is_guid(t)?this._obj[e]=t:(this._obj[e]=$p.utils.fix_guid(t),n=_md.value_mgr(this._obj,e,a,!1,t),n?n instanceof EnumManager?"string"==typeof t?this._obj[e]=t:t?"object"==typeof t&&(this._obj[e]=t.ref||t.name||""):this._obj[e]="":t&&t.presentation?(!t.type||t instanceof DataObj||delete t.type,n.create(t)):$p.utils.is_data_mgr(n)||(this._obj[e]=$p.utils.fetch_type(t,n)):"object"!=typeof t&&(this._obj[e]=t)):a.date_part?this._obj[e]=$p.utils.fix_date(t,!0):a.digits?this._obj[e]=$p.utils.fix_number(t,!a.hasOwnProperty("str_len")):"boolean"==a.types[0]?this._obj[e]=$p.utils.fix_boolean(t):this._obj[e]=t},DataObj.prototype.__notify=function(e){this._data._silent||Object.getNotifier(this).notify({type:"update",name:e,oldValue:this._obj[e]})},DataObj.prototype._setter=function(e,t){this._obj[e]!=t&&(this.__notify(e),this.__setter(e,t),this._data._modified=!0)},DataObj.prototype._getter_ts=function(e){return this._ts_(e)},DataObj.prototype._setter_ts=function(e,t){var n=this._ts_(e);n instanceof TabularSection&&Array.isArray(t)&&n.load(t)},DataObj.prototype.__define({valueOf:{value:function(){return this.ref}},toJSON:{value:function(){return this._obj}},toString:{value:function(){return this.presentation}},_metadata:{get:function(){return this._manager.metadata()}},_deleted:{get:function(){return!!this._obj._deleted}},_modified:{get:function(){return!!this._data&&!!this._data._modified}},is_new:{value:function(){return this._data._is_new}},_set_loaded:{value:function(e){return this._manager.push(this,e),this._data._modified=!1,this._data._is_new=!1,this}},mark_deleted:{value:function(e){return this._obj._deleted=!!e,this.save(),this.__notify("_deleted"),this}},ref:{get:function(){return this._obj.ref},set:function(e){this._obj.ref=$p.utils.fix_guid(e)},enumerable:!0,configurable:!0},empty:{value:function(){return $p.utils.is_empty_guid(this._obj.ref)}},load:{value:function(){var e=function(){return e=null,this._data._modified=!1,this}.bind(this);return this.ref==$p.utils.blank.guid?(this instanceof CatObj?this.id="000000000":this.number_doc="000000000",Promise.resolve(this)):this._manager.cachable&&"e1cib"!=this._manager.cachable?$p.wsql.pouch.load_obj(this).then(e):_rest.load_obj(this).then(e)}},unload:{value:function(){var e,t=this._obj;this._manager.unload_obj(this.ref),this._observers&&(this._observers.length=0),this._notis&&(this._notis.length=0);for(e in this._metadata.tabular_sections)this[e].clear(!0);for(e in this)this.hasOwnProperty(e)&&delete this[e];for(e in t)delete t[e];["_ts_","_obj","_data"].forEach(function(e){delete this[e]}.bind(this)),e=t=null}},save:{value:function(e,t,n){if(this instanceof DocObj&&"boolean"==typeof e){var a=this.posted;this.posted=e}var i,s=this._manager.handle_event(this,"before_save"),o=function(){return s===!1?this instanceof DocObj&&"boolean"==typeof a&&this.posted!=a&&(this.posted=a):this._data._modified=!1,i=null,s=null,o=null,this}.bind(this);if(s===!1)return Promise.reject(o());if(s instanceof Promise||"object"==typeof s&&s.then)return s.then(o);if(this._metadata.hierarchical&&!this._obj.parent&&(this._obj.parent=$p.utils.blank.guid), -this instanceof DocObj||this instanceof TaskObj||this instanceof BusinessProcessObj?($p.utils.blank.date==this.date&&(this.date=new Date),this.number_doc||this.new_number_doc()):this.id||this.new_number_doc(),$p.msg&&$p.msg.show_msg)for(var r in this._metadata.fields)if(this._metadata.fields[r].mandatory&&!this._obj[r])return $p.msg.show_msg({title:$p.msg.mandatory_title,type:"alert-error",text:$p.msg.mandatory_field.replace("%1",this._metadata.fields[r].synonym)}),s=!1,Promise.reject(o());return i=this._manager.cachable&&"e1cib"!=this._manager.cachable?$p.wsql.pouch.save_obj:_rest.save_irest,i(this,{post:e,operational:t,attachments:n}).then(function(e){return e._manager.handle_event(e,"after_save")}).then(o)}},get_attachment:{value:function(e){return this._manager.get_attachment(this.ref,e)}},save_attachment:{value:function(e,t,n){return this._manager.save_attachment(this.ref,e,t,n).then(function(t){return this._attachments||(this._attachments={}),this._attachments[e]&&t.stub||(this._attachments[e]=t),t}.bind(this))}},delete_attachment:{value:function(e){return this._manager.delete_attachment(this.ref,e).then(function(t){return this._attachments&&delete this._attachments[e],t}.bind(this))}},_silent:{value:function(e){"boolean"==typeof e?this._data._silent=e:(this._data._silent=!0,setTimeout(function(){this._data._silent=!1}.bind(this)))}},print:{value:function(e,t){return this._manager.print(this,e,t)}}}),CatObj._extend(DataObj),CatObj.prototype.__define("id",{get:function(){return this._obj.id||""},set:function(e){this.__notify("id"),this._obj.id=e},enumerable:!0}),CatObj.prototype.__define("name",{get:function(){return this._obj.name||""},set:function(e){this.__notify("name"),this._obj.name=String(e)},enumerable:!0}),DocObj._extend(DataObj),DocObj.prototype.__define({posted:{get:function(){return this._obj.posted||!1},set:function(e){this.__notify("posted"),this._obj.posted=$p.utils.fix_boolean(e)},enumerable:!0}}),doc_props_date_number(DocObj.prototype),DataProcessorObj._extend(DataObj),TaskObj._extend(CatObj),doc_props_date_number(TaskObj.prototype),BusinessProcessObj._extend(CatObj),doc_props_date_number(BusinessProcessObj.prototype),EnumObj._extend(DataObj),EnumObj.prototype.__define({order:{get:function(){return this._obj.sequence},set:function(e){this._obj.sequence=parseInt(e)},enumerable:!0},name:{get:function(){return this._obj.ref},set:function(e){this._obj.ref=String(e)},enumerable:!0},synonym:{get:function(){return this._obj.synonym||""},set:function(e){this._obj.synonym=String(e)},enumerable:!0},presentation:{get:function(){return this.synonym||this.name}},empty:{value:function(){return!this.ref||"_"==this.ref}}}),RegisterRow._extend(DataObj),RegisterRow.prototype.__define({_metadata:{get:function(){var e=this._manager.metadata();return e.fields||(e.fields={}._mixin(e.dimensions)._mixin(e.resources)._mixin(e.attributes)),e}},ref:{get:function(){return this._manager.get_ref(this)},enumerable:!0},presentation:{get:function(){return this._metadata.obj_presentation||this._metadata.synonym}}}),TabularSection.prototype.toString=function(){return"Табличная часть "+this._owner._manager.class_name+"."+this._name},TabularSection.prototype.get=function(e){return this._obj[e]?this._obj[e]._row:null},TabularSection.prototype.count=function(){return this._obj.length},TabularSection.prototype.clear=function(e){for(var t in this._obj)delete this._obj[t];return this._obj.length=0,e||this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name}),this},TabularSection.prototype.del=function(e,t){var n,a=this._obj;if("undefined"!=typeof e){if("number"==typeof e)n=e;else if(a[e.row-1]._row===e)n=e.row-1;else for(var i in a)if(a[i]._row===e){n=Number(i),delete a[i]._row;break}void 0!=n&&(a.splice(n,1),a.forEach(function(e,t){e.row=t+1}),t||this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name}),this._owner._data._modified=!0)}},TabularSection.prototype.find=function(e,t){var n=$p._find(this._obj,e,t);if(n)return n._row},TabularSection.prototype.find_rows=function(e,t){var n=this,a=t?function(e){return t.call(n,e._row)}:null;return $p._find_rows.call(n,n._obj,e,a)},TabularSection.prototype.swap=function(e,t){var n=this._obj[e];this._obj[e]=this._obj[t],this._obj[t]=n,this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name})},TabularSection.prototype.add=function(e,t){var n=new($p[this._owner._manager.obj_constructor(this._name)])(this);e||(e={});for(var a in n._metadata.fields)n[a]=e[a]||"";return n._obj.row=this._obj.push(n._obj),n._obj.__define("_row",{value:n,enumerable:!1}),t||this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name}),e=null,this._owner._data._modified=!0,n},TabularSection.prototype.each=function(e){var t=this;t._obj.forEach(function(n){return e.call(t,n._row)})},TabularSection.prototype.forEach=TabularSection.prototype.each,TabularSection.prototype.group_by=function(e,t){try{var n=this.aggregate(e,t,"SUM",!0);return this.clear(!0).load(n)}catch(e){}},TabularSection.prototype.sort=function(e){"string"==typeof e&&(e=e.split(","));var t="select * from ? order by ",n=!0;e.forEach(function(e){e=e.trim().replace(/\s{1,}/g," ").split(" "),n?n=!1:t+=", ",t+="`"+e[0]+"`",e[1]&&(t+=" "+e[1])});try{return n=$p.wsql.alasql(t,[this._obj]),this.clear(!0).load(n)}catch(e){$p.record_log(e)}},TabularSection.prototype.aggregate=function(e,t,n,a){if("string"==typeof e&&(e=e.split(",")),"string"==typeof t&&(t=t.split(",")),n||(n="sum"),!e.length&&1==t.length&&"sum"==n)return this._obj.reduce(function(e,n,a,i){return e+n[t[0]]},0);var i,s=!0;t.forEach(function(e){i?i+=", "+n+"(`"+e+"`) `"+e+"`":i="select "+n+"(`"+e+"`) `"+e+"`"}),e.forEach(function(e){i?i+=", `"+e+"`":i="select `"+e+"`"}),i+=" from ? ",e.forEach(function(e){s?(i+="group by ",s=!1):i+=", ",i+="`"+e+"`"});try{return s=$p.wsql.alasql(i,[this._obj]),a||(s=1==t.length?s.length?s[0][t[0]]:0:s.length?s[0]:{}),s}catch(e){$p.record_log(e)}},TabularSection.prototype.load=function(e){var t,n=this;return n.clear(!0),e instanceof TabularSection?t=e._obj:Array.isArray(e)&&(t=e),t&&t.forEach(function(e){n.add(e,!0)}),this._owner._data._silent||Object.getNotifier(n._owner).notify({type:"rows",tabular:n._name}),n},TabularSection.prototype.sync_grid=function(e,t){for(var n={rows:[]},a=[],i=0;i<e.getColumnCount();i++)a.push(e.getColumnId(i));if(e.clearAll(),this.find_rows(t,function(e){var t=[];a.forEach(function(n){$p.utils.is_data_obj(e[n])?t.push(e[n].presentation):t.push(e[n])}),n.rows.push({id:e.row,data:t})}),e.objBox)try{e.parse(n,"json"),e.callEvent("onGridReconstructed",[])}catch(e){}},TabularSection.prototype.toJSON=function(){return this._obj},TabularSectionRow.prototype.__define("_metadata",{get:function(){return this._owner._owner._metadata.tabular_sections[this._owner._name]},enumerable:!1}),TabularSectionRow.prototype.__define("row",{get:function(){return this._obj.row||0},enumerable:!0}),TabularSectionRow.prototype.__define("_clone",{value:function(){return new($p[this._owner._owner._manager.obj_constructor(this._owner._name)])(this._owner)._mixin(this._obj)},enumerable:!1}),TabularSectionRow.prototype._getter=DataObj.prototype._getter,TabularSectionRow.prototype._setter=function(e,t){if(this._obj[e]!=t&&(t||this._obj[e]!=$p.utils.blank.guid)){if(this._owner._owner._data._silent||Object.getNotifier(this._owner._owner).notify({type:"row",row:this,tabular:this._owner._name,name:e,oldValue:this._obj[e]}),this._metadata.fields[e].choice_type){var n;n=2==this._metadata.fields[e].choice_type.path.length?this[this._metadata.fields[e].choice_type.path[1]]:this._owner._owner[this._metadata.fields[e].choice_type.path[0]],n&&n.type&&(t=$p.utils.fetch_type(t,n.type))}DataObj.prototype.__setter.call(this,e,t),this._owner._owner._data._modified=!0}};var _rest=$p.rest=new Rest;DataManager.prototype.__define("rest_name",{get:function(){var e=this.class_name.split("."),t={cat:"Catalog",doc:"Document",ireg:"InformationRegister",areg:"AccumulationRegister",cch:"ChartOfCharacteristicTypes",cacc:"ChartOfAccounts",tsk:"Task",bp:"BusinessProcess"};return t[e[0]]+"_"+_md.syns_1с(e[1])},enumerable:!1}),DataManager.prototype.rest_tree=function(e){var t,n,a=this,i=a.metadata(),s=[];return $p.ajax.default_attr(e,!i.irest&&$p.job_prm.rest?$p.job_prm.rest_url():$p.job_prm.irest_url()),e.url+=this.rest_name+"?allowedOnly=true&$format=json&$top=1000&$select=Ref_Key,DeletionMark,Parent_Key,Description&$filter=IsFolder eq true",$p.ajax.get_ex(e.url,e).then(function(e){return JSON.parse(e.response)}).then(function(e){for(var a=0;a<e.value.length;a++)n=e.value[a],t={ref:n.Ref_Key,_deleted:n.DeletionMark,parent:n.Parent_Key,presentation:n.Description},s.push(t);return $p.iface.data_to_tree(s)})},DataManager.prototype.rest_selection=function(e){if("get_tree"==e.action)return this.rest_tree(e);var t,n,a,i,s,o,r=this,l=r.metadata(),c=[],p=[];return s=function(){var e="$select=Ref_Key,DeletionMark";return l.form&&l.form.selection?l.form.selection.fields.forEach(function(e){c.push(e)}):r instanceof DocManager?(c.push("posted"),c.push("date"),c.push("number_doc")):r instanceof TaskManager?(c.push("name as presentation"),c.push("date"),c.push("number_doc"),c.push("completed")):r instanceof BusinessProcessManager?(c.push("date"),c.push("number_doc"),c.push("started"),c.push("finished")):(l.hierarchical&&l.group_hierarchy?c.push("is_folder"):c.push("0 as is_folder"),l.main_presentation_name?c.push("name as presentation"):l.code_length?c.push("id as presentation"):c.push("'...' as presentation"),l.has_owners&&c.push("owner"),l.code_length&&c.push("id")),c.forEach(function(t){var n;if(t.indexOf(" as ")!=-1)if(n=t.split(" as ")[0].split("."),1==n.length)t=n[0];else{if("_t_"!=n[0])return;t=n[1]}"0"!=t&&(a=_md.syns_1с(t),_md.get(r.class_name,t).type.is_ref&&a.indexOf("_Key")==-1&&_md.get(r.class_name,t).type.types.length&&_md.get(r.class_name,t).type.types[0].indexOf("enm.")==-1&&(a+="_Key"),e+=","+a)}),c.push("ref"),c.push("_deleted"),e}(),$p.ajax.default_attr(e,!l.irest&&$p.job_prm.rest?$p.job_prm.rest_url():$p.job_prm.irest_url()),e.url+=(l.irest&&l.irest.selection?l.irest.selection:this.rest_name)+"?allowedOnly=true&$format=json&$top=1000&"+s,_md.get(r.class_name,"date")&&(e.date_from||e.date_till)&&(e.url+="&$filter="+_rest.filter_date("Date",e.date_from,e.date_till),o=!0),l.hierarchical&&e.parent&&(e.url+=o?" and ":"&$filter=",e.url+="Parent_Key eq guid'"+e.parent+"'",o=!0),l.has_owners&&e.owner&&(e.url+=o?" and ":"&$filter=",e.url+="Owner_Key eq guid'"+e.owner+"'",o=!0),e.filter&&(e.url+=o?" and ":"&$filter=",e.url+="$filter eq '"+e.filter+"'",o=!0),$p.ajax.get_ex(e.url,e).then(function(e){return JSON.parse(e.response)}).then(function(s){for(var o=0;o<s.value.length;o++)n=s.value[o],t={},c.forEach(function(e){var s;if("ref"==e)return void(t[e]=n.Ref_Key);if(e.indexOf(" as ")!=-1?(s=e.split(" as ")[1],e=e.split(" as ")[0].split("."),e=e[e.length-1]):s=e,a=_md.syns_1с(e),i=_md.get(r.class_name,e))if(a.indexOf("_Key")==-1&&i.type.is_ref&&i.type.types.length&&i.type.types[0].indexOf("enm.")==-1&&(a+="_Key"),i.type.date_part)t[s]=$p.moment(n[a]).format($p.moment._masks[i.type.date_part]);else if(i.type.is_ref)if(n[a]&&n[a]!=$p.utils.blank.guid){var o=_md.value_mgr(t,e,i.type,!1,n[a]);o?t[s]=o.get(n[a]).presentation:t[s]=""}else t[s]="";else t[s]=n[a]}),p.push(t);return $p.iface.data_to_grid.call(r,p,e)})},InfoRegManager.prototype.rest_slice_last=function(e){e.period||(e.period=$p.utils.date_add_day(new Date,1));var t=this,n=t.metadata(),a="Period=datetime'"+$p.moment(e.period).format($p.moment._masks.iso)+"'",i="";for(var s in n.dimensions)if(void 0!==e[s]){var o=_md.syns_1с(s),r=n.dimensions[s];o.indexOf("_Key")==-1&&r.type.is_ref&&r.type.types.length&&r.type.types[0].indexOf("enm.")==-1?(o+="_Key",i&&(i+=" and "),i+=o+" eq guid'"+e[s].ref+"'"):(i&&(i+=" and "),i+=r.type.digits?o+" eq "+$p.utils.fix_number(e[s]):r.type.date_part?o+" eq datetime'"+$p.moment(e[s]).format($p.moment._masks.iso)+"'":o+" eq '"+e[s]+"'")}return i&&(a+=",Condition='"+i+"'"),$p.ajax.default_attr(e,$p.job_prm.rest_url()),e.url+=this.rest_name+"/SliceLast(%sl)?allowedOnly=true&$format=json&$top=1000".replace("%sl",a),_rest.ajax_to_data(e,t).then(function(e){return t.load_array(e)})},DataObj.prototype.to_atom=function(e){function t(e){var t=e._metadata.fields,i=e instanceof TabularSectionRow?"\n\t<d:":"\n<d:";for(n in t){if(a=t[n],r=_md.syns_1с(n),l=e[n],l instanceof EnumObj)l=l.empty()?"":l.name;else if(l instanceof DataObj)r.indexOf("_Key")==-1&&(r+="_Key"),l=l.ref;else if(a.type.date_part)l=l.getFullYear()<1e3?"0001-01-01T00:00:00Z":$p.moment(l).format($p.moment.defaultFormatUtc);else if(void 0==l)continue;p+=i+r+">"+l+"</d:"+r+">"}}var n,a,i,s,o,r,l,c='<entry><category term="StandardODATA.%n" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"/>\t\t\t\t\n<title type="text"/><updated>%d</updated><author/><summary/><content type="application/xml">\t\t\t\t\n<m:properties xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">\t\t\t%p\t\t\t\n</m:properties></content></entry>'.replace("%n",this._manager.rest_name).replace("%d",$p.moment().format($p.moment.defaultFormatUtc)),p="\n<d:Ref_Key>"+this.ref+"</d:Ref_Key>\n<d:DeletionMark>"+this._deleted+"</d:DeletionMark>";this instanceof DocObj?(p+="\n<d:Date>"+$p.moment(this.date).format($p.moment.defaultFormatUtc)+"</d:Date>",p+="\n<d:Number>"+this.number_doc+"</d:Number>"):(this._metadata.main_presentation_name&&(p+="\n<d:Description>"+this.name+"</d:Description>"),this._metadata.code_length&&(p+="\n<d:Code>"+this.id+"</d:Code>"),this._metadata.hierarchical&&this._metadata.group_hierarchy&&(p+="\n<d:IsFolder>"+this.is_folder+"</d:IsFolder>")),t(this);for(i in this._metadata.tabular_sections)o=this._metadata.tabular_sections[i],r="StandardODATA."+this._manager.rest_name+"_"+_md.syns_1с(i)+"_RowType",s=this[i],s.count()?(p+="\n<d:"+_md.syns_1с(i)+' m:type="Collection('+r+')">',s.each(function(e){p+='\n\t<d:element m:type="'+r+'">',p+="\n\t<d:LineNumber>"+e.row+"</d:LineNumber>",t(e),p+="\n\t</d:element>"}),p+="\n</d:"+_md.syns_1с(i)+">"):p+="\n<d:"+_md.syns_1с(i)+' m:type="Collection('+r+')" />';return c.replace("%p",p)},DataManager.prototype.__define({pouch_load_array:{value:function(e,t){var n={limit:e.length+1,include_docs:!0,keys:e.map(function(e){return this.class_name+"|"+e}.bind(this))};return t&&(n.attachments=!0,n.binary=!0),this.pouch_db.allDocs(n).then(function(e){return $p.wsql.pouch.load_changes(e,{})})}},pouch_load_view:{value:function(e){var t,n=this,a=[],i={limit:1e3,include_docs:!0,startkey:n.class_name+"|",endkey:n.class_name+"|￿"};return new Promise(function(s,o){function r(l,c){c?c.rows.length?(i.startkey=c.rows[c.rows.length-1].key,i.skip=1,c.rows.forEach(function(e){t=e.doc,key=t._id.split("|"),t.ref=key[1],a.push(t)}),n.load_array(a),a.length=0,n.pouch_db.query(e,i,r)):s():l&&o(l)}n.pouch_db.query(e,i,r)})}},pouch_db:{get:function(){return this.cachable.indexOf("_remote")!=-1?$p.wsql.pouch.remote[this.cachable.replace("_remote","")]:$p.wsql.pouch.local[this.cachable]||$p.wsql.pouch.remote[this.cachable]}},pouch_find_rows:{value:function(e){var t,n,a,i,s,o,r=this,l=[],c=0,p=0,d=0,u={limit:100,include_docs:!0,startkey:r.class_name+"|",endkey:r.class_name+"|￿"};return e&&(e._top?(s=e._top,delete e._top):s=300,e._raw&&(n=e._raw,delete e._raw),e._total_count&&(i=e._total_count,delete e._total_count),e._view&&(a=e._view,delete e._view),e._key&&("des"==e._key._order_by?(u.startkey=e._key.endkey||e._key+"￿",u.endkey=e._key.startkey||e._key,u.descending=!0):(u.startkey=e._key.startkey||e._key,u.endkey=e._key.endkey||e._key+"￿")),"number"==typeof e._skip&&(p=e._skip,delete e._skip),e._attachments&&(u.attachments=!0,u.binary=!0,delete e._attachments)),i&&(o=!0,i=0,Object.keys(e).length<=1&&e._key&&e._key.hasOwnProperty("_search"))?(u.include_docs=!1,u.limit=1e5,r.pouch_db.query(a,u).then(function(t){return t.rows.forEach(function(t){if(!e._key._search||t.key[t.key.length-1].toLowerCase().indexOf(e._key._search)!=-1){if(i++,p&&(d++,d<p))return;if(s&&(c++,c>s))return;l.push(t.id)}}),delete u.startkey,delete u.endkey,u.descending&&delete u.descending,u.keys=l,u.include_docs=!0,r.pouch_db.allDocs(u)}).then(function(e){return{rows:e.rows.map(function(e){var t=e.doc;return t.ref=t._id.split("|")[1],n||(delete t._id,delete t._rev),t}),_total_count:i}})):new Promise(function(f,m){function h(a,h){h?h.rows.length?(u.startkey=h.rows[h.rows.length-1].key,u.skip=1,h.rows.forEach(function(a){t=a.doc,key=t._id.split("|"),t.ref=key[1],n||(delete t._id,delete t._rev),$p._selection.call(r,t,e)&&(o&&i++,p&&(d++,d<p)||s&&(c++,c>s)||l.push(t))}),s&&c>s&&!o?f(n?l:r.load_array(l)):_()):f(o?{rows:n?l:r.load_array(l),_total_count:i}:n?l:r.load_array(l)):a&&m(a)}function _(){a?r.pouch_db.query(a,u,h):r.pouch_db.allDocs(u,h)}_()})}},pouch_selection:{value:function(e){var t,n,a,i=this,s=e.metadata||i.metadata(),o=["ref","_deleted"],r={_raw:!0,_total_count:!0,_top:e.count||30,_skip:e.start||0},l=[];if(s.form&&s.form.selection?s.form.selection.fields.forEach(function(e){o.push(e)}):i instanceof DocManager?(o.push("posted"),o.push("date"),o.push("number_doc")):i instanceof TaskManager?(o.push("name as presentation"),o.push("date"),o.push("number_doc"),o.push("completed")):i instanceof BusinessProcessManager?(o.push("date"),o.push("number_doc"),o.push("started"),o.push("finished")):(s.hierarchical&&s.group_hierarchy?o.push("is_folder"):o.push("0 as is_folder"),s.main_presentation_name?o.push("name as presentation"):s.code_length?o.push("id as presentation"):o.push("'...' as presentation"),s.has_owners&&o.push("owner"),s.code_length&&o.push("id")),_md.get(i.class_name,"date")&&(e.date_from||e.date_till)&&(e.date_from||(e.date_from=new Date("2015-01-01")),e.date_till||(e.date_till=$p.utils.date_add_day(new Date,1)),r.date={between:[e.date_from,e.date_till]}),s.hierarchical&&e.parent&&(r.parent=e.parent),e.selection)if(Array.isArray(e.selection))e.selection.forEach(function(e){for(a in e)"_"==a[0]&&"_view"!=a&&"_key"!=a||(r[a]=e[a])});else for(a in e.selection)"_"==a[0]&&"_view"!=a&&"_key"!=a||(r[a]=e.selection[a]);return r._key&&r._key._drop_date&&r.date&&delete r.date,!e.filter||r._key&&r._key._search||(1==s.input_by_string.length?r[s.input_by_string]={like:e.filter}:(r.or=[],s.input_by_string.forEach(function(t){var n={};n[t]={like:e.filter},r.or.push(n)}))),r._key&&r._key._order_by&&(r._key._order_by=e.direction),i.pouch_find_rows(r).then(function(s){return s.hasOwnProperty("_total_count")&&s.hasOwnProperty("rows")&&(e._total_count=s._total_count,s=s.rows),s.forEach(function(e){t={},o.forEach(function(s){if("ref"==s)return void(t[s]=e[s]);if(s.indexOf(" as ")!=-1?(a=s.split(" as ")[1],s=s.split(" as ")[0].split("."),s=s[s.length-1]):a=s,n=_md.get(i.class_name,s))if(n.type.date_part)t[a]=$p.moment(e[s]).format($p.moment._masks[n.type.date_part]);else if(n.type.is_ref)if(e[s]&&e[s]!=$p.utils.blank.guid){var o=_md.value_mgr(t,s,n.type,!1,e[s]);o?t[a]=o.get(e[s]).presentation:t[a]=""}else t[a]="";else"number"==typeof e[s]&&n.type.fraction_figits?t[a]=e[s].toFixed(n.type.fraction_figits):t[a]=e[s]}),l.push(t)}),$p.iface.data_to_grid.call(i,l,e)}).catch($p.record_log)}},pouch_tree:{value:function(e){return this.pouch_find_rows({is_folder:!0,_raw:!0,_top:e.count||300,_skip:e.start||0}).then(function(e){return e.sort(function(e,t){return e.parent==$p.utils.blank.guid&&t.parent!=$p.utils.blank.guid?-1:t.parent==$p.utils.blank.guid&&e.parent!=$p.utils.blank.guid?1:e.name<t.name?-1:e.name>t.name?1:0}),e.map(function(e){return{ref:e.ref,parent:e.parent,presentation:e.name}})}).then($p.iface.data_to_tree)}},save_attachment:{value:function(e,t,n,a){a||(a={type:"text/plain"}),n instanceof Blob||a.indexOf("text")!=-1||(n=new Blob([n],{type:a}));var i,s=this.pouch_db;return e=this.class_name+"|"+$p.utils.fix_guid(e),s.get(e).then(function(e){e&&(i=e._rev)}).catch(function(e){if(404!=e.status)throw e}).then(function(){return s.putAttachment(e,t,i,n,a)})}},get_attachment:{value:function(e,t){return this.pouch_db.getAttachment(this.class_name+"|"+$p.utils.fix_guid(e),t)}},delete_attachment:{value:function(e,t){var n,a=this.pouch_db;return e=this.class_name+"|"+$p.utils.fix_guid(e),a.get(e).then(function(e){e&&(n=e._rev)}).catch(function(e){if(404!=e.status)throw e}).then(function(){return a.removeAttachment(e,t,n)})}}}),DataObj.prototype.__define({new_number_doc:{value:function(e){if(this._metadata.code_length){e||(e=($p.current_acl&&$p.current_acl.prefix||"")+(this.organization&&this.organization.prefix?this.organization.prefix:$p.wsql.get_user_param("zone")+"-"));var t=this,n="",a=this.date instanceof Date?this.date.getFullYear():0,i=this._metadata.code_length-e.length;return"ram"==this._manager.cachable?Promise.resolve(this.new_cat_id(e)):t._manager.pouch_db.query("doc/number_doc",{limit:1,include_docs:!1,startkey:[t._manager.class_name,a,e+"￿"],endkey:[t._manager.class_name,a,e],descending:!0}).then(function(a){if(a.rows.length){for(var s=a.rows[0].key[2],o=s.length-1;o>0&&!isNaN(parseInt(s[o]));o--)n=s[o]+n;n=(parseInt(n||0)+1).toFixed(0)}else n="1";for(;n.length<i;)n="0"+n;return t instanceof DocObj||t instanceof TaskObj||t instanceof BusinessProcessObj?t.number_doc=e+n:t.id=e+n,t})}}},new_cat_id:{value:function(e){e||(e=($p.current_acl&&$p.current_acl.prefix||"")+(this.organization&&this.organization.prefix?this.organization.prefix:$p.wsql.get_user_param("zone")+"-"));var t=this._metadata.code_length-e.length,n=this instanceof DocObj||this instanceof TaskObj||this instanceof BusinessProcessObj?"number_doc":"id",a="",i=$p.wsql.alasql("select top 1 "+n+" as id from ? where "+n+" like '"+e+"%' order by "+n+" desc",[this._manager.alatable]);if(i.length){for(var s=i[0].id||"",o=s.length-1;o>0&&!isNaN(parseInt(s[o]));o--)a=s[o]+a;a=(parseInt(a||0)+1).toFixed(0)}else a="1";for(;a.length<t;)a="0"+a;return this[n]=e+a,this}}}),$p.iface.OBtnAuthSync=function(){function e(){$p.wsql.pouch.authorized?dhtmlx.confirm({title:$p.msg.log_out_title,text:$p.msg.logged_in+$p.wsql.pouch.authorized+$p.msg.log_out_break,cancel:$p.msg.cancel,callback:function(e){e&&$p.wsql.pouch.log_out()}}):$p.iface.frm_auth({modal_dialog:!0})}function t(e){e&&a?clearTimeout(a):i.forEach(function(t){e?t.buttons.sync.innerHTML='<i class="fa fa-refresh fa-spin md-fa-lg"></i>':$p.wsql.pouch.authorized?t.buttons.sync.innerHTML='<i class="fa fa-refresh md-fa-lg"></i>':t.buttons.sync.innerHTML='<i class="fa fa-ban md-fa-lg"></i>'}),a=e?setTimeout(t,3e3):0}function n(){i.forEach(function(e){$p.wsql.pouch.authorized?(e.buttons.auth.title="Отключиться от сервера",e.buttons.auth.innerHTML='<span class="span_user">'+$p.wsql.pouch.authorized+"</span>",e.buttons.sync.title="Синхронизация выполняется...",e.buttons.sync.innerHTML='<i class="fa fa-refresh md-fa-lg"></i>'):(e.buttons.auth.title="Войти на сервер и включить синхронизацию данных",e.buttons.auth.innerHTML=' <i class="fa fa-sign-in md-fa-lg"></i><span class="span_user">Вход...</span>',e.buttons.sync.title="Синхронизация не выполняется - пользователь не авторизован на сервере",e.buttons.sync.innerHTML='<i class="fa fa-ban md-fa-lg"></i>')})}var a,i=[];this.bind=function(t){return t.buttons.auth.onclick=e,t.buttons.sync.onclick=null,i.push(t),setTimeout(n),t},$p.on({pouch_load_data_start:function(e){$p.iface.sync||$p.iface.wnd_sync(),$p.iface.sync.create($p.eve.stepper),$p.eve.stepper.frm_sync.setItemValue("text_bottom","Читаем справочники"),e.hasOwnProperty("local_rows")&&e.local_rows<10?($p.eve.stepper.wnd_sync.setText("Первый запуск - подготовка данных"),$p.eve.stepper.frm_sync.setItemValue("text_processed","Загрузка начального образа")):($p.eve.stepper.wnd_sync.setText("Загрузка данных из IndexedDB"),$p.eve.stepper.frm_sync.setItemValue("text_processed","Извлечение начального образа")),t(!0)},pouch_load_data_page:function(e){if(t(!0),$p.eve.stepper.wnd_sync){var n=e.docs_written||e.page*e.limit;$p.eve.stepper.frm_sync.setItemValue("text_current","Обработано элементов: "+n+" из "+e.total_rows),$p.eve.stepper.frm_sync.setItemValue("text_bottom","Текущий запрос: "+e.page+" ("+(100*n/e.total_rows).toFixed(0)+"%)")}},pouch_change:function(e,n){t(!0)},pouch_load_data_loaded:function(e){$p.eve.stepper.wnd_sync&&(e.docs_written?$p.iface.sync.close():$p.iface.sync.close())},pouch_load_data_error:function(e){t(),$p.eve.stepper.wnd_sync&&$p.iface.sync.close()},log_in:function(e){n()},log_out:function(){n()}})};var eXcell_proto=new eXcell;eXcell_proto.input_keydown=function(e,t){function n(e){t.source.on_select&&t.source.on_select.call(t.source,e)}if(8===e.keyCode||46===e.keyCode)t.setValue(""),t.grid.editStop(),t.source.on_select&&t.source.on_select.call(t.source,"");else if(9===e.keyCode||13===e.keyCode)t.grid.editStop();else if(115===e.keyCode)t.cell.firstChild.childNodes[1].onclick(e);else if(113===e.keyCode)if(t.source.tabular_section){if(t.mgr=_md.value_mgr(t.source.row,t.source.col,t.source.row._metadata.fields[t.source.col].type),t.mgr){var a=t.source.row[t.source.col];t.mgr.form_obj(t.source.wnd,{o:a,on_select:n})}}else if(1==t.fpath.length&&(t.mgr=_md.value_mgr(t.source.o._obj,t.fpath[0],t.source.o._metadata.fields[t.fpath[0]].type),t.mgr)){var a=t.source.o[t.fpath[0]];t.mgr.form_obj(t.source.wnd,{o:a,on_select:n})}return $p.iface.cancel_bubble(e)},eXcell_ocombo.prototype=eXcell_proto,window.eXcell_ocombo=eXcell_ocombo,window.eXcell_ref=eXcell_ocombo,window.eXcell_refc=eXcell_ocombo,eXcell_pwd.prototype=eXcell_proto,window.eXcell_pwd=eXcell_pwd,dhtmlXCalendarObject.prototype._dateToStr=function(e,t){return e instanceof Date&&e.getFullYear()<1e3?"":window.dhx4.date2str(e,t||this._dateFormat,this._dateStrings())},eXcell_dhxCalendar.prototype.edit=function(){var e=this.grid.getPosition(this.cell);this.grid._grid_calendarA._show(!1,!1),this.grid._grid_calendarA.setPosition(e[0],e[1]+this.cell.offsetHeight),this.grid._grid_calendarA._last_operation_calendar=!1,this.grid.callEvent("onCalendarShow",[this.grid._grid_calendarA,this.cell.parentNode.idd,this.cell._cellIndex]),this.cell._cediton=!0,this.val=this.cell.val,this.val instanceof Date&&this.val.getFullYear()<1e3&&(this.val=new Date),this._val=this.cell.innerHTML;var t=this.grid._grid_calendarA.draw;this.grid._grid_calendarA.draw=function(){},this.grid._grid_calendarA.setDateFormat(this.grid._dtmask||"%d.%m.%Y"),this.grid._grid_calendarA.setDate(this.val||new Date),this.grid._grid_calendarA.draw=t},eXcell_dhxCalendar.prototype.setCValue=function(e,t){this.cell.innerHTML=e instanceof Date?this.grid._grid_calendarA._dateToStr(e):e,this.grid._grid_calendarA.getFormatedDate(this.grid._dtmask||"%d/%m/%Y",e).toString(),this.grid.callEvent("onCellChanged",[this.cell.parentNode.idd,this.cell._cellIndex,arguments.length>1?t:e])},function(){function e(e,t,n,a){if(n.indexOf("odata/standard.odata")!=-1||n.indexOf("/hs/rest")!=-1){var i,s;$p.ajax.authorized?(i=$p.ajax.username,s=$p.aes.Ctr.decrypt($p.ajax.password)):$p.job_prm.guest_name?(i=$p.job_prm.guest_name,s=$p.aes.Ctr.decrypt($p.job_prm.guest_pwd)):(i=$p.wsql.get_user_param("user_name"),s=$p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd"))),e.open(t,n,a,i,s),e.withCredentials=!0,e.setRequestHeader("Authorization","Basic "+btoa(unescape(encodeURIComponent(i+":"+s))))}else e.open(t,n,a)}dhx4.ajax._call=function(t,n,a,i,s,o,r){var l=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),c=null!=navigator.userAgent.match(/AppleWebKit/)&&null!=navigator.userAgent.match(/Qt/)&&null!=navigator.userAgent.match(/Safari/);if(1==i&&(l.onreadystatechange=function(){if(4==l.readyState||1==c&&3==l.readyState){if((200!=l.status||""==l.responseText)&&!dhx4.callEvent("onAjaxError",[{xmlDoc:l,filePath:n,async:i}]))return;window.setTimeout(function(){"function"==typeof s&&s.apply(window,[{xmlDoc:l,filePath:n,async:i}]),null!=o&&("undefined"!=typeof o.postData?dhx4.ajax.postLong(o.url,o.postData,s):dhx4.ajax.getLong(o.url,s)),s=null,l=null},1)}}),"GET"==t&&(n+=this._dhxr(n)),l.open(t,n,i),e(l,t,n,i),null!=r)for(var p in r)l.setRequestHeader(p,r[p]);else"POST"==t||"PUT"==t||"DELETE"==t?l.setRequestHeader("Content-Type","application/x-www-form-urlencoded"):"GET"==t&&(a=null);return l.setRequestHeader("X-Requested-With","XMLHttpRequest"),l.send(a),1!=i&&(4==l.readyState||1==c&&3==l.readyState)&&(200==l.status&&""!=l.responseText||dhx4.callEvent("onAjaxError",[{xmlDoc:l,filePath:n,async:i}])),{xmlDoc:l,filePath:n,async:i}},dhtmlx.ajax.prototype.send=function(t,n,a){var i=this.getXHR();if("function"==typeof a&&(a=[a]),"object"==typeof n){var s=[];for(var o in n){var r=n[o];null!==r&&r!==dhtmlx.undefined||(r=""),s.push(o+"="+encodeURIComponent(r))}n=s.join("&")}n&&!this.post&&(t=t+(t.indexOf("?")!=-1?"&":"?")+n,n=null),e(i,this.post?"POST":"GET",t,!this._sync),this.post&&i.setRequestHeader("Content-type","application/x-www-form-urlencoded");var l=this;return i.onreadystatechange=function(){if(!i.readyState||4==i.readyState){if(a&&l)for(var e=0;e<a.length;e++)a[e]&&a[e].call(l.master||l,i.responseText,i.responseXML,i);l.master=null,a=l=null}},i.send(n||null),i}}(),dhtmlXCellObject.prototype.is_visible=function(){var e=this.cell.getBoundingClientRect();return e.right>0&&e.bottom>0},$p.iface.data_to_grid=function(e,t){function n(e){var t;return t=e.hasOwnProperty("posted")?e.posted?"cell_doc_posted":"cell_doc":e.is_folder?"cell_ref_folder":"cell_ref_elm",e._deleted&&(t+="_deleted"),t}function a(e){return e instanceof Date?e.getHours()||e.getMinutes()?$p.moment(e).format($p.moment._masks.date_time):$p.moment(e).format($p.moment._masks.date):"number"==typeof e?e:$p.iface.normalize_xml(e||"")}if(this.data_to_grid)return this.data_to_grid(e,t);var i="<?xml version='1.0' encoding='UTF-8'?><rows total_count='%1' pos='%2' set_parent='%3'>".replace("%1",t._total_count||e.length).replace("%2",t.start).replace("%3",t.set_parent||""),s=this.caption_flds(t);return i+=s.head,e.forEach(function(e){i+='<row id="'+e.ref+'"><cell class="'+n(e)+'">'+a(e[s.acols[0].id])+"</cell>";for(var t=1;t<s.acols.length;t++)i+="<cell>"+a(e[s.acols[t].id])+"</cell>";i+="</row>"}),i+"</rows>"},$p.iface.data_to_tree=function(e){function t(n,a){var i={id:a.ref,text:a.presentation,items:[]};n.push(i),$p._find_rows(e,{parent:a.ref},function(e){t(i.items,e)}),i.items.length||delete i.items}var n=[{id:$p.utils.blank.guid,text:"..."}];return $p._find_rows(e,{parent:$p.utils.blank.guid},function(e){t(n,e)}),n},$p.iface.ODropdownList=ODropdownList,dhtmlXCellObject.prototype.attachDynTree=function(e,t,n){this.setCollapsedText&&this.setCollapsedText("Дерево"),t||(t={is_folder:!0});var a=this.attachTreeView();return a.__define({filter:{get:function(){},set:function(e){t=e},enumerable:!1,configurable:!1}}),setTimeout(function(){e.sync_grid({action:"get_tree",filter:t},a).then(function(e){n&&n(e)})}),a},OCombo._extend(dhtmlXCombo),$p.iface.OCombo=OCombo,$p.iface.select_from_list=function(e,t){return new Promise(function(n,a){function i(e){"cancel"!=e&&(s=c.getSelectedRowId()),l.close()}Array.isArray(e)&&e.length?1==e.length&&n(e[0]):n(void 0);var s,o,r={name:"wnd_select_from_list",wnd:{id:"wnd_select_from_list",width:300,height:300,modal:!0,center:!0,caption:$p.msg.select_from_list,allow_close:!0,on_close:function(){return s&&n(e[parseInt(s)-1]),!0}}},l=$p.iface.dat_blank(null,r.wnd),c=l.attachGrid(),p=l.attachToolbar({items:[{id:"select",type:"button",text:$p.msg.select_from_list},{id:"cancel",type:"button",text:"Отмена"}],onClick:i});c.setIconsPath(dhtmlx.image_path),c.setImagePath(dhtmlx.image_path),c.setHeader($p.msg.value),c.setColTypes("ro"),c.enableAutoWidth(!0,1200,600),c.attachEvent("onRowDblClicked",i),c.enableMultiselect(!!t),c.setNoHeader(!0),c.init(),p.addSpacer("select"),l.hideHeader(),l.cell.offsetParent.querySelector(".dhxwin_brd").style.border="none",e.forEach(function(e,t){ -var n;n="object"==typeof e?e.presentation||e.text||e.toString():e.toString(),c.addRow(1+t,n),e.selected&&(o=1+t)}),o&&c.selectRowById(o)})},$p.iface.ODateRangePicker=ODateRangePicker,dhtmlXCellObject.prototype.attachHeadFields=function(e){function t(e){if(a)u.entBox&&!u.entBox.parentElement?setTimeout(u.destructor):e.forEach(function(e){"unload"==e.type?d&&d.close?d.close():u.destructor():u.forEachRow(function(t){t==e.name&&u.cells(t,1).setValue(a[e.name])})});else{var i=[];e.forEach(function(e){i.indexOf[e.object]==-1&&(i.push(e.object),Object.unobserve(e.object,t),c&&c instanceof TabularSection&&Object.unobserve(e.object,n))}),i=null}}function n(t){var n;t.forEach(function(t){!n&&u.clearAll&&l==t.tabular&&(n=!0,u.clearAll(),u.parse(o.get_property_grid_xml(i,a,{title:e.ts_title,ts:l,selection:r,metadata:s}),function(){},"xml"))})}var a,i,s,o,r,l,c,p,d=this,u=d.attachGrid(),f=u.destructor;return new dhtmlXPropertyGrid(u),u.setInitWidthsP("40,60"),u.setDateFormat("%d.%m.%Y %H:%i"),u.init(),u.setSizes(),u.attachEvent("onPropertyChanged",function(e,t,n){if(e||u&&u.getSelectedRowId())return p.on_select(t)}),u.attachEvent("onCheckbox",function(e,t,n){return void 0!=a[e]?p.on_select(n,{obj:a,field:e}):e.split("|").length>1?p.on_select(n,u.get_cell_field(e)):void 0}),u.attachEvent("onKeyPress",function(e,t,n){switch(e){case 13:case 9:u.editStop&&u.editStop();break;case 46:}}),e.read_only&&u.setEditable(!1),u.__define({selection:{get:function(){return r},set:function(e){r=e,this.reload()}},reload:{value:function(){n([{tabular:l}])}},get_cell_field:{value:function(e){if(a){var t={row_id:e||u.getSelectedRowId()},n=t.row_id.split("|");if(n.length<2)return{obj:a,field:n[0]}._mixin(p);var i;return r?a[n[0]].find_rows(r,function(e){if(e.property==n[1]||e.param==n[1]||e.Свойство==n[1]||e.Параметр==n[1])return i=e,!1}):i=a[n[0]].find(n[1]),i?(t.obj=i,i["Значение"]?(t.field="Значение",t.property=i.Свойство||i.Параметр):(t.field="value",t.property=i.property||i.param),t._mixin(p)):void 0}},enumerable:!1},_obj:{get:function(){return a}},_owner_cell:{get:function(){return d}},destructor:{value:function(){a&&Object.unobserve(a,t),c&&c instanceof TabularSection&&Object.unobserve(c,n),a=null,c=null,s=null,o=null,p=null,f.call(u)}},attach:{value:function(e){a&&Object.unobserve(a,t),c&&c instanceof TabularSection&&Object.unobserve(a,n),e.oxml&&(i=e.oxml),e.selection&&(r=e.selection),a=e.obj,s=e.metadata||a._metadata.fields,o=a._manager,l=e.ts||"",c=l?a[l]:a.extra_fields||a["ДополнительныеРеквизиты"],c&&!l&&(l=a.extra_fields?"extra_fields":"ДополнительныеРеквизиты"),p={on_select:function(e,t){if(t||(t=u.get_cell_field()),t){var n=o.handle_event(a,"value_change",{field:t.field,value:e,tabular_section:t.row_id?l:"",grid:u,cell:u.cells(t.row_id||t.field,1),wnd:p.pwnd});return"boolean"!=typeof n&&(t.obj[t.field]=e,n=!0),n}},pwnd:e.pwnd||d},Object.observe(a,t,["update","unload"]),c&&c instanceof TabularSection&&Object.observe(a,n,["row","rows"]),l&&!e.ts_title&&(e.ts_title=a._metadata.tabular_sections[l].synonym),n([{tabular:l}])}}}),e&&u.attach(e),u},dhtmlXGridObject.prototype.get_cell_value=function(){var e=this.get_cell_field();if(e&&e.obj)return e.obj[e.field]},dhtmlXCellObject.prototype.attachTabular=function(e){function t(e){var t=m.getSelectedRowId();return t&&!isNaN(Number(t))?Number(t)-1:void(e||$p.msg.show_msg({type:"alert-warning",text:$p.msg.no_selected_row.replace("%1",o._metadata.tabular_sections[r].synonym||r),title:(o._metadata.obj_presentation||o._metadata.synonym)+": "+o.presentation}))}function n(e,t,n,a,i){if(2!=e||a==i)return!0;var s=m.get_cell_field(),l=c.handle_event(o,"value_change",{field:s.field,value:a,tabular_section:r,grid:m,row:s.obj,cell:t&&n?m.cells(t,n):m.getSelectedCellIndex()>=0?m.cells():null,wnd:g.pwnd});return"boolean"!=typeof l&&(s.obj[s.field]=a,l=!0),l}function a(e){m.clearAll&&e.some(function(e){if("rows"==e.type&&e.tabular==r)return l.sync_grid(m,f),!0})}function i(e){if(e.length>20)try{l.sync_grid(m,f)}catch(e){}else e.forEach(function(e){r==e.tabular&&(e.row&&m.getSelectedRowId()==e.row.row?void 0!=m.getColIndexById(e.name)&&m.cells(e.row.row,m.getColIndexById(e.name)).setCValue($p.utils.is_data_obj(e.row[e.name])?e.row[e.name].presentation:e.row[e.name]):l.sync_grid(m,f))})}function s(e){if(e.clipboardData.types.indexOf("text/plain")!=-1)try{$p.eve.callEvent("tabular_paste",[{obj:o,grid:m,tsname:r,e:e,data:e.clipboardData.getData("text/plain")}])}catch(e){return}}var o=e.obj,r=e.ts,l=o[r],c=o._manager,p=e.metadata||c.metadata().tabular_sections[r].fields,d=this,u=e.ts_captions||{},f=e.selection;if(e.ts_captions||_md.ts_captions(c.class_name,r,u)){var m=this.attachGrid(),h=this.attachToolbar(),_=m.destructor,g={on_select:function(e){n(2,null,null,e)},pwnd:e.pwnd||d,is_tabular:!0};return m.setDateFormat("%d.%m.%Y %H:%i"),m.enableAccessKeyMap(),m._add_row=function(){if(!e.read_only){var t;if(f)for(var n in f)p[n]&&("object"!=typeof f[n]||$p.is_data_obj(f[n]))&&(t||(t={}),t[n]=f[n]);var a=l.add(t);if(c.handle_event(o,"add_row",{tabular_section:r,grid:m,row:a,wnd:g.pwnd})===!1)return;setTimeout(function(){m.selectRowById(a.row)},100)}},m._del_row=function(){if(!e.read_only){var n=t();if(void 0!=n){if(c.handle_event(o,"del_row",{tabular_section:r,grid:m,row:n,wnd:g.pwnd})===!1)return;l.del(n),setTimeout(function(){m.selectRowById(n<l.count()?n+1:n)},100)}}},h.setIconsPath(dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()),h.loadStruct(e.toolbar_struct||$p.injected_data["toolbar_add_del.xml"],function(){this.attachEvent("onclick",function(e){switch(e){case"btn_add":m._add_row();break;case"btn_delete":m._del_row()}})}),m.setIconsPath(dhtmlx.image_path),m.setImagePath(dhtmlx.image_path),m.setHeader(u.headers),u.min_widths&&m.setInitWidths(u.widths),u.min_widths&&m.setColumnMinWidth(u.min_widths),u.aligns&&m.setColAlign(u.aligns),m.setColSorting(u.sortings),m.setColTypes(u.types),m.setColumnIds(u.fields.join(",")),m.enableAutoWidth(!0,1200,600),m.enableEditTabOnly(!0),m.init(),e.read_only&&(m.setEditable(!1),h.forEachItem(function(e){["btn_add","btn_delete"].indexOf(e)!=-1&&h.disableItem(e)})),m.__define({selection:{get:function(){return f},set:function(e){f=e,a([{tabular:r,type:"rows"}])}},destructor:{value:function(){o&&(Object.unobserve(o,i),Object.unobserve(o,a)),o=null,l=null,p=null,c=null,g=null,d.detachToolbar(),m.entBox.removeEventListener("paste",s),_.call(m)}},get_cell_field:{value:function(){if(l){var e,n,a=t(!0),i=m.getSelectedCellIndex();if(void 0!=a?e=l.get(a):m._last&&(e=l.get(m._last.row)),i>=0?n=m.getColumnId(i):m._last&&(n=m.getColumnId(m._last.cindex)),e&&n)return{obj:e,field:n,metadata:p[n]}._mixin(g)}}},refresh_row:{value:function(e){m.selectRowById(e.row),m.forEachCell(e.row,function(t,n){var a=e[m.getColumnId(n)];t.setCValue($p.utils.is_data_obj(a)?a.presentation:a)})}}}),m.attachEvent("onEditCell",n),m.attachEvent("onRowSelect",function(e,t){l&&(m._last={row:e-1,cindex:t})}),a([{tabular:r,type:"rows"}]),Object.observe(o,i,["row"]),Object.observe(o,a,["rows"]),m.entBox.addEventListener("paste",s),m}},$p.iface.Toolbar_filter=function(e){function t(){i&&clearTimeout(i),i=setTimeout(function(){i&&a.call_event()},500)}function n(e,t){"min"==t?a.сalendar.setSensitiveRange(e.value,null):a.сalendar.setSensitiveRange(null,e.value)}var a=this,i=0,s="desktop"==$p.job_prm.device_type?300:120,o={};e.pos||(e.pos=6),a.__define({custom_selection:{get:function(){return o},enumerable:!1,configurable:!1},toolbar:{get:function(){return e.toolbar},enumerable:!1,configurable:!1},call_event:{value:function(){i&&(clearTimeout(i),i=0),e.onchange.call(a,a.get_filter())}}}),a.toolbar.addText("div_filter",e.pos,""),a.div=a.toolbar.objPull[a.toolbar.idPrefix+"div_filter"],e.pos++,(e.manager instanceof DocManager||e.manager instanceof BusinessProcessManager||e.manager instanceof TaskManager||e.period)&&(s="desktop"==$p.job_prm.device_type?180:120,a.toolbar.addInput("input_date_from",e.pos,"","desktop"==$p.job_prm.device_type?80:72),e.pos++,a.toolbar.addText("lbl_date_till",e.pos,"-"),e.pos++,a.toolbar.addInput("input_date_till",e.pos,"","desktop"==$p.job_prm.device_type?80:72),e.pos++,a.input_date_from=a.toolbar.getInput("input_date_from"),a.input_date_from.onclick=function(){n(a.input_date_till,"max")},a.input_date_till=a.toolbar.getInput("input_date_till"),a.input_date_till.onclick=function(){n(a.input_date_from,"min")},a.сalendar=new dhtmlXCalendarObject([a.input_date_from,a.input_date_till]),a.сalendar.attachEvent("onclick",a.call_event),e.date_from||(e.date_from=new Date((new Date).getFullYear().toFixed()+"-01-01")),e.date_till||(e.date_till=$p.utils.date_add_day(new Date,1)),a.input_date_from.value=$p.moment(e.date_from).format("L"),a.input_date_till.value=$p.moment(e.date_till).format("L"),"doc"!=e.manager.cachable||e.custom_selection||(o._view={get value(){return"doc/by_date"}},o._key={get value(){var t=a.get_filter(!0);return{startkey:[e.manager.class_name,t.date_from.getFullYear(),t.date_from.getMonth()+1,t.date_from.getDate()],endkey:[e.manager.class_name,t.date_till.getFullYear(),t.date_till.getMonth()+1,t.date_till.getDate()],_drop_date:!0,_order_by:!0,_search:t.filter.toLowerCase()}}})),e.hide_filter?a.input_date_till?a.toolbar.addSpacer("input_date_till"):a.toolbar.addSpacer("div_filter"):(a.toolbar.addSeparator("filter_sep",e.pos),e.pos++,a.toolbar.addInput("input_filter",e.pos,"",s),a.input_filter=a.toolbar.getInput("input_filter"),a.input_filter.onchange=a.call_event,a.input_filter.onclick=function(){var e=a.input_filter.value;setTimeout(function(){e!=a.input_filter.value&&a.call_event()})},a.input_filter.onkeydown=t,a.input_filter.type="search",a.input_filter.setAttribute("placeholder","Фильтр"),a.toolbar.addSpacer("input_filter"))},$p.iface.Toolbar_filter.prototype.__define({get_filter:{value:function(e){var t,n,a={date_from:this.input_date_from?$p.utils.date_add_day(dhx4.str2date(this.input_date_from.value),0,!0):"",date_till:this.input_date_till?$p.utils.date_add_day(dhx4.str2date(this.input_date_till.value),1,!0):"",filter:this.input_filter?this.input_filter.value:""};if(!e)for(t in this.custom_selection)a.selection||(a.selection=[]),n={},n[t]=this.custom_selection[t].value,a.selection.push(n);return a}},add_filter:{value:function(e){var t=this.toolbar.getPosition("input_filter")-2,n=dhx4.newId(),a=(this.toolbar.getWidth("input_filter")/2).round(0);this.toolbar.setWidth("input_filter",a),this.toolbar.addText("lbl_"+n,t,e.text||""),t++,this.toolbar.addInput("input_"+n,t,"",a),this.custom_selection[e.name]=this.toolbar.getInput("input_"+n)}}}),$p.iface.dat_blank=function(e,t){t||(t={});var n,a=(e||$p.iface.w).createWindow({id:dhx4.newId(),left:t.left||700,top:t.top||20,width:t.width||220,height:t.height||300,move:!0,park:!t.allow_close,center:!!t.center,resize:!0,caption:t.caption||"Tools"}),i={x:(e||$p.iface.w).vp.clientWidth,y:(e||$p.iface.w).vp.clientHeight};return a.getPosition()[0]+a.getDimension()[0]>i.x?(i.x=i.x-a.getDimension()[0],n=!0):i.x=a.getPosition()[0],a.getPosition()[1]+a.getDimension()[1]>i.y?(i.y=i.y-a.getDimension()[1],n=!0):i.y=a.getPosition()[1],n&&(i.x<0||i.y<0?a.maximize():a.setPosition(i.x,i.y)),e=null,t.hasOwnProperty("allow_minmax")&&!t.allow_minmax&&a.button("minmax").hide(),t.allow_close?a.button("park").hide():a.button("close").hide(),a.attachEvent("onClose",function(){var e="function"!=typeof t.on_close||t.on_close(a);if(e)return t.pwnd_modal&&t.pwnd&&t.pwnd.setModal&&t.pwnd.setModal(1),e}),a.setIconCss("without_icon"),a.cell.parentNode.children[1].classList.add("dat_gui"),$p.iface.bind_help(a,t.help_path),a.elmnts={grids:{}},a.wnd_options=function(e){var t=a.getPosition(),n=a.getDimension(),i=a.isParked();e.left=t[0],e.top=t[1],e.width=n[0],e.parked=i,i||(e.height=n[1])},a.bottom_toolbar=function(e){var t={wrapper:a.cell,width:"100%",height:"28px",bottom:"0px",left:"0px",name:"tb_bottom",buttons:[{name:"btn_cancel",text:"Отмена",title:"Закрыть без сохранения",width:"60px",float:"right"},{name:"btn_ok",b:"Ок",title:"Применить изменения",width:"30px",float:"right"}],onclick:function(e){return!1}}._mixin(e),n=new OTooolBar(t),i=a.attachStatusBar({height:12});return i.style.zIndex=-1e3,i.firstChild.style.backgroundColor="transparent",i.firstChild.style.border="none",n},t.modal&&(t.pwnd&&t.pwnd.setModal&&(t.pwnd_modal=t.pwnd.isModal(),t.pwnd.setModal(0)),a.setModal(1)),a},$p.iface.pgrid_on_select=function(e){if(void 0!==e){var t=this.grid instanceof dhtmlXGridObject?this.grid:this,n=t.getUserData("","source"),a=t.getSelectedRowId();if(void 0!=n.o[a])"number"==typeof n.o[a]?n.o[a]=$p.utils.fix_number(e,!0):n.o[a]=e;else if(a.indexOf("fprms")>-1){var i=$p._find(n.o.fprms,a.split("|")[1]);i.value=e}t.cells().setValue($p.utils.is_data_obj(e)?e.presentation:e||""),n.grid_on_change&&n.grid_on_change.call(t,a,e)}},$p.iface.pgrid_on_change=function(e,t,n){e&&$p.iface.pgrid_on_select.call(this,t)},$p.iface.pgrid_on_checkbox=function(e,t,n){var a=this.grid instanceof dhtmlXGridObject?this.grid:this,i=a.getUserData("","source");void 0!=i.o[e]&&(i.o[e]=n),i.grid_on_change&&i.grid_on_change(e,n)},$p.iface.frm_auth=function(e,t,n){function a(n,a){$p.ajax.username=n,$p.ajax.password=$p.aes.Ctr.encrypt(a),n?($p.wsql.get_user_param("user_name")!=n&&$p.wsql.set_user_param("user_name",n),$p.wsql.pouch.log_in(n,a).then(function(){$p.wsql.get_user_param("enable_save_pwd")?$p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd"))!=a&&$p.wsql.set_user_param("user_pwd",$p.aes.Ctr.encrypt(a)):""!=$p.wsql.get_user_param("user_pwd")&&$p.wsql.set_user_param("user_pwd",""),$p.eve.logged_in=!0,e.modal_dialog?s.close():t&&t()}).catch(function(e){l=!0,o.onerror(e)}).then(function(){$p.iface.sync&&$p.iface.sync.close(),s&&s.progressOff&&(s.progressOff(),!l&&e.hide_header&&s.hideHeader()),$p.iface.cell_tree&&!l&&$p.iface.cell_tree.expand()})):this.validate()}function i(e){if(l=!1,this.resetValidateCss(),"guest"==this.getCheckedValue("type")){var t=this.getItemValue("guest"),n="";$p.job_prm.guests&&$p.job_prm.guests.length&&$p.job_prm.guests.some(function(e){if(e.username==t)return n=$p.aes.Ctr.decrypt(e.password),!0}),a.call(this,t,n)}else"auth"==this.getCheckedValue("type")&&a.call(this,this.getItemValue("login"),this.getItemValue("password"))}e||(e={});var s,o,r,l;e.modal_dialog?(e.options||(e.options={name:"frm_auth",caption:"Вход на сервер",width:360,height:300,center:!0,allow_close:!0,allow_minmax:!0,modal:!0}),s=$p.iface.dat_blank(e._dxw,e.options),s.attachEvent("onClose",function(e){return l?n&&n(err):t&&t(),!0}),o=s.attachForm()):(s=e.cell||$p.iface.docs,o=$p.iface.auth=s.attachForm(),$p.msg.show_msg($p.msg.init_login,s)),o.loadStruct($p.injected_data["form_auth.xml"],function(){var t;if($p.job_prm.guests&&$p.job_prm.guests.length){var n=$p.job_prm.guests.map(function(e){var n={text:e.username,value:e.username};return $p.wsql.get_user_param("user_name")==e.username&&(n.selected=!0,t=e.username),n});t||(n[0].selected=!0,t=n[0].value),o.reloadOptions("guest",n)}$p.wsql.get_user_param("user_name")&&$p.wsql.get_user_param("user_name")!=t&&(o.setItemValue("login",$p.wsql.get_user_param("user_name")),o.setItemValue("type","auth"),$p.wsql.get_user_param("enable_save_pwd")&&$p.wsql.get_user_param("user_pwd")&&o.setItemValue("password",$p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd")))),e.modal_dialog||((r=((s.getWidth?s.getWidth():s.cell.offsetWidth)-500)/2)>=10?o.cont.style.paddingLeft=r.toFixed()+"px":o.cont.style.paddingLeft="20px"),setTimeout(function(){dhx4.callEvent("on_draw_auth",[o]),($p.wsql.get_user_param("autologin")||e.try_auto)&&(t||$p.wsql.get_user_param("user_name")&&$p.wsql.get_user_param("user_pwd"))&&i.call(o)})}),o.attachEvent("onButtonClick",i),o.attachEvent("onKeyDown",function(e,t,n,a){13==t.keyCode&&("password"!=n&&"guest"!=this.getCheckedValue("type")||i.call(this))}),o.onerror=function(e){$p.ajax.authorized=!1;var t=e.message.toLowerCase();t.indexOf("auth")!=-1?($p.msg.show_msg({title:$p.msg.main_title+$p.version,type:"alert-error",text:$p.msg.error_auth}),o.setItemValue("password",""),o.validate()):t.indexOf("gateway")==-1&&t.indexOf("net")==-1||$p.msg.show_msg({title:$p.msg.main_title+$p.version,type:"alert-error",text:$p.msg.error_network})}},$p.iface.open_settings=function(e){var t=e||("undefined"!=typeof event?event:void 0);t&&t.preventDefault();var n=$p.job_prm.parse_url();return $p.iface.set_hash(n.obj,n.ref,n.frm,"settings"),$p.iface.cancel_bubble(t)},$p.iface.swith_view=function(e){var t,n=$p.iface,a=function(e){function t(e,t){return e.text>t.text?1:e.text<t.text?-1:void 0}if(n.tree){if(n.tree._view!=e&&["rep","cal"].indexOf(e)==-1){if(n.tree.deleteChildItems(0),"oper"==e){var a,i,s={id:0,item:[{id:"oper_cat",text:$p.msg.meta_cat,open:!0,item:[]},{id:"oper_doc",text:$p.msg.meta_doc,item:[]},{id:"oper_cch",text:$p.msg.meta_cch,item:[]},{id:"oper_cacc",text:$p.msg.meta_cacc,item:[]},{id:"oper_tsk",text:$p.msg.meta_tsk,item:[]}]},o=s.item[0].item;for(a in $p.cat)"function"!=typeof $p.cat[a]&&(i=$p.cat[a].metadata(),i.hide||o.push({id:"oper.cat."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),o=s.item[1].item;for(a in $p.doc)"function"!=typeof $p.doc[a]&&(i=$p.doc[a].metadata(),i.hide||o.push({id:"oper.doc."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),o=s.item[2].item;for(a in $p.cch)"function"!=typeof $p.cch[a]&&(i=$p.cch[a].metadata(),i.hide||o.push({id:"oper.cch."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),o=s.item[3].item;for(a in $p.cacc)"function"!=typeof $p.cacc[a]&&(i=$p.cacc[a].metadata(),i.hide||o.push({id:"oper.cacc."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),o=s.item[4].item;for(a in $p.tsk)"function"!=typeof $p.tsk[a]&&(i=$p.tsk[a].metadata(),i.hide||o.push({id:"oper.tsk."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),n.tree.parse(s,function(){var e=$p.job_prm.parse_url();e.obj&&n.tree.selectItem(e.view+"."+e.obj,!0)},"json")}else n.tree.loadXML(n.tree.tree_filteres,function(){});n.tree._view=e}}else{var r=$p.job_prm.parse_url();if(r.obj){var l=r.obj.split(".");if(l.length>1){var c=$p.md.mgr_by_class_name(r.obj);"function"==typeof n.docs.close&&n.docs.close(),c&&c.form_list(n.docs,{})}}}};return 0==e.indexOf(n.docs.getViewName())?n.docs.getViewName():(t=n.docs.showView(e),1==t&&("cal"!=e||window.dhtmlXScheduler||($p.load_script("dist/dhtmlxscheduler.min.js","script",function(){scheduler.config.first_hour=8,scheduler.config.last_hour=22,n.docs.scheduler=n.docs.attachScheduler(new Date("2015-11-20"),"week","scheduler_here"),n.docs.scheduler.attachEvent("onBeforeViewChange",function(e,t,n,a){return"timeline"!=n||($p.msg.show_not_implemented(),!1)})}),$p.load_script("dist/dhtmlxscheduler.css","link"))),a(e),void("def"==e?n.main.showStatusBar():n.main.hideStatusBar()))},$p.iface.OTooolBar=OTooolBar,$p.iface.add_button=function(e,t,n){var a=document.createElement("div"),i="";return a.name=(t?t.name+"_":"")+n.name,e.appendChild(a),a.className=0==n.name.indexOf("sep_")?"md_otooolbar_sep":"md_otooolbar_button",n.hasOwnProperty("class_name")&&a.classList.add(n.class_name),n.img&&(i='<img src="'+(t?t.image_path:"")+n.img+'">'),n.b?i+='<b style="vertical-align: super;"> '+n.b+"</b>":n.text?i+='<span style="vertical-align: super;"> '+n.text+"</span>":n.css&&a.classList.add(n.css),a.innerHTML=i,n.float&&(a.style.float=n.float),n.clear&&(a.style.clear=n.clear),n.width&&(a.style.width=n.width),n.paddingRight&&(a.style.paddingRight=n.paddingRight),n.paddingLeft&&(a.style.paddingLeft=n.paddingLeft),n.tooltip&&(a.title=n.tooltip),a},"undefined"!=typeof window&&"dhtmlx"in window&&(eXcell_addr.prototype=eXcell_proto,window.eXcell_addr=eXcell_addr),DataManager.prototype.form_obj=function(e,t){function n(){h||((e instanceof dhtmlXLayoutCell||e instanceof dhtmlXSideBarCell||e instanceof dhtmlXCarouselCell)&&(t.bind_pwnd||t.Приклеить)?("function"==typeof e.close&&e.close(!0),f=e,f.close=function(t){var n=f||e;(t||d())&&(n&&(n.elmnts&&["vault","vault_pop"].forEach(function(e){n.elmnts[e]&&n.elmnts[e].unload&&n.elmnts[e].unload()}),v&&v.class_name&&$p.eve.callEvent("frm_close",[v.class_name,y&&y._obj?y.ref:""]),n.conf&&(n.detachToolbar(),n.detachStatusBar(),n.conf.unloading=!0,n.detachObject(!0))),p(t))},f.elmnts={grids:{}}):(m={name:"wnd_obj_"+v.class_name,wnd:{top:80+40*Math.random(),left:120+80*Math.random(),width:700,height:400,modal:!0,center:!1,pwnd:e,allow_close:!0,allow_minmax:!0,on_close:u,caption:x.obj_presentation||x.synonym}},f=$p.iface.dat_blank(null,m.wnd)),f.ref||f.__define({ref:{get:function(){return y?y.ref:$p.utils.blank.guid},enumerable:!1,configurable:!0},set_text:{value:function(e){if(t&&t.set_text||f&&f.setText){var n=y.presentation;if(!n)return;y instanceof CatObj?n=(x.obj_presentation||x.synonym)+": "+n:y instanceof DocObj&&(n+=y.posted?" (проведен)":" (не проведен)"),y._modified&&n.lastIndexOf("*")!=n.length-1?n+=" *":y._modified||n.lastIndexOf("*")!=n.length-1||(n=n.replace(" *","")),(e||g!==n)&&(g=n,t.set_text?t.set_text(n):f.setText(n))}},enumerable:!1,configurable:!0}}),f.elmnts.frm_tabs=f.attachTabbar({arrows_mode:"auto",offsets:{top:0,right:0,bottom:0,left:0}}),f.elmnts.frm_tabs.addTab("tab_header"," Реквизиты ",null,null,!0),f.elmnts.tabs={tab_header:f.elmnts.frm_tabs.cells("tab_header")},f.elmnts.frm_toolbar=f.attachToolbar(),f.elmnts.frm_toolbar.setIconsPath(dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()),f.elmnts.frm_toolbar.loadStruct(t.toolbar_struct||$p.injected_data["toolbar_obj.xml"],function(){f===e&&(this.cont.style.top="4px"),this.addSpacer("btn_unpost"),this.attachEvent("onclick",t.toolbar_click||s);var n=$p.current_acl.get_acl(v.class_name);v instanceof DocManager&&n.indexOf("p")!=-1?(this.enableItem("btn_post"),t.toolbar_struct||this.setItemText("btn_save_close","<b>Провести и закрыть</b>")):this.hideItem("btn_post"),v instanceof DocManager&&n.indexOf("o")!=-1?this.enableItem("btn_unpost"):this.hideItem("btn_unpost"),n.indexOf("e")==-1&&(this.hideItem("btn_save_close"),this.disableItem("btn_save")),t.on_select&&this.setItemText("btn_save_close","Записать и выбрать"),v instanceof CatManager||v instanceof DocManager?(v.printing_plates().then(function(e){for(var t in e)f.elmnts.frm_toolbar.addListOption("bs_print",t,"~","button",e[t].toString())}),f.elmnts.vault_pop=new dhtmlXPopup({toolbar:this,id:"btn_files"}),f.elmnts.vault_pop.attachEvent("onShow",r)):this.disableItem("bs_print"),f!=e&&this.hideItem("btn_close")}),h=!0)}function a(e){y&&f&&f.set_text()}function i(){if(h||(clearTimeout(_),n()),f.set_text(),!t.hide_header&&f.showHeader&&f.showHeader(),t.draw_tabular_sections)t.draw_tabular_sections(y,f,l);else if(!y.is_folder)if(x.form&&x.form.obj&&x.form.obj.tabular_sections_order)x.form.obj.tabular_sections_order.forEach(function(e){l(e)});else for(var e in x.tabular_sections)"extra_fields"!==e&&y[e]instanceof TabularSection&&l(e);if(t.draw_pg_header)t.draw_pg_header(y,f);else{var i=$p.current_acl.get_acl(v.class_name);f.elmnts.pg_header=f.elmnts.tabs.tab_header.attachHeadFields({obj:y,pwnd:f,read_only:i.indexOf("e")==-1}),f.attachEvent("onResizeFinish",function(e){f.elmnts.pg_header.enableAutoHeight(!1,f.elmnts.tabs.tab_header._getHeight()-20,!0)})}return Object.observe(y,a,["update","row"]),{wnd:f,o:y}}function s(e){"btn_save_close"==e?c("close"):"btn_save"==e?c("save"):"btn_post"==e?c("post"):"btn_unpost"==e?c("unpost"):"btn_close"==e?f.close():"btn_go_connection"==e?o():"prn_"==e.substr(0,4)?v.print(y,e,f):"btn_import"==e?v.import(null,y):"btn_export"==e&&v.export({items:[y],pwnd:f,obj:!0})}function o(){$p.msg.show_not_implemented()}function r(){f.elmnts.vault||(f.elmnts.vault=f.elmnts.vault_pop.attachVault(400,250,{_obj:y,buttonClear:!1,autoStart:!0,filesLimit:10,mode:"pouch"}),f.elmnts.vault.conf.wnd=f)}function l(e,t){if(_md.ts_captions(v.class_name,e)){f.elmnts.frm_tabs.addTab("tab_"+e," "+x.tabular_sections[e].synonym+" "),f.elmnts.tabs["tab_"+e]=f.elmnts.frm_tabs.cells("tab_"+e);var n=$p.current_acl.get_acl(v.class_name);if(f.elmnts.grids[e]=f.elmnts.tabs["tab_"+e].attachTabular({obj:y,ts:e,pwnd:f,read_only:n.indexOf("e")==-1,toolbar_struct:t}),n.indexOf("e")==-1){var a=f.elmnts.tabs["tab_"+e].getAttachedToolbar();a.disableItem("btn_add"),a.disableItem("btn_delete")}}}function c(e){f.progressOn();var n;y instanceof DocObj&&("post"==e?n=!0:"unpost"==e?n=!1:"close"==e&&$p.current_acl.get_acl(v.class_name).indexOf("p")!=-1&&(n=!0)),y.save(n).then(function(){f.progressOff(),"close"==e?(t.on_select&&t.on_select(y),f.close()):f.set_text()}).catch(function(e){f.progressOff(),e instanceof Error&&$p.record_log(e)})}function p(n){t&&t.on_close&&!n&&t.on_close(),n||(delete f.ref,delete f.set_text,Object.unobserve(y,a),v=f=y=x=m=e=t=null)}function d(){return!(y._modified&&!b)||(dhtmlx.confirm({title:y.presentation,text:$p.msg.modified_close,cancel:$p.msg.cancel,callback:function(e){e&&(b=!0,"ram"==y._manager.cachable?this.close():y.is_new()?(y.unload(),this.close()):(setTimeout(y.load.bind(y),100),this.close()))}.bind(f)}),!1)}function u(e){if(d())return setTimeout(p),e&&e.elmnts&&["vault","vault_pop"].forEach(function(t){e.elmnts[t]&&e.elmnts[t].unload&&e.elmnts[t].unload()}),v&&v.class_name&&$p.eve.callEvent("frm_close",[v.class_name,y&&y._obj?y.ref:""]),!0}var f,m,h,_,g,b,v=this,x=v.metadata(),y=t.o;return _=setTimeout(n),$p.utils.is_data_obj(y)?y.is_new()&&t.on_select?v.create({},!0).then(function(e){return y=e,e=null,i()}):y.is_new()&&!y.empty()?y.load().then(i):Promise.resolve(i()):(e&&e.progressOn&&e.progressOn(),v.get(t.hasOwnProperty("ref")?t.ref:t,!0,!0).then(function(t){return y=t,t=null,e&&e.progressOff&&e.progressOff(),i()}).catch(function(t){e&&e.progressOff&&e.progressOff(),f.close(),$p.record_log(t)}))},DataObj.prototype.form_obj=function(e,t){return t||(t={}),t.o=this,this._manager.form_obj(e,t)},DataProcessorsManager.prototype.form_rep=function(e,t){function n(){if((e instanceof dhtmlXLayoutCell||e instanceof dhtmlXSideBarCell||e instanceof dhtmlXCarouselCell)&&(t.bind_pwnd||t.Приклеить)){if(o==e&&o._mgr==c)return;"function"==typeof e.close&&e.close(!0),o=e,o.close=function(t){var n=o||e;(t||check_modified())&&(n&&n.conf&&(n.detachToolbar(),n.detachStatusBar(),n.conf.unloading=!0,n.detachObject(!0)),s(t))},o.elmnts={grids:{}}}else r={name:"wnd_rep_"+c.class_name,wnd:{top:80+40*Math.random(),left:120+80*Math.random(),width:700,height:400,modal:!0,center:!1,pwnd:e,allow_close:!0,allow_minmax:!0,on_close:frm_close,caption:p.obj_presentation||p.synonym}},o=$p.iface.dat_blank(null,r.wnd);o._mgr=c,o.report=c.create(),o.set_text||o.__define({set_text:{value:function(e){if(t&&t.set_text||o&&o.setText){var n=p.obj_presentation||p.synonym;(e||l!==n)&&(l=n,t.set_text?t.set_text(n):o.setText(n))}},configurable:!0}}),o.elmnts.layout=o.attachLayout({pattern:"2U",cells:[{id:"a",text:"Отчет",header:!1},{id:"b",text:"Параметры",collapsed_text:"Параметры",width:220}],offsets:{top:0,right:0,bottom:0,left:0}}),o.elmnts.frm_toolbar=o.attachToolbar(),o.elmnts.frm_toolbar.setIconsPath(dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()),o.elmnts.frm_toolbar.loadStruct(t.toolbar_struct||$p.injected_data["toolbar_rep.xml"],function(){o===e&&(this.cont.style.top="4px"),this.addSpacer("btn_run"),this.attachEvent("onclick",t.toolbar_click||a)}),o.set_text(),!t.hide_header&&o.showHeader&&o.showHeader(),o.elmnts.table=new $p.HandsontableDocument(o.elmnts.layout.cells("a"),{allow_offline:o.report.allow_offline,autorun:!1}).then(function(e){if(!e._online)return o.elmnts.table=null}),o.elmnts.frm_prm=document.createElement("DIV"),o.elmnts.frm_prm.style="height: 100%; min-height: 300px; width: 100%",o.elmnts.layout.cells("b").attachObject(o.elmnts.frm_prm),o.report.daterange=new $p.iface.ODateRangePicker(o.elmnts.frm_prm,t)}function a(e){"btn_close"==e?o.close():"btn_run"==e&&o.report.build().then(i).catch(i)}function i(e){o.elmnts.table.requery(e)}function s(n){t&&t.on_close&&!n&&t.on_close(),n||(delete o.set_text,o.elmnts.table&&o.elmnts.table.hot.destroy(),o.report.daterange&&o.report.daterange.remove(),o.report=null,c=o=p=r=e=t=null)}var o,r,l,c=this,p=c.metadata();return t||(t={}),t.date_from||(t.date_from=new Date((new Date).getFullYear().toFixed()+"-01-01")),t.date_till||(t.date_till=new Date((new Date).getFullYear().toFixed()+"-12-31")),n(),o},DataManager.prototype.form_selection=function(e,t){function n(){return e instanceof dhtmlXCellObject?(e instanceof dhtmlXTabBarCell||"function"!=typeof e.close||e.close(!0),m=e,m.close=function(t){(m||e)&&((m||e).detachToolbar(),(m||e).detachStatusBar(),(m||e).conf&&((m||e).conf.unloading=!0),(m||e).detachObject(!0)),p(t)},t.hide_header||setTimeout(function(){m.showHeader()})):(m=$p.iface.w.createWindow(null,0,0,700,500),m.centerOnScreen(),m.setModal(1),m.button("park").hide(),m.button("minmax").show(),m.button("minmax").enable(),m.attachEvent("onClose",d)),$p.iface.bind_help(m),m.setText&&!t.hide_text&&m.setText("Список "+(h.class_name.indexOf("doc.")==-1?'справочника "':'документов "')+(_.list_presentation||_.synonym)+'"'),document.body.addEventListener("keydown",a,!1),m.elmnts={},!t.status_bar&&t.smart_rendering||(m.elmnts.status_bar=m.attachStatusBar()),t.smart_rendering||m.elmnts.status_bar.setText("<div id='"+h.class_name.replace(".","_")+"_select_recinfoArea'></div>"),m.elmnts.toolbar=m.attachToolbar(),m.elmnts.toolbar.setIconsPath(dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()),m.elmnts.toolbar.loadStruct(t.toolbar_struct||$p.injected_data["toolbar_selection.xml"],function(){this.attachEvent("onclick",o),m===e&&(this.cont.parentElement.classList.add("dhx_cell_toolbar_no_borders"),this.cont.parentElement.classList.remove("dhx_cell_toolbar_def"),this.cont.style.top="4px");var n={manager:h,toolbar:this,onchange:i,hide_filter:t.hide_filter,custom_selection:t.custom_selection};t.date_from&&(n.date_from=t.date_from),t.date_till&&(n.date_till=t.date_till),t.period&&(n.period=t.period),m.elmnts.filter=new $p.iface.Toolbar_filter(n);var a=$p.current_acl.get_acl(h.class_name);a.indexOf("i")==-1&&this.hideItem("btn_new"),a.indexOf("v")==-1&&this.hideItem("btn_edit"),a.indexOf("d")==-1&&this.hideItem("btn_delete"),y||(this.hideItem("btn_select"),this.hideItem("sep1"),$p.iface.docs&&$p.iface.docs.getViewName&&"oper"==$p.iface.docs.getViewName()&&this.addListOption("bs_more","btn_order_list","~","button","<i class='fa fa-briefcase fa-lg fa-fw'></i> Список заказов")),this.addListOption("bs_more","btn_import","~","button","<i class='fa fa-upload fa-lg fa-fw'></i> Загрузить из файла"),this.addListOption("bs_more","btn_export","~","button","<i class='fa fa-download fa-lg fa-fw'></i> Выгрузить в файл"),h.printing_plates?h.printing_plates().then(function(e){var t;for(var n in e)m.elmnts.toolbar.addListOption("bs_print",n,"~","button",e[n].toString()),t=!0;t||m.elmnts.toolbar.hideItem("bs_print")}):m.elmnts.toolbar.hideItem("bs_print"),s()}),m._mgr=h,m}function a(e){function t(){var e;return $p.iface.w.forEachWindow(function(t){t==m||!t.isModal()&&$p.iface.w.getTopmostWindow()!=t||(e=!0)}),e}if(m&&m.is_visible&&m.is_visible())if(e.ctrlKey&&70==e.keyCode){if(!t())return setTimeout(function(){m.elmnts.filter.input_filter&&"desktop"==$p.job_prm.device_type&&m.elmnts.filter.input_filter.focus()}),$p.iface.cancel_bubble(e)}else if(e.shiftKey&&116==e.keyCode){if(!t())return setTimeout(function(){m.elmnts.grid.reload()}),e.preventDefault&&e.preventDefault(),$p.iface.cancel_bubble(e)}else 27==e.keyCode&&(t()||setTimeout(function(){m.close()}))}function i(e){m&&m.elmnts&&(g&&(e.filter||e.hide_tree?m.elmnts.cell_tree.collapse():m.elmnts.cell_tree.expand()),m.elmnts.grid.reload())}function s(){var e,n,a,i,s,o;g?(e=m.attachLayout("2U"),a=e.cells("b"),a.hideHeader(),n=m.elmnts.cell_tree=e.cells("a"),n.setWidth("220"),n.hideHeader(),i=m.elmnts.tree=n.attachDynTree(h,null,function(){setTimeout(function(){s&&s.reload&&s.reload()},20)}),i.attachEvent("onSelect",function(e,t){t&&(this.do_not_reload?delete this.do_not_reload:setTimeout(function(){ -s&&s.reload&&s.reload()},20))}),i.attachEvent("onDblClick",function(e){r(e)})):(a=m,setTimeout(function(){s&&s.reload&&s.reload()},20)),s=m.elmnts.grid=a.attachGrid(),s.setIconsPath(dhtmlx.image_path),s.setImagePath(dhtmlx.image_path),s.attachEvent("onBeforeSorting",f),s.attachEvent("onBeforePageChanged",function(){return!!this.getRowsNum()}),s.attachEvent("onXLE",function(){a.progressOff()}),s.attachEvent("onXLS",function(){a.progressOn()}),s.attachEvent("onDynXLS",function(e,t){var n=u(e,t);if(n)return h.sync_grid(n,s),!1}),s.attachEvent("onRowDblClicked",function(e,t){if(i&&i.items[e]){i.selectItem(e);var n=i.getParentId(e);n&&n!=$p.utils.blank.guid&&i.openItem(n)}else r(e)}),t.smart_rendering?s.enableSmartRendering(!0,50):(s.setPagingWTMode(!0,!0,!0,[20,30,60]),s.enablePaging(!0,30,8,h.class_name.replace(".","_")+"_select_recinfoArea"),s.setPagingSkin("toolbar",dhtmlx.skin)),$p.iface.docs&&$p.iface.docs.getViewName&&"oper"==$p.iface.docs.getViewName()&&s.enableMultiselect(!0),s.reload=function(){var e=u();return e?(a.progressOn(),s.clearAll(),h.sync_grid(e,s).then(function(n){if("object"==typeof n)$p.msg.check_soap_result(n);else if(!o){if(e.initial_value){var r=n.indexOf("set_parent"),l=n.indexOf("'>",r),c=n.substr(r+12,l-r-12);$p.utils.is_guid(c)&&g&&(i.do_not_reload=!0,i.selectItem(c,!1)),s.selectRowById(e.initial_value)}else e.parent&&$p.utils.is_guid(e.parent)&&g&&(i.do_not_reload=!0,i.selectItem(e.parent,!1));s.setColumnMinWidth(200,s.getColIndexById("presentation")),s.enableAutoWidth(!0,1200,600),s.setSizes(),o=!0,m.elmnts.filter.input_filter&&"desktop"==$p.job_prm.device_type&&m.elmnts.filter.input_filter.focus(),t.on_grid_inited&&t.on_grid_inited()}v&&o&&s.setSortImgState(!0,b,v),a.progressOff()})):Promise.resolve()}}function o(e){if(!t.toolbar_click||t.toolbar_click(e,m,h)!==!1)if("btn_select"==e)r();else if("btn_new"==e)h.create({},!0).then(function(e){t.on_new?t.on_new(e,m):$p.job_prm.keep_hash?e.form_obj(m):(e._set_loaded(e.ref),$p.iface.set_hash(h.class_name,e.ref))});else if("btn_edit"==e){var n=m.elmnts.grid.getSelectedRowId();n?t.on_edit?t.on_edit(h,n,m):$p.job_prm.keep_hash?h.form_obj(m,{ref:n}):$p.iface.set_hash(h.class_name,n):$p.msg.show_msg({type:"alert-warning",text:$p.msg.no_selected_row.replace("%1",""),title:$p.msg.main_title})}else"prn_"==e.substr(0,4)?l(e):"btn_order_list"==e?$p.iface.set_hash("","","","def"):"btn_delete"==e?c():"btn_import"==e?h.import():"btn_export"==e?h.export(m.elmnts.grid.getSelectedRowId()):"btn_requery"==e&&(x={},m.elmnts.grid.reload())}function r(n){n||(n=m.elmnts.grid.getSelectedRowId());var a;if(t.selection&&t.selection.forEach(function(e){for(var t in e)"is_folder"==t&&(a=e[t])}),m.elmnts.tree&&m.elmnts.tree.items[n]&&m.elmnts.tree.getSelectedId()!=n)return void m.elmnts.tree.selectItem(n,!0);if(n&&a===!0&&m.elmnts.grid.cells(n,0).cell.classList.contains("cell_ref_elm"))return void $p.msg.show_msg($p.msg.select_grp);if(!n&&m.elmnts.tree||m.elmnts.tree&&m.elmnts.tree.getSelectedId()==n){if(a===!1)return void $p.msg.show_msg($p.msg.select_elm);n=m.elmnts.tree.getSelectedId()}n&&(t.on_edit?t.on_edit(h,n,m):y?h.get(n,!0).then(function(t){m.close(),y.call(e.grid||e,t)}):$p.job_prm.keep_hash?h.form_obj(m,{ref:n}):$p.iface.set_hash(h.class_name,n))}function l(e){var t=m.elmnts.grid.getSelectedRowId();t?h.print(t,e,m):$p.msg.show_msg({type:"alert-warning",text:$p.msg.no_selected_row.replace("%1",""),title:$p.msg.main_title})}function c(){var e=m.elmnts.grid.getSelectedRowId();e?h.get(e,!0,!0).then(function(e){dhtmlx.confirm({title:$p.msg.main_title,text:e._deleted?$p.msg.mark_undelete_confirm.replace("%1",e.presentation):$p.msg.mark_delete_confirm.replace("%1",e.presentation),cancel:"Отмена",callback:function(t){t&&e.mark_deleted(!e._deleted)}})}):$p.msg.show_msg({type:"alert-warning",text:$p.msg.no_selected_row.replace("%1",""),title:$p.msg.main_title})}function p(n){document.body.removeEventListener("keydown",a),t&&t.on_close&&!n&&t.on_close(),n||(h=m=_=x=y=e=t=null)}function d(){return setTimeout(p,10),e.on_unload&&e.on_unload.call(e.grid||e),w&&($p.eve.detachEvent(w),w=null),!0}function u(e,n){var a=m.elmnts.filter.get_filter()._mixin({action:"get_selection",metadata:_,class_name:h.class_name,order_by:m.elmnts.grid.columnIds[b]||b,direction:v,start:e||((m.elmnts.grid.currentPage||1)-1)*m.elmnts.grid.rowsBufferOutSize,count:n||m.elmnts.grid.rowsBufferOutSize,get_header:void 0==x.get_header}),i=g?m.elmnts.tree.getSelectedId():null;if(t.smart_rendering&&(a.smart_rendering=!0),t.date_from&&!a.date_from&&(a.date_from=t.date_from),t.date_till&&!a.date_till&&(a.date_till=t.date_till),t.initial_value&&(a.initial_value=t.initial_value),t.custom_selection&&(a.custom_selection=t.custom_selection),t.selection)if(a.selection)if(Array.isArray(t.selection))t.selection.forEach(function(e){a.selection.push(e)});else for(var s in t.selection){res.selection||(res.selection=[]);var o={};o[s]=t.selection[s],a.selection.push(o)}else a.selection=t.selection;t.owner&&!a.owner&&(a.owner=t.owner),a.parent=!i&&!t.parent||a.filter?null:i||t.parent,g&&!a.parent&&(a.parent=$p.utils.blank.guid);for(var r in a)if(x[r]!=a[r])return x=a,a}function f(e){var t=m.elmnts.grid.getSortingState();return b=e,v="des"==t[1]?"asc":"des",m.elmnts.grid.reload(),!0}e||(e=t&&t.pwnd?t.pwnd:{}),t||e instanceof dhtmlXCellObject||(t=e,e={}),t||(t={});var m,h=this,_=t.metadata||h.metadata(),g=_.hierarchical&&!(h instanceof ChartOfAccountManager),b=0,v="asc",x={},y=e.on_select||t.on_select,w=$p.eve.attachEvent("frm_close",function(e,t){h&&h.class_name==e&&m&&m.elmnts&&m.elmnts.grid.reload().then(function(){$p.utils.is_empty_guid(t)||m.elmnts.grid.selectRowById(t,!1,!0,!0)})});return g&&t.initial_value&&t.initial_value!=$p.utils.blank.guid&&!t.parent?h.get(t.initial_value,!0).then(function(e){return t.parent=e.parent.ref,t.set_parent=t.parent,n()}):n()},DataManager.prototype.form_list=function(e,t){return this.form_selection(e,t)},$p.iface.wnd_sync=function(){function e(){var e={name:"wnd_sync",wnd:{id:"wnd_sync",top:130,left:200,width:496,height:290,modal:!0,center:!0,caption:"Подготовка данных"}};t.wnd_sync=$p.iface.dat_blank(null,e.wnd);var n=[{type:"block",name:"form_block_1",list:[{type:"label",name:"form_label_1",label:$p.msg.sync_data},{type:"block",name:"form_block_2",list:[{type:"template",name:"img_long",className:"img_long"},{type:"newcolumn"},{type:"template",name:"text_processed"},{type:"template",name:"text_current"},{type:"template",name:"text_bottom"}]}]},{type:"button",name:"form_button_1",value:$p.msg.sync_break}];t.frm_sync=t.wnd_sync.attachForm(n),t.frm_sync.attachEvent("onButtonClick",function(e){t&&(t.do_break=!0)}),t.frm_sync.setItemValue("text_processed","Инициализация"),t.frm_sync.setItemValue("text_bottom","Загружается структура таблиц...")}var t,n=$p.iface.sync={};n.create=function(n){t=n,e()},n.update=function(e){t.frm_sync.setItemValue("text_processed","Обработано элементов: "+t.step*t.step_size+" из "+t.count_all);var n,a="",i=0;for(var s in e){if(i++,i>4)break;a&&(a+="<br />"),n=$p.cat[s].metadata(),a+=(n.list_presentation||n.synonym)+" ("+e[s].length+")"}t.frm_sync.setItemValue("text_current","Текущий запрос: "+t.step+" ("+Math.round(t.step*t.step_size*100/t.count_all)+"%)"),t.frm_sync.setItemValue("text_bottom",a)},n.close=function(){t&&t.wnd_sync&&(t.wnd_sync.close(),delete t.wnd_sync,delete t.frm_sync)}},DataManager.prototype.export=function(e){function t(){$p.wsql.restore_options("data_manager",l),l.wnd.caption="Экспорт "+r.family_name+" '"+(r.metadata().synonym||r.metadata().name)+"'",o=$p.iface.dat_blank(null,l.wnd),o.bottom_toolbar({buttons:[{name:"btn_cancel",text:'<i class="fa fa-times fa-lg"></i> Отмена',title:"Отмена",width:"80px",float:"right"},{name:"btn_ok",b:'<i class="fa fa-floppy-o"></i> Ок',title:"Выполнить экспорт",width:"50px",float:"right"}],onclick:function(e){return"btn_ok"==e?i():o.close(),!1}}),o.button("close").show(),o.button("park").hide(),o.attachEvent("onClose",s);var t=[{type:"fieldset",name:"form_range",label:"Выгрузить",list:[{type:"settings",labelWidth:320,labelAlign:"left",position:"label-right"},{type:"radio",name:"range",label:"Выделенные строки",value:"selected"},{type:"radio",name:"range",label:"Весь справочник",value:"all"}]},{type:"fieldset",name:"form_fieldset_2",label:"Дополнительно выгрузить",list:[{type:"settings",labelWidth:160,position:"label-right"},{type:"checkbox",name:"meta",label:"Описание метаданных",labelAlign:"left",position:"label-right",checked:l.meta},{type:"newcolumn"},{type:"checkbox",name:"relation",label:"Связанные объекты",position:"label-right",checked:l.relation,tooltip:"Связанные объекты по ссылкам (пока не реализовано)"}]},{type:"fieldset",name:"fieldset_format",label:"Формат файла",list:[{type:"settings",labelWidth:60,labelAlign:"left",position:"label-right"},{type:"radio",name:"format",label:"json",value:"json",tooltip:"Выгрузить в формате JSON"},{type:"newcolumn"},{type:"radio",name:"format",label:"xlsx",value:"xlsx",tooltip:"Выгрузить в офисном формате XLSX"},{type:"newcolumn"},{type:"radio",name:"format",label:"atom",value:"atom",tooltip:"Выгрузить в формате XML Atom"}]}];o.elmnts.frm=o.attachForm(t),o.elmnts.frm.setItemValue("range",l.range||"all"),e.items&&1==e.items.length?(e.obj?o.elmnts.frm.setItemLabel("range","selected","Тек. объект: "+e.items[0].presentation):r.get(e.items[0],!0).then(function(e){o.elmnts.frm.setItemLabel("range","selected","Тек. объект: "+e.presentation)}),o.elmnts.frm.setItemValue("range","selected")):e.items&&e.items.length&&o.elmnts.frm.setItemLabel("range","selected","Выделенные строки ("+e.items.length+" элем.)"),r instanceof DocManager&&o.elmnts.frm.setItemLabel("range","all","Все документы из кеша (0 элем.)"),o.elmnts.frm.setItemValue("format",l.format||"json"),o.elmnts.frm.attachEvent("onChange",n),n(),e.pwnd&&e.pwnd.isModal&&e.pwnd.isModal()&&(e.set_pwnd_modal=!0,e.pwnd.setModal(!1)),o.setModal(!0)}function n(){o.elmnts.frm.setItemValue("relation",!1),o.elmnts.frm.disableItem("relation"),"all"==o.elmnts.frm.getItemValue("range")?(o.elmnts.frm.disableItem("format","atom"),"atom"==o.elmnts.frm.getItemValue("format")&&o.elmnts.frm.setItemValue("format","json")):o.elmnts.frm.enableItem("format","atom"),"json"==o.elmnts.frm.getItemValue("format")?o.elmnts.frm.enableItem("meta"):"sql"==o.elmnts.frm.getItemValue("format")?(o.elmnts.frm.setItemValue("meta",!1),o.elmnts.frm.disableItem("meta")):(o.elmnts.frm.setItemValue("meta",!1),o.elmnts.frm.disableItem("meta"))}function a(){return l.format=o.elmnts.frm.getItemValue("format"),l.range=o.elmnts.frm.getItemValue("range"),l.meta=o.elmnts.frm.getItemValue("meta"),l.relation=o.elmnts.frm.getItemValue("relation"),l}function i(){function t(){e.obj?$p.wsql.alasql("SELECT * INTO XLSX('"+r.table_name+".xlsx',{headers:true}) FROM ?",[e.items[0]._obj]):$p.wsql.alasql("SELECT * INTO XLSX('"+r.table_name+".xlsx',{headers:true}) FROM "+r.table_name)}a();var n={meta:{},items:{}},i=n.items[r.class_name]=[];if(l.meta&&(n.meta[r.class_name]=r.metadata()),"json"==l.format)e.obj?i.push(e.items[0]._obj):r.each(function(t){"all"!=l.range&&e.items.indexOf(t.ref)==-1||i.push(t._obj)}),e.items.length&&!i.length?r.get(e.items[0],!0).then(function(e){i.push(e._obj),alasql.utils.saveFile(r.table_name+".json",JSON.stringify(n,null,4))}):alasql.utils.saveFile(r.table_name+".json",JSON.stringify(n,null,4));else if("xlsx"==l.format)window.xlsx?t():$p.load_script("//cdn.jsdelivr.net/js-xlsx/latest/xlsx.core.min.js","script",t);else if("atom"==l.format&&e.items.length){var s=e.obj?Promise.resolve(e.items[0]):r.get(e.items[0],!0);s.then(function(e){alasql.utils.saveFile(r.table_name+".xml",e.to_atom())})}else $p.msg.show_not_implemented()}function s(t){return $p.iface.popup.hide(),o.wnd_options(l.wnd),$p.wsql.save_options("data_manager",a()),o.setModal(!1),e.set_pwnd_modal&&e.pwnd.setModal&&e.pwnd.setModal(!0),!0}e&&"string"==typeof e?e={items:e.split(",")}:e||(e={items:[]});var o,r=this,l={name:"export",wnd:{top:130,left:200,width:480,height:350}};t()},DataManager.prototype.import=function(e,t){function n(e){function n(e,n){var a=_md.mgr_by_class_name(e);if(n.length)if(t){if(t._manager==a)for(var s in n)$p.utils.fix_guid(n[s])==t.ref&&(i=!0,a.load_array([n[s]],!0))}else i=!0,a.load_array(n,!0)}if(o.close(),a.files.length){var s=new FileReader;s.onload=function(e){try{var t=JSON.parse(s.result);if(t.items)for(var a in t.items)n(a,t.items[a]);else["cat","doc","ireg","areg","cch","cacc"].forEach(function(e){if(t[e])for(var a in t[e])n(e+"."+a,t.cat[a])});i||$p.msg.show_msg($p.msg.sync_no_data)}catch(e){$p.msg.show_msg(e.message)}},s.readAsText(a.files[0])}}var a,i;if(!e&&void 0!=typeof window){var s={name:"import",wnd:{width:300,height:100,caption:$p.msg.select_file_import}},o=$p.iface.dat_blank(null,s.wnd);a=document.createElement("input"),a.setAttribute("id","json_file"),a.setAttribute("type","file"),a.setAttribute("accept",".json"),a.setAttribute("value","*.json"),a.onchange=n,o.button("close").show(),o.button("park").hide(),o.attachObject(a),o.centerOnScreen(),o.setModal(!0),setTimeout(function(){a.click()},100)}},$p.eve.__define({set_offline:{value:function(e){var t=$p.job_prm.offline;$p.job_prm.offline=!(!e&&!$p.wsql.get_user_param("offline","boolean")),t!=$p.job_prm.offline&&(t=$p.job_prm.offline)}},on_rotate:{value:function(e){$p.job_prm.device_orient=0==window.orientation||180==window.orientation?"portrait":"landscape","undefined"!=typeof e&&$p.eve.callEvent("onOrientationChange",[$p.job_prm.device_orient])}},steps:{value:{load_meta:0,authorization:1,create_managers:2,process_access:3,load_data_files:4,load_data_db:5,load_data_wsql:6,save_data_wsql:7}},log_in:{value:function(e){var t,n={};return e($p.eve.steps.load_meta),$p.ajax.default_attr(n,$p.job_prm.irest_url()),($p.job_prm.offline?Promise.resolve({responseURL:"",response:""}):$p.ajax.get_ex(n.url,n)).then(function(e){if($p.job_prm.offline||($p.job_prm.irest_enabled=!0),"{"==e.response[0])return JSON.parse(e.response)}).catch(function(){}).then(function(n){return e($p.eve.steps.authorization),t=n,t.root=!0,$p.job_prm.offline||$p.job_prm.irest_enabled?t:$p.ajax.get_ex($p.job_prm.rest_url()+"?$format=json",!0).then(function(){return t})}).catch(function(e){throw $p.iface.auth.onerror&&$p.iface.auth.onerror(e),e}).then(function(t){return e($p.eve.steps.load_data_files),$p.job_prm.offline?t:($p.eve.callEvent("log_in",[$p.ajax.authorized=!0]),"string"==typeof t&&(t=JSON.parse(t)),void($p.msg.check_soap_result(t)||($p.wsql.get_user_param("enable_save_pwd")?$p.wsql.set_user_param("user_pwd",$p.ajax.password):$p.wsql.get_user_param("user_pwd")&&$p.wsql.set_user_param("user_pwd",""),t.now_1c&&t.now_js&&$p.wsql.set_user_param("time_diff",t.now_1c-t.now_js))))}).then(function(){_md.printing_plates(t.printing_plates)})}}}),function(w,eve,msg){var timer_setted=!1,cache;w.addEventListener("online",eve.set_offline),w.addEventListener("offline",function(){eve.set_offline(!0)}),w.addEventListener("load",function(){setTimeout(function(){function navigate(e){e&&(location.origin+location.pathname).indexOf(e)==-1&&location.replace(e)}function init_params(){function e(){var e=dhtmlx.codebase,t=!0,n=!0;e.indexOf("cdn.jsdelivr.net")!=-1&&(e="//cdn.jsdelivr.net/metadata/latest/");for(var a=0;a<document.styleSheets.length;a++)document.styleSheets[a].href&&(document.styleSheets[a].href.indexOf("dhx_web")==-1&&document.styleSheets[a].href.indexOf("dhx_terrace")==-1||(t=!1),document.styleSheets[a].href.indexOf("metadata.css")!=-1&&(n=!1));dhtmlx.skin=$p.wsql.get_user_param("skin")||$p.job_prm.skin||"dhx_web",t&&$p.load_script(e+("dhx_web"==dhtmlx.skin?"dhx_web.css":"dhx_terrace.css"),"link"),n&&$p.load_script(e+"metadata.css","link"),$p.job_prm.additional_css&&$p.job_prm.additional_css.forEach(function(e){(dhx4.isIE||e.indexOf("ie_only")==-1)&&$p.load_script(e,"link")}),dhtmlx.image_path="//oknosoft.github.io/metadata.js/lib/imgs/",dhtmlx.skin_suffix=function(){return dhtmlx.skin.replace("dhx","")+"/"},dhx4.ajax.cache=!0,$p.iface.__define("w",{value:new dhtmlXWindows,enumerable:!1}),$p.iface.w.setSkin(dhtmlx.skin),$p.iface.__define("popup",{value:new dhtmlXPopup,enumerable:!1})}$p.wsql.init_params(),"dhtmlx"in w&&e(),"undefined"==typeof w.orientation?$p.job_prm.device_orient=w.innerWidth>w.innerHeight?"landscape":"portrait":eve.on_rotate(),w.addEventListener("orientationchange",eve.on_rotate,!1),eve.stepper={step:0,count_all:0,step_size:57,files:0},eve.set_offline(!navigator.onLine),setTimeout(function(){$p.wsql.pouch.load_data().catch($p.record_log);var e;(e=document.querySelector("#splash"))&&e.parentNode.removeChild(e),eve.callEvent("iface_init",[$p])},20),(cache=w.applicationCache)&&(cache.addEventListener("noupdate",function(e){},!1),cache.addEventListener("cached",function(e){timer_setted=!0,$p.iface.appcache&&$p.iface.appcache.close()},!1),cache.addEventListener("updateready",function(e){try{cache.swapCache()}catch(e){}$p.iface.do_reload()},!1),cache.addEventListener("error",$p.record_log,!1))}if(!w.JSON||!w.indexedDB)throw eve.redirect=!0,msg.show_msg({type:"alert-error",text:msg.unsupported_browser,title:msg.unsupported_browser_title}),msg.unsupported_browser;$p.__define("job_prm",{value:new JobPrm,writable:!1}),($p.job_prm.use_ip_geo||$p.job_prm.use_google_geo)&&($p.ipinfo=new IPInfo),$p.job_prm.use_google_geo&&(window.google&&window.google.maps?location_callback():$p.on("iface_init",function(){setTimeout(function(){$p.load_script("//maps.google.com/maps/api/js?callback=$p.ipinfo.location_callback","script",function(){})},100)})),$p.job_prm.allow_post_message&&w.addEventListener("message",function(event){if(("*"==$p.job_prm.allow_post_message||$p.job_prm.allow_post_message==event.origin)&&"string"==typeof event.data)try{var res=eval(event.data);if(res&&event.source){if("object"==typeof res)res=JSON.stringify(res);else if("function"==typeof res)return;event.source.postMessage(res,"*")}}catch(e){$p.record_log(e)}}),$p.job_prm.__define("device_type",{get:function(){var e=$p.wsql.get_user_param("device_type");return e||(e=function(e){return e<800?"phone":e<1024?"tablet":"desktop"}(Math.max(screen.width,screen.height)),$p.wsql.set_user_param("device_type",e)),e},set:function(e){$p.wsql.set_user_param("device_type",e)}}),document.body.addEventListener("keydown",function(e){eve.callEvent("keydown",[e])},!1),setTimeout(init_params,10)},10)},!1),w.onbeforeunload=function(){if(!eve.redirect)return msg.onbeforeunload},w.addEventListener("popstat",$p.iface.hash_route),w.addEventListener("hashchange",$p.iface.hash_route)}(window,$p.eve,$p.msg),SpreadsheetDocument.prototype.__define({clear:{value:function(){for(;this._attr.content.firstChild;)this._attr.content.removeChild(this._attr.content.firstChild)}},put:{value:function(e,t){var n;e instanceof HTMLElement?(n=document.createElement(e.tagName),n.innerHTML=e.innerHTML,t||(t=e.attributes)):(n=document.createElement("DIV"),n.innerHTML=e),t&&Object.keys(t).forEach(function(e){"id"!=e&&"id"!=t[e].name&&n.setAttribute(t[e].name||e,t[e].value||t[e])}),this._attr.content.appendChild(n)}},content:{get:function(){return this._attr.content},set:function(e){this.clear(),"string"==typeof e?this._attr.content.innerHTML=e:e instanceof HTMLElement&&(this._attr.content.innerHTML=e.innerHTML)}},title:{get:function(){return this._attr.title},set:function(e){this._attr.title=e}}}),$p.SpreadsheetDocument=SpreadsheetDocument,$p.HandsontableDocument=HandsontableDocument,$p.injected_data._mixin({"form_auth.xml":'<?xml version="1.0" encoding="UTF-8"?>\n<items>\n\t<item type="settings" position="label-left" labelWidth="80" inputWidth="180" noteWidth="180"/>\n\t<item type="fieldset" name="data" inputWidth="auto" label="Авторизация">\n\n <item type="radio" name="type" labelWidth="auto" position="label-right" checked="true" value="guest" label="Гостевой (демо) режим">\n <item type="select" name="guest" label="Роль">\n <option value="Дилер" label="Дилер"/>\n </item>\n </item>\n\n\t\t<item type="radio" name="type" labelWidth="auto" position="label-right" value="auth" label="Есть учетная запись">\n\t\t\t<item type="input" value="" name="login" label="Логин" validate="NotEmpty" />\n\t\t\t<item type="password" value="" name="password" label="Пароль" validate="NotEmpty" />\n\t\t</item>\n\n\t\t<item type="button" value="Войти" name="submit"/>\n\n <item type="template" name="text_options" className="order_dealer_options" inputWidth="170"\n value="<a href=\'#\' onclick=\'$p.iface.open_settings();\' title=\'Страница настроек программы\' > <i class=\'fa fa-cog fa-lg\'></i> Настройки </a> <a href=\'//www.oknosoft.ru/feedback\' target=\'_blank\' style=\'margin-left: 9px;\' title=\'Задать вопрос через форму обратной связи\' > <i class=\'fa fa-question-circle fa-lg\'></i> Вопрос </a>" />\n\n\t</item>\n</items>',"toolbar_add_del.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n <item id="sep0" type="separator"/>\r\n <item type="button" id="btn_add" text="<i class=\'fa fa-plus-circle fa-fw\'></i> Добавить" title="Добавить строку" />\r\n <item type="button" id="btn_delete" text="<i class=\'fa fa-times fa-fw\'></i> Удалить" title="Удалить строку" />\r\n</toolbar>',"toolbar_obj.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n <item id="sep0" type="separator"/>\r\n <item type="button" id="btn_save_close" text="<b>Записать и закрыть</b>" title="Рассчитать, записать и закрыть" />\r\n <item type="button" id="btn_save" text="<i class=\'fa fa-floppy-o fa-fw\'></i>" title="Рассчитать и записать данные"/>\r\n <item type="button" id="btn_post" enabled="false" text="<i class=\'fa fa-check-square-o fa-fw\'></i>" title="Провести документ" />\r\n <item type="button" id="btn_unpost" enabled="false" text="<i class=\'fa fa-square-o fa-fw\'></i>" title="Отмена проведения" />\r\n\r\n <item type="button" id="btn_files" text="<i class=\'fa fa-paperclip fa-fw\'></i>" title="Присоединенные файлы"/>\r\n\r\n <item type="buttonSelect" id="bs_print" text="<i class=\'fa fa-print fa-fw\'></i>" title="Печать" openAll="true">\r\n </item>\r\n\r\n <item type="buttonSelect" id="bs_create_by_virtue" text="<i class=\'fa fa-bolt fa-fw\'></i>" title="Создать на основании" openAll="true" >\r\n <item type="button" id="btn_message" enabled="false" text="Сообщение" />\r\n </item>\r\n\r\n <item type="buttonSelect" id="bs_go_to" text="<i class=\'fa fa-external-link fa-fw\'></i>" title="Перейти" openAll="true" >\r\n <item type="button" id="btn_go_connection" enabled="false" text="Связи" />\r\n </item>\r\n\r\n <item type="buttonSelect" id="bs_more" text="<i class=\'fa fa-th-large fa-fw\'></i>" title="Дополнительно" openAll="true">\r\n\r\n <item type="button" id="btn_import" text="<i class=\'fa fa-upload fa-fw\'></i> Загрузить из файла" />\r\n <item type="button" id="btn_export" text="<i class=\'fa fa-download fa-fw\'></i> Выгрузить в файл" />\r\n </item>\r\n\r\n <item id="sep1" type="separator"/>\r\n <item type="button" id="btn_close" text="<i class=\'fa fa-times fa-fw\'></i>" title="Закрыть форму"/>\r\n <item id="sep2" type="separator"/>\r\n\r\n</toolbar>\r\n',"toolbar_ok_cancel.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n <item id="btn_ok" type="button" img="" imgdis="" text="<b>Ок</b>" />\r\n <item id="btn_cancel" type="button"\timg="" imgdis="" text="Отмена" />\r\n</toolbar>',"toolbar_rep.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n <item id="sep0" type="separator"/>\r\n <item type="button" id="btn_run" text="<i class=\'fa fa-play fa-fw\'></i> Сформировать" title="Сформировать отчет"/>\r\n\r\n <item type="buttonSelect" id="bs_more" text="<i class=\'fa fa-th-large fa-fw\'></i>" title="Дополнительно" openAll="true">\r\n\r\n <item type="button" id="btn_print" text="<i class=\'fa fa-print fa-fw\'></i> Печать" />\r\n\r\n <item id="sep3" type="separator"/>\r\n\r\n <item type="button" id="btn_export" text="<i class=\'fa fa-file-excel-o fa-fw\'></i> Выгрузить в файл" />\r\n\r\n <item id="sep4" type="separator"/>\r\n\r\n <item type="button" id="btn_import" text="<i class=\'fa fa-folder-open-o fa-fw\'></i> Выбрать вариант" />\r\n <item type="button" id="btn_export" text="<i class=\'fa fa-floppy-o fa-fw\'></i> Сохранить вариант" />\r\n\r\n </item>\r\n\r\n <item id="sep1" type="separator"/>\r\n\r\n</toolbar>\r\n',"toolbar_selection.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n\r\n <item id="sep0" type="separator"/>\r\n\r\n <item id="btn_select" type="button" title="Выбрать элемент списка" text="<b>Выбрать</b>" />\r\n\r\n <item id="sep1" type="separator"/>\r\n <item id="btn_new" type="button"\ttext="<i class=\'fa fa-plus-circle fa-fw\'></i>"\ttitle="Создать" />\r\n <item id="btn_edit" type="button"\ttext="<i class=\'fa fa-pencil fa-fw\'></i>"\ttitle="Изменить" />\r\n <item id="btn_delete" type="button"\ttext="<i class=\'fa fa-times fa-fw\'></i>"\ttitle="Удалить" />\r\n <item id="sep2" type="separator"/>\r\n\r\n <item type="buttonSelect" id="bs_print" text="<i class=\'fa fa-print fa-fw\'></i> Печать" openAll="true" >\r\n </item>\r\n\r\n <item type="buttonSelect" id="bs_more" text="<i class=\'fa fa-th-large fa-fw\'></i>" title="Дополнительно" openAll="true">\r\n <item id="btn_requery" type="button"\ttext="<i class=\'fa fa-refresh fa-fw\'></i> Обновить список" />\r\n </item>\r\n\r\n <item id="sep3" type="separator"/>\r\n\r\n</toolbar>'});var xmlToJSON=function(){this.version="1.3";var e={mergeCDATA:!0,grokAttr:!0,grokText:!0,normalize:!0,xmlns:!0,namespaceKey:"_ns",textKey:"_text",valueKey:"_value",attrKey:"_attr",cdataKey:"_cdata",attrsAsObject:!0,stripAttrPrefix:!0,stripElemPrefix:!0,childrenAsArray:!0},t=new RegExp(/(?!xmlns)^.*:/),n=new RegExp(/^\s+|\s+$/g);return this.grokType=function(e){return/^\s*$/.test(e)?null:/^(?:true|false)$/i.test(e)?"true"===e.toLowerCase():isFinite(e)?parseFloat(e):e},this.parseString=function(e,t){return this.parseXML(this.stringToXML(e),t)},this.parseXML=function(a,i){for(var s in i)e[s]=i[s];var o={},r=0,l="";if(e.xmlns&&a.namespaceURI&&(o[e.namespaceKey]=a.namespaceURI),a.attributes&&a.attributes.length>0){var c={};for(r;r<a.attributes.length;r++){var p=a.attributes.item(r);m={};var d="";d=e.stripAttrPrefix?p.name.replace(t,""):p.name,e.grokAttr?m[e.valueKey]=this.grokType(p.value.replace(n,"")):m[e.valueKey]=p.value.replace(n,""),e.xmlns&&p.namespaceURI&&(m[e.namespaceKey]=p.namespaceURI),e.attrsAsObject?c[d]=m:o[e.attrKey+d]=m}e.attrsAsObject&&(o[e.attrKey]=c)}if(a.hasChildNodes())for(var u,f,m,h=0;h<a.childNodes.length;h++)u=a.childNodes.item(h),4===u.nodeType?e.mergeCDATA?l+=u.nodeValue:o.hasOwnProperty(e.cdataKey)?(o[e.cdataKey].constructor!==Array&&(o[e.cdataKey]=[o[e.cdataKey]]),o[e.cdataKey].push(u.nodeValue)):e.childrenAsArray?(o[e.cdataKey]=[],o[e.cdataKey].push(u.nodeValue)):o[e.cdataKey]=u.nodeValue:3===u.nodeType?l+=u.nodeValue:1===u.nodeType&&(0===r&&(o={}),f=e.stripElemPrefix?u.nodeName.replace(t,""):u.nodeName,m=xmlToJSON.parseXML(u),o.hasOwnProperty(f)?(o[f].constructor!==Array&&(o[f]=[o[f]]),o[f].push(m)):(e.childrenAsArray?(o[f]=[],o[f].push(m)):o[f]=m,r++));else l||(e.childrenAsArray?(o[e.textKey]=[],o[e.textKey].push(null)):o[e.textKey]=null);if(l)if(e.grokText){var _=this.grokType(l.replace(n,""));null!==_&&void 0!==_&&(o[e.textKey]=_)}else e.normalize?o[e.textKey]=l.replace(n,"").replace(/\s+/g," "):o[e.textKey]=l.replace(n,"");return o},this.xmlToString=function(e){try{var t=e.xml?e.xml:(new XMLSerializer).serializeToString(e);return t}catch(e){return null}},this.stringToXML=function(e){try{var t=null;if(window.DOMParser){var n=new DOMParser;return t=n.parseFromString(e,"text/xml")}return t=new ActiveXObject("Microsoft.XMLDOM"),t.async=!1,t.loadXML(e),t}catch(e){return null}},this}();"undefined"!=typeof module&&null!==module&&module.exports?module.exports=xmlToJSON:"function"==typeof define&&define.amd&&define(function(){return xmlToJSON});/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ -var saveAs=saveAs||function(e){"use strict";if(!("undefined"==typeof e||"undefined"!=typeof navigator&&/MSIE [1-9]\./.test(navigator.userAgent))){var t=e.document,n=function(){return e.URL||e.webkitURL||e},a=t.createElementNS("http://www.w3.org/1999/xhtml","a"),i="download"in a,s=function(e){var t=new MouseEvent("click");e.dispatchEvent(t)},o=/constructor/i.test(e.HTMLElement),r=/CriOS\/[\d]+/.test(navigator.userAgent),l=function(t){(e.setImmediate||e.setTimeout)(function(){throw t},0)},c="application/octet-stream",p=4e4,d=function(e){var t=function(){"string"==typeof e?n().revokeObjectURL(e):e.remove()};setTimeout(t,p)},u=function(e,t,n){t=[].concat(t);for(var a=t.length;a--;){var i=e["on"+t[a]];if("function"==typeof i)try{i.call(e,n||e)}catch(e){l(e)}}},f=function(e){return/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob([String.fromCharCode(65279),e],{type:e.type}):e},m=function(t,l,p){p||(t=f(t));var m,h=this,_=t.type,g=_===c,b=function(){u(h,"writestart progress write writeend".split(" "))},v=function(){if((r||g&&o)&&e.FileReader){var a=new FileReader;return a.onloadend=function(){var t=r?a.result:a.result.replace(/^data:[^;]*;/,"data:attachment/file;"),n=e.open(t,"_blank");n||(e.location.href=t),t=void 0,h.readyState=h.DONE,b()},a.readAsDataURL(t),void(h.readyState=h.INIT)}if(m||(m=n().createObjectURL(t)),g)e.location.href=m;else{var i=e.open(m,"_blank");i||(e.location.href=m)}h.readyState=h.DONE,b(),d(m)};return h.readyState=h.INIT,i?(m=n().createObjectURL(t),void setTimeout(function(){a.href=m,a.download=l,s(a),b(),d(m),h.readyState=h.DONE})):void v()},h=m.prototype,_=function(e,t,n){return new m(e,t||e.name||"download",n)};return"undefined"!=typeof navigator&&navigator.msSaveOrOpenBlob?function(e,t,n){return t=t||e.name||"download",n||(e=f(e)),navigator.msSaveOrOpenBlob(e,t)}:(h.abort=function(){},h.readyState=h.INIT=0,h.WRITING=1,h.DONE=2,h.error=h.onwritestart=h.onprogress=h.onwrite=h.onabort=h.onerror=h.onwriteend=null,_)}}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||this.content);/*! +!function(e,t){"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?module.exports=t():e.$p=t()}(this,function(){function MetaEngine(){this.__define({version:{value:"0.12.225",writable:!1},toString:{value:function(){return"Oknosoft data engine. v:"+this.version},writable:!1},utils:{value:new Utils},injected_data:{value:{},writable:!1},ajax:{value:new Ajax,writable:!1},msg:{value:new Messages,writable:!1},wsql:{value:new WSQL,writable:!1},eve:{value:new AppEvents,writable:!1},aes:{value:new Aes("metadata.js"),writable:!1},moment:{get:function(){return this.utils.moment}},_patch:{value:function(e,t){for(var n in t)"object"==typeof t[n]&&e[n]&&"object"==typeof e[n]?$p._patch(e[n],t[n]):e[n]=t[n];return e}},_find:{value:function(e,t,n){var a,i,s;if("object"!=typeof t)for(i in e){a=e[i];for(var o in a)if("function"!=typeof a[o]&&$p.utils.is_equal(a[o],t))return a}else for(i in e){a=e[i],s=!0;for(var o in t)if("function"!=typeof a[o]&&!$p.utils.is_equal(a[o],t[o])){s=!1;break}if(s)return a}}},_selection:{value:function(e,t){var n,a,i,s=!0;if(t)if("function"==typeof t)s=t.call(this,e);else for(n in t)if(a=t[n],i="object"==typeof a,"_"!=n.substr(0,1))if("function"==typeof a){if(s=a.call(this,e,n),!s)break}else if("or"==n&&Array.isArray(a)){if(s=a.some(function(t){var n=Object.keys(t)[0];return t[n].hasOwnProperty("like")?e[n]&&e[n].toLowerCase().indexOf(t[n].like.toLowerCase())!=-1:$p.utils.is_equal(e[n],t[n])}),!s)break}else if(i&&a.hasOwnProperty("like")){if(!e[n]||e[n].toLowerCase().indexOf(a.like.toLowerCase())==-1){s=!1;break}}else if(i&&a.hasOwnProperty("not")){if($p.utils.is_equal(e[n],a.not)){s=!1;break}}else if(i&&a.hasOwnProperty("in")){if(s=a.in.some(function(t){return $p.utils.is_equal(t,e[n])}),!s)break}else if(i&&a.hasOwnProperty("lt")){if(s=e[n]<a.lt,!s)break}else if(i&&a.hasOwnProperty("gt")){if(s=e[n]>a.gt,!s)break}else if(i&&a.hasOwnProperty("between")){var o=e[n];if("number"!=typeof o&&(o=$p.utils.fix_date(e[n])),s=o>=a.between[0]&&o<=a.between[1],!s)break}else if(!$p.utils.is_equal(e[n],a)){s=!1;break}return s}},_find_rows:{value:function(e,t,n){var a,i,s=[],o=0;t&&(t._top?(i=t._top,delete t._top):i=300);for(var r in e)if(a=e[r],$p._selection.call(this,a,t)){if(n){if(n.call(this,a)===!1)break}else s.push(a);if(i&&(o++,o>=i))break}return s}},on:{value:function(e,t){if("object"!=typeof e)return this.eve.attachEvent(e,t);for(var n in e)e[n]._evnts||(e[n]._evnts=[]),e[n]._evnts.push(this.eve.attachEvent(n,e[n]))}},off:{value:function(e){"function"==typeof e&&e._evnts?e._evnts.forEach(function(e){$p.eve.detachEvent(e)}):e?$p.eve.detachEvent(e):$p.eve.detachAllEvents()}},record_log:{value:function(e){$p.ireg&&$p.ireg.log&&$p.ireg.log.record(e),console.log(e)}},md:{value:new Meta},enm:{value:new function(){this.toString=function(){return $p.msg.meta_enn_mgr}}},cat:{value:new function(){this.toString=function(){return $p.msg.meta_cat_mgr}}},doc:{value:new function(){this.toString=function(){return $p.msg.meta_doc_mgr}}},ireg:{value:new function(){this.toString=function(){return $p.msg.meta_ireg_mgr}}},areg:{value:new function(){this.toString=function(){return $p.msg.meta_areg_mgr}}},accreg:{value:new function(){this.toString=function(){return $p.msg.meta_accreg_mgr}}},dp:{value:new function(){this.toString=function(){return $p.msg.meta_dp_mgr}}},rep:{value:new function(){this.toString=function(){return $p.msg.meta_reports_mgr}}},cacc:{value:new function(){this.toString=function(){return $p.msg.meta_charts_of_accounts_mgr}}},cch:{value:new function(){this.toString=function(){return $p.msg.meta_charts_of_characteristic_mgr}}},tsk:{value:new function(){this.toString=function(){return $p.msg.meta_task_mgr}}},bp:{value:new function(){this.toString=function(){return $p.msg.meta_bp_mgr}}},DataManager:{value:DataManager},RefDataManager:{value:RefDataManager},DataProcessorsManager:{value:DataProcessorsManager},EnumManager:{value:EnumManager},RegisterManager:{value:RegisterManager},InfoRegManager:{value:InfoRegManager},LogManager:{value:LogManager},MetaObjManager:{value:MetaObjManager},MetaFieldManager:{value:MetaFieldManager},SchemeSettingsManager:{value:SchemeSettingsManager},AccumRegManager:{value:AccumRegManager},CatManager:{value:CatManager},ChartOfCharacteristicManager:{value:ChartOfCharacteristicManager},ChartOfAccountManager:{value:ChartOfAccountManager},DocManager:{value:DocManager},TaskManager:{value:TaskManager},BusinessProcessManager:{value:BusinessProcessManager},DataObj:{value:DataObj},CatObj:{value:CatObj},DocObj:{value:DocObj},DataProcessorObj:{value:DataProcessorObj},TaskObj:{value:TaskObj},BusinessProcessObj:{value:BusinessProcessObj},EnumObj:{value:EnumObj},RegisterRow:{value:RegisterRow},TabularSection:{value:TabularSection},TabularSectionRow:{value:TabularSectionRow}})}function Utils(){this.moment="function"==typeof moment?moment:require("moment"),this.moment._masks={date:"DD.MM.YY",date_time:"DD.MM.YYYY HH:mm",ldt:"DD MMMM YYYY, HH:mm",iso:"YYYY-MM-DDTHH:mm:ss"},this.fix_date=function(e,t){if(e instanceof Date)return e;var n=this.moment(e,["DD-MM-YYYY","DD-MM-YYYY HH:mm","DD-MM-YYYY HH:mm:ss","DD-MM-YY HH:mm","YYYYDDMMHHmmss",this.moment.ISO_8601]);return n.isValid()?n.toDate():t?this.blank.date:e},this.fix_guid=function(e,t){if(e&&"string"==typeof e);else{if(e instanceof DataObj)return e.ref;if(e&&"object"==typeof e)if(e.presentation){if(e.ref)return e.ref;if(e.name)return e.name}else e="object"==typeof e.ref&&e.ref.hasOwnProperty("ref")?e.ref.ref:e.ref}return this.is_guid(e)||t===!1?e:t?this.generate_guid():this.blank.guid},this.fix_number=function(e,t){var n=parseFloat(e);return isNaN(n)?t?0:e:n},this.fix_boolean=function(e){return"string"==typeof e?!(!e||"false"==e.toLowerCase()):!!e},this.blank={date:this.fix_date("0001-01-01T00:00:00"),guid:"00000000-0000-0000-0000-000000000000",by_type:function(e){var t;return t=e.is_ref?this.guid:e.date_part?this.date:e.digits?0:(!e.types||"boolean"!=e.types[0])&&""}},this.fetch_type=function(e,t){var n=e;return t.is_ref?n=this.fix_guid(e):t.date_part?n=this.fix_date(e,!0):t.digits?n=this.fix_number(e,!0):"boolean"==t.types[0]&&(n=this.fix_boolean(e)),n},this.date_add_day=function(e,t,n){var a=new Date(e);return a.setDate(e.getDate()+t),n&&a.setHours(0,-a.getTimezoneOffset(),0,0),a},this.generate_guid=function(){var e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){var n=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?n:7&n|8).toString(16)})},this.is_guid=function(e){return!("string"!=typeof e||e.length<36)&&(e.length>36&&(e=e.substr(0,36)),/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(e))},this.is_empty_guid=function(e){return!e||e===this.blank.guid},this.is_data_obj=function(e){return e&&e instanceof DataObj},this.is_data_mgr=function(e){return e&&e instanceof DataManager},this.is_equal=function(e,t){return e==t||typeof e!=typeof t&&this.fix_guid(e,!1)==this.fix_guid(t,!1)},this.blob_as_text=function(e,t){return new Promise(function(n,a){var i=new FileReader;i.onload=function(e){n(i.result)},i.onerror=function(e){a(e)},"data_url"==t?i.readAsDataURL(e):i.readAsText(e)})}}function Ajax(){function e(e,t,n,a,i){return new Promise(function(s,o){if("undefined"==typeof window&&a&&a.request)a.request({url:encodeURI(t),headers:{Authorization:a.auth}},function(e,t,n){e?o(e):200!=t.statusCode?o({message:t.statusMessage,description:n,status:t.statusCode}):s({response:n})});else{var r=new XMLHttpRequest;if(window.dhx4&&window.dhx4.isIE&&(t=encodeURI(t)),a){var l,c;"object"==typeof a&&a.username&&a.hasOwnProperty("password")?(l=a.username,c=a.password):$p.ajax.username&&$p.ajax.authorized?(l=$p.ajax.username,c=$p.aes.Ctr.decrypt($p.ajax.password)):(l=$p.wsql.get_user_param("user_name"),c=$p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd")),!l&&$p.job_prm&&$p.job_prm.guest_name&&(l=$p.job_prm.guest_name,c=$p.aes.Ctr.decrypt($p.job_prm.guest_pwd))),r.open(e,t,!0,l,c),r.withCredentials=!0,r.setRequestHeader("Authorization","Basic "+btoa(unescape(encodeURIComponent(l+":"+c))))}else r.open(e,t,!0);i&&i.call(this,r),"GET"!=e?this.hide_headers||a.hide_headers||(r.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),r.setRequestHeader("X-Requested-With","XMLHttpRequest")):n=null,r.onload=function(){200==r.status&&(r.response instanceof Blob||"<!DOCTYPE"!==r.response.substr(0,9))?(void 0==r.responseURL&&(r.responseURL=t),s(r)):o(r.response?{message:r.statusText,description:r.response,status:r.status}:Error(r.statusText))},r.onerror=function(){o(Error("Network Error"))},r.send(n)}})}this.username="",this.password="",this.root=!0,this.authorized=!1,this.get=function(t){return e.call(this,"GET",t)},this.post=function(t,n){return 1==arguments.length?n="":2==arguments.length&&"function"==typeof n?(onLoad=n,n=""):n=String(n),e.call(this,"POST",t,n)},this.get_ex=function(t,n,a){return e.call(this,"GET",t,null,n,a)},this.post_ex=function(t,n,a,i){return e.call(this,"POST",t,n,a,i)},this.put_ex=function(t,n,a,i){return e.call(this,"PUT",t,n,a,i)},this.patch_ex=function(t,n,a,i){return e.call(this,"PATCH",t,n,a,i)},this.delete_ex=function(t,n,a){return e.call(this,"DELETE",t,null,n,a)},this.get_and_show_blob=function(e,t,n){function a(t){return e=window.URL.createObjectURL(t.response),i=window.open(e,"wnd_print",s),i.onload=function(t){window.URL.revokeObjectURL(e)},i}var i,s="menubar=no,toolbar=no,location=no,status=no,directories=no,resizable=yes,scrollbars=yes";return!n||"string"==typeof n&&n.toLowerCase().indexOf("post")!=-1?this.post_ex(e,"object"==typeof t?JSON.stringify(t):t,!0,function(e){e.responseType="blob"}).then(a):this.get_ex(e,!0,function(e){e.responseType="blob"}).then(a)},this.get_and_save_blob=function(e,t,n){return this.post_ex(e,"object"==typeof t?JSON.stringify(t):t,!0,function(e){e.responseType="blob"}).then(function(e){saveAs(e.response,n)})},this.default_attr=function(e,t){e.url||(e.url=t),e.username||(e.username=this.username),e.password||(e.password=this.password),e.hide_headers=!0,$p.job_prm["1c"]&&(e.auth=$p.job_prm["1c"].auth,e.request=$p.job_prm["1c"].request)}}function WSQL(){var e,t=this,n={};this.__define({js_time_diff:{value:-new Date("0001-01-01").valueOf()},time_diff:{get:function(){var e=this.get_user_param("time_diff","number");return!e||isNaN(e)||e<621355716e5||e>62135622e6?this.js_time_diff:e}},set_user_param:{value:function(t,a){var i=a;"object"==typeof a?i=JSON.stringify(a):a===!1&&(i=""),e.setItem($p.job_prm.local_storage_prefix+t,i),n[t]=a}},get_user_param:{value:function(t,a){return!n.hasOwnProperty(t)&&e&&(n[t]=this.fetch_type(e.getItem($p.job_prm.local_storage_prefix+t),a)),n[t]}},promise:{value:function(e,n){return new Promise(function(a,i){t.alasql(e,n||[],function(e,t){t?i(t):a(e)})})}},save_options:{value:function(e,n){return t.set_user_param(e+"_"+n.name,n)}},restore_options:{value:function(e,n){var a=t.get_user_param(e+"_"+n.name,"object");for(var i in a)if("object"!=typeof a[i])n[i]=a[i];else{n[i]||(n[i]={});for(var s in a[i])n[i][s]=a[i][s]}return n}},fetch_type:{value:function(e,t){if("object"==t){try{e=JSON.parse(e)}catch(t){e={}}return e}return"number"==t?$p.utils.fix_number(e,!0):"date"==t?$p.utils.fix_date(e,!0):"boolean"==t?$p.utils.fix_boolean(e):e}},alasql:{value:"undefined"!=typeof alasql?alasql:require("alasql")},init_params:{value:function(){if(!$p.job_prm.local_storage_prefix&&!$p.job_prm.create_tables)return Promise.resolve();e="undefined"==typeof localStorage?"undefined"==typeof WorkerGlobalScope?new require("node-localstorage").LocalStorage("./localstorage"):{setItem:function(e,t){},getItem:function(e){}}:localStorage;var n,a=[{p:"user_name",v:"",t:"string"},{p:"user_pwd",v:"",t:"string"},{p:"browser_uid",v:$p.utils.generate_guid(),t:"string"},{p:"zone",v:$p.job_prm.hasOwnProperty("zone")?$p.job_prm.zone:1,t:$p.job_prm.zone_is_string?"string":"number"},{p:"enable_save_pwd",v:$p.job_prm.enable_save_pwd,t:"boolean"},{p:"autologin",v:"",t:"boolean"},{p:"skin",v:"dhx_web",t:"string"},{p:"rest_path",v:"",t:"string"}];$p.job_prm.additional_params&&(a=a.concat($p.job_prm.additional_params)),e.getItem($p.job_prm.local_storage_prefix+"zone")||(n=$p.job_prm.hasOwnProperty("zone")?$p.job_prm.zone:1),$p.job_prm.url_prm.hasOwnProperty("zone")&&(n=$p.job_prm.zone_is_string?$p.job_prm.url_prm.zone:$p.utils.fix_number($p.job_prm.url_prm.zone,!0)),void 0!==n&&t.set_user_param("zone",n),a.forEach(function(e){(void 0==t.get_user_param(e.p,e.t)||!t.get_user_param(e.p,e.t)&&e.p.indexOf("url")!=-1)&&t.set_user_param(e.p,$p.job_prm.hasOwnProperty(e.p)?$p.job_prm[e.p]:e.v)});var i={path:t.get_user_param("couch_path","string")||$p.job_prm.couch_path||"",zone:t.get_user_param("zone","number"),prefix:$p.job_prm.local_storage_prefix,suffix:t.get_user_param("couch_suffix","string")||"",user_node:$p.job_prm.user_node,noreplicate:$p.job_prm.noreplicate};i.path&&(t.__define("pouch",{value:new Pouch}),t.pouch.init(i)),this.create_tables&&(this.alasq(this.create_tables,[]),this.create_tables="")}},drop_tables:{value:function(e){function n(){s--,s<=0?setTimeout(e,10):a()}function a(){var e=o[s-1].tableid;"_"==e.substr(0,1)?n():t.alasql("drop table IF EXISTS "+e,[],n)}function i(e){o=e,(s=e.length)?a():n()}var s=0,o=[];t.alasql("SHOW TABLES",[],i)}}}),this.__define({aladb:{value:new this.alasql.Database("md")}})}function Col_struct(e,t,n,a,i,s){this.id=e,this.width=t,this.type=n,this.align=a,this.sort=i,this.caption=s}function InterfaceObjs(){function e(e,t,n){if(this.layout=e.attachLayout({pattern:"2U",cells:[{id:"a",text:"Разделы",collapsed_text:"Разделы",width:220},{id:"b",text:"Раздел",header:!1}],offsets:{top:0,right:0,bottom:0,left:0}}),this.tree=this.layout.cells("a").attachTreeView(),this.tree.attachEvent("onSelect",function(e,t){if(t){var a=$p.md.mgr_by_class_name(e);a instanceof DataProcessorsManager?a.form_rep(this.layout.cells("b"),n||{hide_header:!0}):a&&a.form_list(this.layout.cells("b"),n||{hide_header:!0})}}.bind(this)),!t){var a=$p.md.get_classes();t=[];for(var i in a)a[i].length&&t.push(i)}1==t.length?$p.md.get_classes()[t[0]].forEach(function(e){var n=t[0]+"."+e,a=$p.md.get(n);a.hide||(this.tree.addItem(n,a.list_presentation||a.synonym),this.tree.setItemIcons(n,{file:"icon_1c_"+t[0]}))}.bind(this)):t.forEach(function(e){this.tree.addItem(e,$p.msg["meta_"+e]),this.tree.setItemIcons(e,{file:"icon_1c_"+e,folder_opened:"icon_1c_"+e,folder_closed:"icon_1c_"+e}),$p.md.get_classes()[e].forEach(function(t){var n=e+"."+t,a=$p.md.get(n);a.hide||(this.tree.addItem(n,a.list_presentation||a.synonym,e),this.tree.setItemIcons(n,{file:"icon_1c_"+e}))}.bind(this))}.bind(this))}function t(e){e.attachHTMLString($p.injected_data["view_settings.html"]),this.cont=e.cell.querySelector(".dhx_cell_cont_tabbar"),this.cont.style.overflow="auto",this.form2=function(e){var t=new dhtmlXForm(e,[{type:"settings",labelWidth:80,position:"label-left"},{type:"label",labelWidth:320,label:"Адрес CouchDB",className:"label_options"},{type:"input",inputWidth:220,name:"couch_path",label:"Путь:",validate:"NotEmpty"},{type:"template",label:"",value:"",note:{text:"Можно указать как относительный, так и абсолютный URL публикации CouchDB",width:320}},{type:"label",labelWidth:320,label:"Адрес http сервиса 1С",className:"label_options"},{type:"input",inputWidth:220,name:"rest_path",label:"Путь",validate:"NotEmpty"},{type:"template",label:"",value:"",note:{text:"Можно указать как относительный, так и абсолютный URL публикации 1С OData",width:320}},{type:"label",labelWidth:320,label:"Значение разделителя данных",className:"label_options"},{type:"input",inputWidth:220,name:"zone",label:"Зона:",numberFormat:["0","",""],validate:"NotEmpty,ValidInteger"},{type:"template",label:"",value:"",note:{text:"Для неразделенной публикации, зона = 0",width:320}},{type:"label",labelWidth:320,label:"Суффикс базы пользователя",className:"label_options"},{type:"input",inputWidth:220,name:"couch_suffix",label:"Суффикс:"},{type:"template",label:"",value:"",note:{text:"Назначается абоненту при регистрации",width:320}},{type:"block",blockOffset:0,name:"block_buttons",list:[{type:"button",name:"save",value:"<i class='fa fa-floppy-o fa-lg'></i>",tooltip:"Применить настройки и перезагрузить программу"},{type:"newcolumn"},{type:"button",offsetLeft:20,name:"reset",value:"<i class='fa fa-refresh fa-lg'></i>",tooltip:"Стереть справочники и перезаполнить данными сервера"}]}]);return t.cont.style.fontSize="100%",["zone","couch_path","couch_suffix","rest_path"].forEach(function(e){"zone"==e?t.setItemValue(e,$p.wsql.get_user_param(e)):t.setItemValue(e,$p.wsql.get_user_param(e)||$p.job_prm[e])}),t.attachEvent("onChange",function(e,t,n){$p.wsql.set_user_param(e,"enable_save_pwd"==e?n||"":t)}),t.disableItem("couch_suffix"),$p.job_prm.rest_path||t.disableItem("rest_path"),t.attachEvent("onButtonClick",function(e){"save"==e?($p.wsql.pouch.log_out(),setTimeout(function(){$p.eve.redirect=!0,location.reload(!0)},1e3)):"reset"==e&&dhtmlx.confirm({title:"Сброс данных",text:"Стереть справочники и перезаполнить данными сервера?",cancel:$p.msg.cancel,callback:function(e){e&&$p.wsql.pouch.reset_local_data()}})}),t}(this.cont.querySelector("[name=form2]").firstChild),this.form1=function(e){var t=new dhtmlXForm(e,[{type:"settings",labelWidth:320,position:"label-left"},{type:"label",label:"Тип устройства",className:"label_options"},{type:"block",blockOffset:0,name:"block_device_type",list:[{type:"settings",labelAlign:"left",position:"label-right"},{type:"radio",name:"device_type",labelWidth:120,label:'<i class="fa fa-desktop"></i> Компьютер',value:"desktop"},{type:"newcolumn"},{type:"radio",name:"device_type",labelWidth:150,label:'<i class="fa fa-mobile fa-lg"></i> Телефон, планшет',value:"phone"}]},{type:"template",label:"",value:"",note:{text:"Класс устройства определяется автоматически, но пользователь может задать его явно",width:320}},{type:"label",label:"Сохранять пароль пользователя",className:"label_options"},{type:"checkbox",name:"enable_save_pwd",label:"Разрешить:",labelWidth:90,checked:$p.wsql.get_user_param("enable_save_pwd","boolean")},{type:"template",label:"",value:"",note:{text:"Не рекомендуется, если к компьютеру имеют доступ посторонние лица",width:320}},{type:"template",label:"",value:"",note:{text:"",width:320}},{type:"label",label:"Подключаемые модули",className:"label_options"},{type:"input",position:"label-top",inputWidth:320,name:"modifiers",label:"Модификаторы:",value:$p.wsql.get_user_param("modifiers"),rows:3,style:"height:80px;"},{type:"template",label:"",value:"",note:{text:"Список дополнительных модулей",width:320}}]);return t.cont.style.fontSize="100%",t.checkItem("device_type",$p.job_prm.device_type),t.attachEvent("onChange",function(e,t,n){$p.wsql.set_user_param(e,"enable_save_pwd"==e?n||"":t)}),t.disableItem("modifiers"),t.getInput("modifiers").onchange=function(){$p.wsql.set_user_param("modifiers",this.value)},t}(this.cont.querySelector("[name=form1]").firstChild)}var n=this;this.clear_svgs=function(e){for("string"==typeof e&&(e=document.getElementById(e));e.firstChild;)e.removeChild(e.firstChild)},this.get_offset=function(e){var t={left:0,top:0};if(e.offsetParent)do t.left+=e.offsetLeft,t.top+=e.offsetTop;while(e=e.offsetParent);return t},this.normalize_xml=function(e){if(!e)return"";var t={"&":"&",'"':""","'":"'","<":"<",">":">"};return e.replace(/[&"'<>]/g,function(e){return t[e]})},this.scale_svg=function(e,t,n){var a,i,s,o,r,l,c,p,d,u={},m="number"==typeof t?t:t.height,f="number"==typeof t?(1.5*t).round(0):t.width,h="number"==typeof t?1/0:t.zoom||1/0;r=e.indexOf(">"),c=e.substring(5,r),s=c.split(" "),o=e.substr(r+1),o=o.substr(0,o.length-6);for(a in s)e=s[a].split("="),"width,height,x,y".indexOf(e[0])!=-1&&(e[1]=Number(e[1].replace(/"/g,"")),u[e[0]]=e[1]);(l=c.indexOf("viewBox="))!=-1?(p=c.substring(l+9),d='viewBox="'+p.substring(0,p.indexOf('"'))+'"'):d='viewBox="'+(u.x||0)+" "+(u.y||0)+" "+(u.width-n)+" "+(u.height-n)+'"';var _=u.height,g=u.width;return i=(m-n)/_,u.height=m,u.width=(g*i).round(0),u.width>f&&(i=(f-n)/g,u.height=(_*i).round(0),u.width=f),i>h&&(i=h,u.height=(_*i).round(0),u.width=(g*i).round(0)),u.x=(u.x*i).round(0),u.y=(u.y*i).round(0),'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="'+u.width+'" height="'+u.height+'" x="'+u.x+'" y="'+u.y+'" xml:space="preserve" '+d+">"+o+"</svg>"},this.bind_help=function(e,t){function n(e){if(!e.help_path)return void $p.msg.show_msg({title:"Справка",type:"alert-info",text:$p.msg.not_implemented})}e instanceof dhtmlXCellObject||(!e.help_path&&t&&(e.help_path=t),e.button("help").show(),e.button("help").enable(),e.attachEvent("onHelp",n))},this.set_hash=function(e,t,a,i){var s={},o=$p.job_prm.parse_url();1==arguments.length&&"object"==typeof e&&(s=e,s.hasOwnProperty("obj")&&(e=s.obj,delete s.obj),s.hasOwnProperty("ref")&&(t=s.ref,delete s.ref),s.hasOwnProperty("frm")&&(a=s.frm,delete s.frm),s.hasOwnProperty("view")&&(i=s.view,delete s.view)),void 0===e&&(e=o.obj||""),void 0===t&&(t=o.ref||""),void 0===a&&(a=o.frm||""),void 0===i&&(i=o.view||"");var r="obj="+e+"&ref="+t+"&frm="+a+"&view="+i;for(var l in s)r+="&"+l+"="+s[l];location.hash.substr(1)==r?n.hash_route():location.hash=r},this.hash_route=function(e){var t,a=$p.job_prm.parse_url(),i=$p.eve.callEvent("hash_route",[a]);if(i===!1||n.before_route&&n.before_route(e)===!1||$p.ajax.authorized&&(a.ref&&"undefined"!=typeof _md?(t=_md.mgr_by_class_name(a.obj),t&&t[a.frm||"form_obj"](n.docs,a.ref)):a.view&&n.swith_view&&n.swith_view(a.view)),e)return n.cancel_bubble(e)},this.cancel_bubble=function(e){var t=e||event;return t&&t.stopPropagation&&t.stopPropagation(),t&&!t.cancelBubble&&(t.cancelBubble=!0),!1},this.Col_struct=Col_struct,this.init_sidebar=function(e,t,a){n.btn_auth_sync=new n.OBtnAuthSync,n.btns_nav=function(e){return n.btn_auth_sync.bind(new n.OTooolBar({wrapper:e,class_name:"md_otbnav",width:"260px",height:"28px",top:"3px",right:"3px",name:"right",buttons:t,onclick:function(e){return n.main.cells(e).setActive(!0),!1}}))},n.main=new dhtmlXSideBar({parent:document.body,icons_path:a||"dist/imgs/",width:180,header:!0,template:"tiles",autohide:!0,items:e,offsets:{top:0,right:0,bottom:0,left:0}}),n.main.attachEvent("onSelect",function(e){var t=$p.job_prm.parse_url();t.view!=e&&n.set_hash(t.obj,t.ref,t.frm,e),n["view_"+e](n.main.cells(e))}),n.main.progressOn();var i=$p.job_prm.parse_url();i.view&&n.main.getAllItems().indexOf(i.view)!=-1?setTimeout(n.hash_route):n.set_hash(i.obj,i.ref,i.frm,"doc")},this.All_meta_objs=e,this.Setting2col=t,this.do_reload=function(){function e(){dhtmlx.confirm({title:$p.msg.file_new_date_title,text:$p.msg.file_new_date,ok:"Перезагрузка",cancel:"Продолжить",callback:function(n){n?($p.wsql.pouch.log_out(),setTimeout(function(){$p.eve.redirect=!0,location.reload(!0)},1e3)):(t++,setTimeout(e,3e4*t))}})}var t=0;e()}}function Pouch(){var e,t,n,a,i=this,s={};i.__define({DB:{value:"undefined"==typeof PouchDB?require("pouchdb-core").plugin(require("pouchdb-adapter-memory")).plugin(require("pouchdb-adapter-http")).plugin(require("pouchdb-replication")).plugin(require("pouchdb-mapreduce")):PouchDB},init:{value:function(e){s._mixin(e),s.path&&0!=s.path.indexOf("http")&&"undefined"!=typeof location&&(s.path=location.protocol+"//"+location.host+s.path)}},local:{get:function(){if(!e){var t={auto_compaction:!0,revs_limit:2};e={ram:new i.DB(s.prefix+s.zone+"_ram",t),doc:new i.DB(s.prefix+s.zone+"_doc",t),meta:new i.DB(s.prefix+"meta",t),sync:{}}}return s.path&&!e._meta&&(e._meta=new i.DB(s.path+"meta",{auth:{username:"guest",password:"meta"},skip_setup:!0}),i.run_sync(e.meta,e._meta,"meta")),e}},remote:{get:function(){return!t&&n&&(t={ram:new i.DB(s.path+s.zone+"_ram",{auth:{username:n.username,password:n.password},skip_setup:!0}),doc:new i.DB(s.path+s.zone+"_doc"+s.suffix,{auth:{username:n.username,password:n.password},skip_setup:!0})}),t}},log_in:{value:function(e,t){return void 0==e&&void 0==t&&(e=$p.job_prm.guest_name,t=$p.aes.Ctr.decrypt($p.job_prm.guest_pwd)),n?n.username==e?Promise.resolve():Promise.reject():$p.ajax.get_ex(s.path+s.zone+"_ram",{username:e,password:t}).then(function(a){return n={username:e,password:t},setTimeout(function(){dhx4.callEvent("log_in",[e])}),{ram:i.run_sync(i.local.ram,i.remote.ram,"ram"),doc:i.run_sync(i.local.doc,i.remote.doc,"doc")}})}},log_out:{value:function(){if(n){if(e.sync.doc)try{e.sync.doc.cancel()}catch(e){}if(e.sync.ram)try{e.sync.ram.cancel()}catch(e){}n=null}t&&t.ram&&delete t.ram,t&&t.doc&&delete t.doc,t=null,dhx4.callEvent("log_out")}},reset_local_data:{value:function(){var e=i.local.ram.destroy.bind(i.local.ram),t=i.local.doc.destroy.bind(i.local.doc),n=function(){setTimeout(function(){$p.eve.redirect=!0,location.reload(!0)},1e3)};i.log_out(),setTimeout(function(){e().then(t).catch(t).then(n).catch(n)},1e3)}},load_data:{value:function(){var e={limit:800,include_docs:!0},t={total_rows:0,limit:e.limit,page:0,start:Date.now()};return new Promise(function(n,s){function o(){i.local.ram.allDocs(e,function(r,l){l?(t.page++,t.total_rows=l.total_rows,t.duration=Date.now()-t.start,$p.eve.callEvent("pouch_load_data_page",[t]),i.load_changes(l,e)?o():(n(),a=!0,$p.eve.callEvent("pouch_load_data_loaded",[t]),t.note="pouch_load_data_loaded",$p.record_log(t))):r&&(s(r),$p.eve.callEvent("pouch_load_data_error",[r]))})}i.local.ram.info().then(function(e){e.doc_count>=($p.job_prm.pouch_ram_doc_count||10)?($p.eve.callEvent("pouch_load_data_start",[t]),o()):($p.eve.callEvent("pouch_load_data_error",[e]),s(e))})})}},authorized:{get:function(){return n&&n.username}},data_loaded:{get:function(){return!!a}},run_sync:{value:function(t,n,s){var o,r;return t.info().then(function(e){return o=e,n.info()}).then(function(e){return"ram"!=s?e:n.get("data_version").then(function(t){return t.version!=$p.wsql.get_user_param("couch_ram_data_version")&&($p.wsql.get_user_param("couch_ram_data_version")&&(e=i.reset_local_data()),$p.wsql.set_user_param("couch_ram_data_version",t.version)),e}).catch(function(e){$p.record_log(e)}).then(function(){return e})}).then(function(l){if(l){"ram"==s&&o.doc_count<($p.job_prm.pouch_ram_doc_count||10)?(r={total_rows:l.doc_count,local_rows:o.doc_count,docs_written:0,limit:200,page:0,start:Date.now()},$p.eve.callEvent("pouch_load_data_start",[r])):"doc"==s&&setTimeout(function(){$p.eve.callEvent("pouch_doc_sync_start")});var c={live:!0,retry:!0,batch_size:300,batches_limit:8};return"meta"==s?c.filter="auth/meta":$p.job_prm.pouch_filter&&$p.job_prm.pouch_filter[s]&&(c.filter=$p.job_prm.pouch_filter[s]),"ram"==s||"meta"==s||$p.wsql.get_user_param("zone")==$p.job_prm.zone_demo?e.sync[s]=t.replicate.from(n,c):e.sync[s]=t.sync(n,c),e.sync[s].on("change",function(e){"ram"==s?(i.load_changes(e),o.doc_count<($p.job_prm.pouch_ram_doc_count||10)&&(r.page++,r.docs_written=e.docs_written,r.duration=Date.now()-r.start,$p.eve.callEvent("pouch_load_data_page",[r]),r.docs_written>=r.total_rows&&(a=!0,$p.eve.callEvent("pouch_load_data_loaded",[r]),r.note="pouch_load_data_loaded",$p.record_log(r)))):(e.update_only=!0,i.load_changes(e)),$p.eve.callEvent("pouch_change",[s,e])}).on("paused",function(e){e&&$p.eve.callEvent("pouch_paused",[s,e])}).on("active",function(e){$p.eve.callEvent("pouch_active",[s,e])}).on("denied",function(e){$p.eve.callEvent("pouch_denied",[s,e])}).on("complete",function(e){$p.eve.callEvent("pouch_complete",[s,e])}).on("error",function(e){$p.eve.callEvent("pouch_error",[s,e])}),e.sync[s]}})}},load_obj:{value:function(e){return e._manager.pouch_db.get(e._manager.class_name+"|"+e.ref).then(function(t){delete t._id,delete t._rev,e._mixin(t)._set_loaded()}).catch(function(e){if(404!=e.status)throw e}).then(function(t){return e})}},save_obj:{value:function(e,t){var n=e._obj._clone(),a=t.db||e._manager.pouch_db;return n._id=e._manager.class_name+"|"+e.ref,delete n.ref,t.attachments&&(n._attachments=t.attachments),(e.is_new()?Promise.resolve():a.get(n._id)).then(function(e){if(e){n._rev=e._rev;for(var t in e._attachments)n._attachments||(n._attachments={}),n._attachments[t]||(n._attachments[t]=e._attachments[t])}}).catch(function(e){if(404!=e.status)throw e}).then(function(){return a.put(n)}).then(function(){if(e.is_new()&&e._set_loaded(e.ref),n._attachments){e._attachments||(e._attachments={});for(var a in n._attachments)e._attachments[a]&&n._attachments[a].stub||(e._attachments[a]=n._attachments[a])}return n=null,t=null,e})}},load_changes:{value:function(e,t){var n,a,i,s,o={};if(t)n=e.rows;else if(e.direction){if("pull"!=e.direction)return;n=e.change.docs}else n=e.docs;if(n.length>0){t&&(t.startkey=n[n.length-1].key,t.skip=1),n.forEach(function(e){if(a=t?e.doc:e,!a)if(e.value&&e.value.deleted)a={_id:e.id,_deleted:!0};else if(e.error)return;s=a._id.split("|"),i=s[0].split("."),a.ref=s[1],delete a._id,delete a._rev,o[i[0]]||(o[i[0]]={}),o[i[0]][i[1]]||(o[i[0]][i[1]]=[]),o[i[0]][i[1]].push(a)});for(var r in o)for(i in o[r])$p[r]&&$p[r][i]&&$p[r][i].load_array(o[r][i],!e.update_only||"update_only");return o=e=n=a=null,!0}return!1}},backup_database:{value:function(e){}},restore_database:{value:function(e){}}})}function Messages(){this.toString=function(){return"Интернационализация сообщений"},"undefined"!=typeof window&&"dhtmlx"in window&&(this.show_msg=function(e,t){if(e){if("string"==typeof e){if($p.iface.synctxt)return void $p.iface.synctxt.show_message(e);e={type:"info",text:e}}t&&"function"==typeof t.setText&&t.setText(e.text),dhtmlx.message(e)}},this.check_soap_result=function(e){return e?"limit_query"==e.error?($p.iface.docs.progressOff(),$p.msg.show_msg({type:"alert-warning",text:$p.msg.limit_query.replace("%1",e.queries).replace("%2",e.queries_avalable),title:$p.msg.srv_overload}),!0):"network"==e.error||"empty"==e.error?($p.iface.docs.progressOff(),$p.msg.show_msg({type:"alert-warning",text:$p.msg.error_network,title:$p.msg.error_critical}),!0):e.error&&e.error_description?($p.iface.docs.progressOff(),e.error_description.indexOf("Недостаточно прав")!=-1&&(e.error_type="alert-warning",e.error_title=$p.msg.error_rights),$p.msg.show_msg({type:e.error_type||"alert-error",text:e.error_description,title:e.error_title||$p.msg.error_critical}),!0):e.error&&!e.messages?($p.iface.docs.progressOff(),$p.msg.show_msg({type:"alert-error",title:$p.msg.error_critical,text:$p.msg.unknown_error.replace("%1","unknown_error")}),!0):void 0:($p.msg.show_msg({type:"alert-error",text:$p.msg.empty_response,title:$p.msg.error_critical}),!0)},this.show_not_implemented=function(){$p.msg.show_msg({type:"alert-warning",text:$p.msg.not_implemented,title:$p.msg.main_title})})}function Meta(){function e(e){return e.info().then(function(){return e.get("meta")}).then(function(n){return $p._patch(t,n),n=null,e.get("meta_patch")}).then(function(e){return $p._patch(t,e),e=null,delete t._id,delete t._rev,t})}var t={enm:{accumulation_record_type:[{order:0,name:"debit",synonym:"Приход"},{order:1,name:"credit",synonym:"Расход"}],comparison_types:[{order:0,name:"gt",synonym:"Больше"},{order:1,name:"gte",synonym:"Больше или равно"},{order:2,name:"lt",synonym:"Меньше"},{order:3,name:"lte",synonym:"Меньше или равно "},{order:4,name:"eq",synonym:"Равно"},{order:5,name:"ne",synonym:"Не равно"},{order:6,name:"in",synonym:"В списке"},{order:7,name:"nin",synonym:"Не в списке"},{order:8,name:"lke",synonym:"Подобно "},{order:9,name:"nlk",synonym:"Не подобно"}]},cat:{meta_objs:{},meta_fields:{},scheme_settings:{name:"scheme_settings",splitted:!0,synonym:"Настройки отчетов и списков",illustration:"",obj_presentation:"",list_presentation:"",input_by_string:["name"],hierarchical:!1,has_owners:!1,group_hierarchy:!0,main_presentation_name:!0,code_length:0,fields:{obj:{synonym:"Объект",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:250}},user:{synonym:"Пользователь",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:50}},predefined_name:{synonym:"",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:256}}},tabular_sections:{ +available_fields:{name:"available_fields",synonym:"Доступные поля",tooltip:"Состав, порядок и ширина колонок",fields:{parent:{synonym:"Родитель",multiline_mode:!1,tooltip:"Для плоского списка, родитель пустой",type:{types:["string"],str_len:100}},use:{synonym:"Использование",multiline_mode:!1,tooltip:"",type:{types:["boolean"]}},field:{synonym:"Поле",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}},width:{synonym:"Ширина",multiline_mode:!1,tooltip:"",type:{types:["number"],digits:6,fraction_figits:0}},caption:{synonym:"Заголовок",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}}}},sort_fields:{name:"sort_fields",synonym:"Поля сортировки",tooltip:"",fields:{parent:{synonym:"Родитель",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}},field:{synonym:"Поле",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}}}},grouping_fields:{name:"grouping_fields",synonym:"Поля группировки",tooltip:"",fields:{parent:{synonym:"Родитель",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}},field:{synonym:"Поле",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}}}},selection:{name:"selection",synonym:"Отбор",tooltip:"",fields:{parent:{synonym:"Родитель",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}},use:{synonym:"Использование",multiline_mode:!1,tooltip:"",type:{types:["boolean"]}},left_value:{synonym:"Левое значение",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}},comparison_type:{synonym:"Вид сравнения",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}},right_value:{synonym:"Правое значение",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:100}}}},scheme:{name:"scheme",synonym:"Структура",tooltip:"",fields:{parent:{synonym:"Родитель",multiline_mode:!1,tooltip:"",type:{types:["string"],str_len:10}},kind:{synonym:"Вид раздела отчета",multiline_mode:!1,tooltip:"список, таблица, группировка строк, группировка колонок",type:{types:["string"],str_len:10}}}}},cachable:"doc"}},doc:{},ireg:{log:{name:"log",note:"",synonym:"Журнал событий",dimensions:{date:{synonym:"Дата",multiline_mode:!1,tooltip:"Время события",type:{types:["number"],digits:15,fraction_figits:0}},sequence:{synonym:"Порядок",multiline_mode:!1,tooltip:"Порядок следования",type:{types:["number"],digits:6,fraction_figits:0}}},resources:{class:{synonym:"Класс",multiline_mode:!1,tooltip:"Класс события",type:{types:["string"],str_len:100}},note:{synonym:"Комментарий",multiline_mode:!0,tooltip:"Текст события",type:{types:["string"],str_len:0}},obj:{synonym:"Объект",multiline_mode:!0,tooltip:"Объект, к которому относится событие",type:{types:["string"],str_len:0}}}}},areg:{},dp:{},rep:{},cch:{},cacc:{}};_md=this,_md.create_managers=function(){},_md.init=function(n){function a(){return!n||i||s?e(n||$p.wsql.pouch.local.meta).then(function(){return i?void _md.create_managers():t}).catch($p.record_log):($p._patch(t,n),n=null,_md.create_managers(),void 0)}var i=!n||$p.wsql.pouch&&n==$p.wsql.pouch.local.meta,s=n&&$p.wsql.pouch&&n==$p.wsql.pouch.local._meta;return $p.on("pouch_change",function(e,n){"meta"==e&&(t?$p.iface&&$p.iface.do_reload&&setTimeout(function(){$p.iface.do_reload()},3e3):a())}),a()},_md.get=function(e,n){var a=e.split(".");if(!n)return t[a[0]][a[1]];var i={multiline_mode:!1,note:"",synonym:"",tooltip:"",type:{is_ref:!1,types:["string"]}},s="doc,tsk,bp".indexOf(a[0])!=-1,o="cat,cch,cacc,tsk".indexOf(a[0])!=-1;return s&&"number_doc"==n?(i.synonym="Номер",i.tooltip="Номер документа",i.type.str_len=11):s&&"date"==n?(i.synonym="Дата",i.tooltip="Дата документа",i.type.date_part="date_time",i.type.types[0]="date"):s&&"posted"==n?(i.synonym="Проведен",i.type.types[0]="boolean"):o&&"id"==n?i.synonym="Код":o&&"name"==n?i.synonym="Наименование":"_deleted"==n?(i.synonym="Пометка удаления",i.type.types[0]="boolean"):"is_folder"==n?(i.synonym="Это группа",i.type.types[0]="boolean"):"ref"==n?(i.synonym="Ссылка",i.type.is_ref=!0,i.type.types[0]=e):i=n?t[a[0]][a[1]].fields[n]:t[a[0]][a[1]],i},_md.get_classes=function(){var e={};for(var n in t){e[n]=[];for(var a in t[n])e[n].push(a)}return e},_md.sql_type=function(e,t,n,a){var i;return i="type"==t&&"cch_properties"==e.table_name||"svg"==t&&"cat_production_params"==e.table_name?" JSON":n.is_ref||n.types.indexOf("guid")!=-1?a?n.types.every(function(e){return 0==e.indexOf("enm.")})?" character varying(100)":n.hasOwnProperty("str_len")?" character varying("+Math.max(36,n.str_len)+")":" uuid":" CHAR":n.hasOwnProperty("str_len")?a?n.str_len?" character varying("+n.str_len+")":" text":" CHAR":n.date_part?a&&"date"!=n.date_part?"date_time"==n.date_part?" timestamp with time zone":" time without time zone":" Date":n.hasOwnProperty("digits")?0==n.fraction_figits?a?n.digits<7?" integer":" bigint":" INT":a?" numeric("+n.digits+","+n.fraction_figits+")":" FLOAT":n.types.indexOf("boolean")!=-1?" BOOLEAN":n.types.indexOf("json")!=-1?" JSON":a?" character varying(255)":" CHAR"},_md.sql_composite=function(e,t,n,a){var i="";return e[t].type.types.length>1&&"type"!=t&&(n=n?n.substr(0,29)+"_T":t.substr(0,29)+"_T",i=a?', "'+n+'" character varying(255)':_md.sql_mask(n)+" CHAR"),i},_md.sql_mask=function(e,t){return", "+(t?"_t_.":"")+("`"+e+"`")},_md.mgr_by_class_name=function(e){if(e){var t=e.split(".");if(t[1]&&$p[t[0]])return $p[t[0]][t[1]]}},_md.value_mgr=function(e,t,n,a,i){function s(e){return e&&1==n.types.length&&(n._mgr=e),e}var o,r,l,c,p;if(n._mgr)return n._mgr;if(1==n.types.length){if(l=n.types[0].split("."),l.length>1&&$p[l[0]])return s($p[l[0]][l[1]])}else if(i&&i.type&&(l=i.type.split("."),l.length>1&&$p[l[0]]))return s($p[l[0]][l[1]]);if(o=e.property||e.param,"value"==t&&o){if($p.utils.is_data_obj(o))r=o;else{if(!$p.utils.is_guid(o))return;r=$p.cch.properties.get(o,!1)}if($p.utils.is_data_obj(r)){if(r.is_new())return $p.cat.property_values;if(c=[],r.type.types.forEach(function(e){l=e.split("."),l.length>1&&$p[l[0]][l[1]]&&c.push($p[l[0]][l[1]])}),1==c.length||e[t]==$p.utils.blank.guid)return s(c[0]);if(a)return c;if((o=e[t])instanceof DataObj)return o._manager;if($p.utils.is_guid(o)&&o!=$p.utils.blank.guid)for(var d in c)if(p=c[d],p.get(o,!1,!0))return p}}else{if(c=[],n.types.forEach(function(e){l=e.split("."),l.length>1&&$p[l[0]][l[1]]&&c.push($p[l[0]][l[1]])}),1==c.length||e[t]==$p.utils.blank.guid)return s(c[0]);if(a)return c;if((o=e[t])instanceof DataObj)return o._manager;if($p.utils.is_guid(o)&&o!=$p.utils.blank.guid)for(var d in c)if(p=c[d],p.get(o,!1,!0))return p}},_md.control_by_type=function(e,t){var n;return n="boolean"==typeof t&&e.types.indexOf("boolean")!=-1?"ch":"number"==typeof t&&e.digits?e.fraction_figits<5?"calck":"edn":t instanceof Date&&e.date_part?"dhxCalendar":e.is_ref?"ocombo":e.date_part?"dhxCalendar":e.digits?e.fraction_figits<5?"calck":"edn":"boolean"==e.types[0]?"ch":e.hasOwnProperty("str_len")&&(e.str_len>=100||0==e.str_len)?"txt":"ed"},_md.ts_captions=function(e,t,n){n||(n={});var a,i=_md.get(e).tabular_sections[t],s=_md.get(e).form,o=i.fields;if(s&&s.obj){if(!s.obj.tabular_sections[t])return;n._mixin(s.obj.tabular_sections[t])}else{"contact_information"===t&&(o={type:"",kind:"",presentation:""}),n.fields=["row"],n.headers="№",n.widths="40",n.min_widths="",n.aligns="",n.sortings="na",n.types="cntr";for(var r in o)a=i.fields[r],a.hide||(n.fields.push(r),n.headers+=","+(a.synonym?a.synonym.replace(/,/g," "):r),n.types+=","+_md.control_by_type(a.type),n.sortings+=",na")}return!0},_md.syns_js=function(e){var n={DeletionMark:"_deleted",Description:"name",DataVersion:"data_version",IsFolder:"is_folder",Number:"number_doc",Date:"date","Дата":"date",Posted:"posted",Code:"id",Parent_Key:"parent",Owner_Key:"owner",Owner:"owner",Ref_Key:"ref","Ссылка":"ref",LineNumber:"row"};return n[e]?n[e]:t.syns_js[t.syns_1с.indexOf(e)]||e},_md.syns_1с=function(e){var n={_deleted:"DeletionMark",name:"Description",is_folder:"IsFolder",number_doc:"Number",date:"Date",posted:"Posted",id:"Code",ref:"Ref_Key",parent:"Parent_Key",owner:"Owner_Key",row:"LineNumber"};return n[e]?n[e]:t.syns_1с[t.syns_js.indexOf(e)]||e},_md.printing_plates=function(e){if(e)for(var n in e.doc)t.doc[n].printing_plates=e.doc[n]},_md.class_name_from_1c=function(e){var t=e.split(".");return 1==t.length?"enm."+e:("Перечисление"==t[0]?e="enm.":"Справочник"==t[0]?e="cat.":"Документ"==t[0]?e="doc.":"РегистрСведений"==t[0]?e="ireg.":"РегистрНакопления"==t[0]?e="areg.":"РегистрБухгалтерии"==t[0]?e="accreg.":"ПланВидовХарактеристик"==t[0]?e="cch.":"ПланСчетов"==t[0]?e="cacc.":"Обработка"==t[0]?e="dp.":"Отчет"==t[0]&&(e="rep."),e+_md.syns_js(t[1]))},_md.class_name_to_1c=function(e){var t=e.split(".");return 1==t.length?"Перечисление."+e:("enm"==t[0]?e="Перечисление.":"cat"==t[0]?e="Справочник.":"doc"==t[0]?e="Документ.":"ireg"==t[0]?e="РегистрСведений.":"areg"==t[0]?e="РегистрНакопления.":"accreg"==t[0]?e="РегистрБухгалтерии.":"cch"==t[0]?e="ПланВидовХарактеристик.":"cacc"==t[0]?e="ПланСчетов.":"dp"==t[0]?e="Обработка.":"rep"==t[0]&&(e="Отчет."),e+_md.syns_1с(t[1]))},_md.create_tables=function(e,t){function n(){s--,0==s?e?e(l):alasql.utils.saveFile("create_tables.sql",l):a()}function a(){var e=o[s-1];l+=e.class[e.name].get_sql_struct(t)+"; ",n()}var i,s=0,o=[],r=_md.get_classes(),l=t&&t.postgres?"":"USE md; ";"enm,cch,cacc,cat,bp,tsk,doc,ireg,areg".split(",").forEach(function(e){for(i in r[e])o.push({class:$p[e],name:r[e][i]})}),s=o.length,a()}}function DataManager(e){var t=_md.get(e),n={after_create:[],after_load:[],before_save:[],after_save:[],value_change:[],add_row:[],del_row:[]};this.__define({cachable:{get:function(){return e.indexOf("enm.")!=-1?"ram":t.cachable?t.cachable:e.indexOf("doc.")!=-1||e.indexOf("dp.")!=-1||e.indexOf("rep.")!=-1?"doc":"ram"}},class_name:{value:e,writable:!1},alatable:{get:function(){return $p.wsql.aladb.tables[this.table_name]?$p.wsql.aladb.tables[this.table_name].data:[]}},metadata:{value:function(e){return e?t.fields[e]||t.tabular_sections[e]:t}},on:{value:function(e,t){if("object"==typeof e)for(var a in e)e.hasOwnProperty(a)&&n[a].push(e[a]);else n[e].push(t)}},off:{value:function(e,t){}},handle_event:{value:function(e,t,a){var i,s=[];return n[t].forEach(function(t){s!==!1&&(i=t.call(e,a),i===!1?s=i:i&&s.push(i))}),s===!1?s:s.length?1==s.length?s[0]:s.some(function(e){return"object"==typeof e&&e.then})?Promise.all(s):s:void 0}},by_ref:{value:{}}})}function RefDataManager(e){RefDataManager.superclass.constructor.call(this,e)}function DataProcessorsManager(e){DataProcessorsManager.superclass.constructor.call(this,e)}function EnumManager(e){EnumManager.superclass.constructor.call(this,e);var t=$p.md.get(e);for(var n in t)new EnumObj(t[n],this)}function RegisterManager(e){RegisterManager.superclass.constructor.call(this,e),this.push=function(e,t){t&&t!=e.ref?(delete this.by_ref[e.ref],this.by_ref[t]=e):this.by_ref[e.ref]=e},this.get=function(e,t,n){if(e?"string"==typeof e&&(e={ref:e}):e={},e.ref&&n)return t?Promise.resolve(this.by_ref[e.ref]):this.by_ref[e.ref];e.action="select";var a,i=$p.wsql.alasql(this.get_sql_struct(e),e._values);if(delete e.action,delete e._values,i.length)if(n)a=this.by_ref[this.get_ref(i[0])];else{a=[];for(var s in i)a.push(this.by_ref[this.get_ref(i[s])])}return t?Promise.resolve(a):a},this.unload_obj=function(e){delete this.by_ref[e],this.alatable.some(function(t,n,a){if(t.ref==e)return a.splice(n,1),!0})},this.load_array=function(e,t){for(var n,a,i=[],s=0;s<e.length;s++){if(n=this.get_ref(e[s]),a=this.by_ref[n],a||e[s]._deleted){if(a&&e[s]._deleted){a.unload();continue}(a.is_new()||t)&&(a._mixin(e[s]),a._set_loaded())}else a=new($p[this.obj_constructor()])(e[s],this),t&&a._set_loaded();i.push(a)}return i}}function InfoRegManager(e){InfoRegManager.superclass.constructor.call(this,e)}function AccumRegManager(e){AccumRegManager.superclass.constructor.call(this,e)}function CatManager(e){CatManager.superclass.constructor.call(this,e),this.metadata().hierarchical&&this.metadata().group_hierarchy&&$p[this.obj_constructor()].prototype.__define("is_folder",{get:function(){return this._obj.is_folder||!1},set:function(e){this._obj.is_folder=$p.utils.fix_boolean(e)},enumerable:!0,configurable:!0})}function ChartOfCharacteristicManager(e){ChartOfCharacteristicManager.superclass.constructor.call(this,e)}function ChartOfAccountManager(e){ChartOfAccountManager.superclass.constructor.call(this,e)}function DocManager(e){DocManager.superclass.constructor.call(this,e)}function TaskManager(e){TaskManager.superclass.constructor.call(this,e)}function BusinessProcessManager(e){BusinessProcessManager.superclass.constructor.call(this,e)}function LogManager(){LogManager.superclass.constructor.call(this,"ireg.log");var e;this.__define({record:{value:function(t){t instanceof Error?(console&&console.log(t),t={class:"error",note:t.toString()}):"object"!=typeof t||t.class||t.obj?"object"!=typeof t&&(t={note:t}):t={class:"obj",obj:t,note:t.note},t.date=Date.now()+$p.wsql.time_diff,e||(e=alasql.compile("select MAX(`sequence`) as `sequence` from `ireg_log` where `date` = ?"));var n=e([t.date]);n.length&&void 0!==n[0].sequence?t.sequence=parseInt(n[0].sequence)+1:t.sequence=0,t.class||(t.class="note"),$p.wsql.alasql("insert into `ireg_log` (`ref`, `date`, `sequence`, `class`, `note`, `obj`) values (?,?,?,?,?,?)",[t.date+"¶"+t.sequence,t.date,t.sequence,t.class,t.note,t.obj?JSON.stringify(t.obj):""])}},backup:{value:function(e,t){}},restore:{value:function(e,t){}},clear:{value:function(e,t){}},show:{value:function(e){}},get:{value:function(e,t,n){if("object"==typeof e&&(e=e.ref||""),!this.by_ref[e]){if(t===!1)return;var a=e.split("¶");$p.wsql.alasql("select * from `ireg_log` where date="+a[0]+" and sequence="+a[1]).forEach(function(e){new RegisterRow(e,this)}.bind(this))}return t?Promise.resolve(this.by_ref[e]):this.by_ref[e]}},get_sql_struct:{value:function(e){if(e&&"get_selection"==e.action){var t="select * from `ireg_log`";return e.date_from?t+=e.date_till?" where `date` >= ? and `date` <= ?":" where `date` >= ?":e.date_till&&(t+=" where `date` <= ?"),t}return LogManager.superclass.get_sql_struct.call(this,e)}},caption_flds:{value:function(e){var t='<column id="%1" width="%2" type="%3" align="%4" sort="%5">%6</column>',n=[],a="";if(n.push(new Col_struct("date","200","ro","left","server","Дата")),n.push(new Col_struct("class","100","ro","left","server","Класс")),n.push(new Col_struct("note","*","ro","left","server","Событие")),e.get_header){a="<head>";for(var i in n)a+=t.replace("%1",n[i].id).replace("%2",n[i].width).replace("%3",n[i].type).replace("%4",n[i].align).replace("%5",n[i].sort).replace("%6",n[i].caption);a+="</head>"}return{head:a,acols:n}}},data_to_grid:{value:function(e,t){var n="<?xml version='1.0' encoding='UTF-8'?><rows total_count='%1' pos='%2' set_parent='%3'>".replace("%1",e.length).replace("%2",t.start).replace("%3",t.set_parent||""),a=this.caption_flds(t);return n+=a.head,e.forEach(function(e){n+='<row id="'+e.ref+'"><cell>'+$p.moment(e.date-$p.wsql.time_diff).format("DD.MM.YYYY HH:mm:ss")+"."+e.sequence+"</cell><cell>"+(e.class||"")+"</cell><cell>"+(e.note||"")+"</cell></row>"}),n+"</rows>"}}})}function MetaObjManager(){MetaObjManager.superclass.constructor.call(this,"cat.meta_objs")}function MetaFieldManager(){MetaFieldManager.superclass.constructor.call(this,"cat.meta_fields")}function SchemeSettingsManager(){SchemeSettingsManager.superclass.constructor.call(this,"cat.scheme_settings")}function DataObj(e,t){var n,a={},i={},s={_is_new:!(this instanceof EnumObj)};return t instanceof DataProcessorsManager||t instanceof EnumManager||(n=t.get(e,!1,!0)),n?(e=null,n):(t instanceof EnumManager?i.ref=e.name:t instanceof RegisterManager?i.ref=t.get_ref(e):i.ref=$p.utils.fix_guid(e),this.__define({_obj:{value:i,configurable:!0},_ts_:{value:function(e){return a[e]||(a[e]=new TabularSection(e,this)),a[e]},configurable:!0},_manager:{value:t},_data:{value:s,configurable:!0}}),t.alatable&&t.push&&(t.alatable.push(i),t.push(this,i.ref)),void(e=null))}function CatObj(e,t){var n="";CatObj.superclass.constructor.call(this,e,t),this.__define("presentation",{get:function(){return this.name||this.id?this.name||this.id||this._metadata.obj_presentation||this._metadata.synonym:n},set:function(e){e&&(n=String(e))}}),e&&"object"==typeof e&&(e._not_set_loaded?(delete e._not_set_loaded,this._mixin(e)):(this._mixin(e),$p.utils.is_empty_guid(this.ref)||!e.id&&!e.name||this._set_loaded(this.ref))),e=null}function DocObj(e,t){var n="";DocObj.superclass.constructor.call(this,e,t),this.__define("presentation",{get:function(){return this.number_doc?(this._metadata.obj_presentation||this._metadata.synonym)+" №"+this.number_doc+" от "+$p.moment(this.date).format($p.moment._masks.ldt):n},set:function(e){e&&(n=String(e))}}),e&&"object"==typeof e&&this._mixin(e),!$p.utils.is_empty_guid(this.ref)&&e.number_doc&&this._set_loaded(this.ref),e=null}function doc_props_date_number(e){e.__define({number_doc:{get:function(){return this._obj.number_doc||""},set:function(e){this.__notify("number_doc"),this._obj.number_doc=e},enumerable:!0},date:{get:function(){return this._obj.date||$p.utils.blank.date},set:function(e){this.__notify("date"),this._obj.date=$p.utils.fix_date(e,!0)},enumerable:!0}})}function DataProcessorObj(e,t){DataProcessorObj.superclass.constructor.call(this,e,t);var n,a=t.metadata();for(n in a.fields)e[n]=$p.utils.fetch_type("",a.fields[n].type);for(n in a.tabular_sections)e[n]=[];this._mixin(e)}function TaskObj(e,t){TaskObj.superclass.constructor.call(this,e,t)}function BusinessProcessObj(e,t){BusinessProcessObj.superclass.constructor.call(this,e,t)}function EnumObj(e,t){EnumObj.superclass.constructor.call(this,e,t),e&&"object"==typeof e&&this._mixin(e)}function RegisterRow(e,t){RegisterRow.superclass.constructor.call(this,e,t),e&&"object"==typeof e&&this._mixin(e);for(var n in t.metadata().dimensions)if(!e.hasOwnProperty(n)&&e.ref){var a=e.ref.split("¶");Object.keys(t.metadata().dimensions).forEach(function(e,t){this[e]=a[t]}.bind(this));break}}function TabularSection(e,t){t._obj[e]||(t._obj[e]=[]),this.__define("_name",{value:e,enumerable:!1}),this.__define("_owner",{value:t,enumerable:!1}),this.__define("_obj",{value:t._obj[e],writable:!1,enumerable:!1})}function TabularSectionRow(e){var t={};this.__define("_owner",{value:e,enumerable:!1}),this.__define("_obj",{value:t,writable:!1,enumerable:!1})}function Rest(){this.filter_date=function(e,t,n){t||(t=new Date("2015-01-01"));var a=e+" gt datetime'"+$p.moment(t).format($p.moment._masks.iso)+"'";return n&&(a+=" and "+e+" lt datetime'"+$p.moment(n).format($p.moment._masks.iso)+"'"),a},this.to_data=function(e,t){var n,a,i,s,o,r,l={},c=t.metadata(),p=c.fields,d=c.tabular_sections;t instanceof RefDataManager?(e.hasOwnProperty("DeletionMark")&&(l._deleted=e.DeletionMark),e.hasOwnProperty("DataVersion"),e.hasOwnProperty("Ref_Key")&&(l.ref=e.Ref_Key)):p={}._mixin(c.dimensions)._mixin(c.resources)._mixin(c.attributes),t instanceof DocManager?(e.hasOwnProperty("Number")?l.number_doc=e.Number||e.number_doc:e.hasOwnProperty("number_doc")&&(l.number_doc=e.number_doc),e.hasOwnProperty("Date")?l.date=e.Date:e.hasOwnProperty("date")&&(l.date=e.date),e.hasOwnProperty("Posted")?l.posted=e.Posted:e.hasOwnProperty("posted")&&(l.posted=e.posted)):(c.main_presentation_name&&(e.hasOwnProperty("Description")?l.name=e.Description:e.hasOwnProperty("name")&&(l.name=e.name)),c.code_length&&(e.hasOwnProperty("Code")?l.id=e.Code:e.hasOwnProperty("id")&&(l.id=e.id)));for(a in p)if(e.hasOwnProperty(a))l[a]=e[a];else{if(o=_md.syns_1с(a),o.indexOf("_Key")==-1&&p[a].type.is_ref&&e[o+"_Key"]&&(o+="_Key"),!e.hasOwnProperty(o))continue;l[a]=e[o]}for(n in d)r="extra_fields"==n||e.hasOwnProperty(n)?n:_md.syns_1с(n),e.hasOwnProperty(r)&&(l[n]=[],e[r]&&(e[r].sort(function(e,t){return(e.LineNumber||e.row)>(t.LineNumber||t.row)}),e[r].forEach(function(e){s={};for(i in d[n].fields)o=e.hasOwnProperty(i)||"extra_fields"==n&&("property"==i||"value"==i)?i:_md.syns_1с(i),o.indexOf("_Key")==-1&&d[n].fields[i].type.is_ref&&e[o+"_Key"]&&(o+="_Key"),s[i]=e[o];l[n].push(s)})));return l},this.ajax_to_data=function(e,t){return $p.ajax.get_ex(e.url,e).then(function(e){return JSON.parse(e.response)}).then(function(e){var n=[];return e.value.forEach(function(e){n.push(_rest.to_data(e,t))}),n})},this.build_select=function(e,t){function n(e,a){"function"==typeof a?s+=a(t,e):(o=_md.syns_1с(e),r=_md.get(t.class_name,e),r&&(r=r.type,r.is_ref&&o.indexOf("_Key")==-1&&r.types.length&&r.types[0].indexOf("enm.")==-1&&(o+="_Key"),r.types.length&&(["boolean","number"].indexOf(typeof a)!=-1?s+=o+" eq "+a:r.is_ref&&"object"!=typeof a||a instanceof DataObj?s+=o+" eq guid'"+a+"'":"string"==typeof a?s+=o+" eq '"+a+"'":"object"==typeof a&&(a.hasOwnProperty("like")?s+=o+" like '%"+a.like+"%'":a.hasOwnProperty("not")?s+=" not ("+n(e,a.not)+") ":a.hasOwnProperty("in")&&(s+=o+" in ("+(r.is_ref?a.in.map(function(e){return"guid'"+e+"'"}).join(","):a.in.join(","))+") ")))))}function a(e){for(var t in e)if(s?s+=" and ":s="&$filter=","or"==t&&Array.isArray(e[t])){var a=!0;e[t].forEach(function(e){a?(s+=" ( ",a=!1):s+=" or ";var t=Object.keys(e)[0];n(t,e[t])}),s+=" ) "}else n(t,e[t])}var i,s,o,r,l="";e||(e={}),e.fields&&(e.fields.forEach(function(e){"ref"==e?o="Ref_Key":(o=_md.syns_1с(e),r=_md.get(t.class_name,e).type,r.is_ref&&o.indexOf("_Key")==-1&&r.types.length&&r.types[0].indexOf("enm.")==-1&&(o+="_Key")),i?i+=",":i="&$select=",i+=o}),l+=i),e.selection&&("function"==typeof e.selection||(Array.isArray(e.selection)?e.selection.forEach(a):a(e.selection)),s&&(l+=s)),$p.job_prm.rest&&t.rest_name.indexOf("Module_")==-1&&t.rest_name.indexOf("DataProcessor_")==-1&&t.rest_name.indexOf("Report_")==-1&&l.indexOf(" like ")==-1&&l.indexOf(" in ")==-1&&!t.metadata().irest?$p.ajax.default_attr(e,$p.job_prm.rest_url()):$p.ajax.default_attr(e,$p.job_prm.irest_url()),e.url+=t.rest_name+"?allowedOnly=true&$format=json&$top="+(e.top||300)+l},this.load_array=function(e,t){return _rest.build_select(e,t),_rest.ajax_to_data(e,t)},this.load_obj=function(e){var t={};return $p.ajax.default_attr(t,!e._metadata.irest&&$p.job_prm.rest?$p.job_prm.rest_url():$p.job_prm.irest_url()),t.url+=e._manager.rest_name+"(guid'"+e.ref+"')?$format=json",$p.ajax.get_ex(t.url,t).then(function(e){return JSON.parse(e.response)}).then(function(t){return e._mixin(_rest.to_data(t,e._manager))._set_loaded(),e}).catch(function(t){return 404==t.status?e:void $p.record_log(t)})},this.save_irest=function(e,t){var n=JSON.stringify(e),a=(void 0!=t.post?",post="+t.post:"")+(void 0!=t.operational?",operational="+t.operational:"");return $p.ajax.default_attr(t,$p.job_prm.irest_url()),t.url+=e._manager.rest_name+"(guid'"+e.ref+"'"+a+")",$p.ajax.post_ex(t.url,n,t).then(function(e){return JSON.parse(e.response)}).then(function(t){return e._mixin(t)})},this.save_rest=function(e,t){var n,a=e.to_atom();return $p.ajax.default_attr(t,$p.job_prm.rest_url()),n=t.url+e._manager.rest_name,t.url=n+"(guid'"+e.ref+"')?$format=json&$select=Ref_Key,DeletionMark",$p.ajax.get_ex(t.url,t).catch(function(e){return 404==e.status?{response:JSON.stringify({is_new:!0})}:Promise.reject(e)}).then(function(e){return JSON.parse(e.response)}).then(function(i){return i.is_new?$p.ajax.post_ex(n,a,t):$p.ajax.patch_ex(n+"(guid'"+e.ref+"')",a,t)}).then(function(t){var n=xmlToJSON.parseString(t.response,{mergeCDATA:!1,grokAttr:!0,grokText:!1,normalize:!0,xmlns:!1,namespaceKey:"_ns",textKey:"_text",valueKey:"_value",attrKey:"_attr",cdataKey:"_cdata",attrsAsObject:!1,stripAttrPrefix:!0,stripElemPrefix:!0,childrenAsArray:!1});if(n.entry&&n.entry.content&&n.entry.updated){var a,i=n.entry.content.properties,s={};for(var o in i)if(0!=o.indexOf("_"))if(a=i[o].element)if(s[o]=[],Array.isArray(a))for(var r in a){s[o][r]={};for(var l in a[r])0!=l.indexOf("_")&&(s[o][r][l]="false"!==a[r][l]._text&&a[r][l]._text)}else{s[o][0]={};for(var l in a)0!=l.indexOf("_")&&(s[o][0][l]="false"!==a[l]._text&&a[l]._text)}else s[o]="false"!==i[o]._text&&i[o]._text;return _rest.to_data(s,e._manager)}}).then(function(t){return e._mixin(t)})}}function eXcell_ocombo(e){if(e){var t=this;t.cell=e,t.grid=e.parentNode.grid,t.setValue=function(e){t.setCValue(e instanceof DataObj?e.presentation:e||"")},t.getValue=function(){return t.grid.get_cell_value()},t.shiftNext=function(){t.grid.editStop()},t.edit=function(){t.combo||(t.val=t.getValue(),t.cell.innerHTML="",t.combo=new OCombo({parent:t.cell}._mixin(t.grid.get_cell_field())),t.combo.getInput().focus())},t.detach=function(){if(t.combo){if(t.combo.getComboText){t.setValue(t.combo.getComboText()),t.combo.getSelectedValue()||t.combo.callEvent("onChange");var e=!$p.utils.is_equal(t.val,t.getValue());return t.combo.unload(),e}t.combo.unload&&t.combo.unload()}return!0}}}function eXcell_pwd(e){var t;e&&(this.cell=e,this.grid=e.parentNode.grid,eXcell_ed.call(this),t=this.edit,this.edit=function(){t.call(this),this.obj.type="password"},this.setValue=function(){this.setCValue("*********")},this.getValue=function(){return this.grid.get_cell_value()},this.detach=function(){if(this.grid.get_cell_field){var e=this.grid.get_cell_field();e.obj[e.field]=this.obj.value}return this.setValue(),t=null,this.val!=this.getValue()})}function ODropdownList(e){function t(t){s.innerHTML=e.values[s.getAttribute("current")],e.event_name&&!t&&dhx4.callEvent(e.event_name,[s.getAttribute("current")])}function n(){i.classList.remove("open")}var a,i,s,o=document.createElement("ul");e.container.innerHTML='<div class="dropdown_list">'+e.title+'<a href="#" class="dropdown_list"></a></div>',i=e.container.firstChild,s=i.querySelector("a"),s.setAttribute("current",Array.isArray(e.values)?"0":Object.keys(e.values)[0]),i.onclick=function(e){if(i.classList.contains("open")){if("LI"==e.target.tagName)for(var a in o.childNodes)if(o.childNodes[a]==e.target){s.setAttribute("current",e.target.getAttribute("current")),t();break}n()}else i.classList.add("open");return $p.iface.cancel_bubble(e)},i.appendChild(o),o.className="dropdown_menu",e.class_name&&(i.classList.add(e.class_name),o.classList.add(e.class_name));for(var r in e.values){a=document.createElement("li");var l=e.values[r].indexOf("<i");a.innerHTML=e.values[r].substr(l)+" "+e.values[r].substr(0,l),a.setAttribute("current",r),o.appendChild(a)}document.body.addEventListener("keydown",function(e){27==e.keyCode&&i.classList.remove("open")}),document.body.addEventListener("click",n),this.unload=function(){for(var t;t=i.lastChild;)i.removeChild(t);e.container.removeChild(i),a=o=i=s=e=null},t(!0)}function OCombo(e){function t(e){var t={_top:30};return m&&m.metadata().hierarchical&&m.metadata().group_hierarchy&&("elm"==u.choice_groups_elm?t.is_folder=!1:"grp"!=u.choice_groups_elm&&"parent"!=d||(t.is_folder=!0)),u.choice_links&&u.choice_links.forEach(function(e){e.name&&"selection"==e.name[0]&&(p instanceof TabularSectionRow?e.path.length<2?t[e.name[1]]="function"==typeof e.path[0]?e.path[0]:p._owner._owner[e.path[0]]:t[e.name[1]]=p[e.path[1]]:t[e.name[1]]="function"==typeof e.path[0]?e.path[0]:p[e.path[0]])}),u.choice_params&&u.choice_params.forEach(function(e){var n=Array.isArray(e.path)?{in:e.path}:e.path;t[e.name]?Array.isArray(t[e.name])?t[e.name].push(n):(t[e.name]=[t[e.name]],t[e.name].push(n)):t[e.name]=n}),u._option_list_local&&(t._local=!0),e&&(t.presentation={like:e}),t}function n(a){if("select"==this.name)m?m.form_selection(g,{initial_value:p[d].ref,selection:[t()]}):n.call({name:"type"});else if("add"==this.name)m&&m.create({},!0).then(function(t){t._set_loaded(t.ref),t.form_obj(e.pwnd)});else if("open"==this.name)p&&p[d]&&!p[d].empty()&&p[d].form_obj(e.pwnd);else if("type"==this.name){var i,s,o=[],r=p,l=d;u.type.types.forEach(function(e){i=_md.mgr_by_class_name(e),s=i.metadata(),o.push({presentation:s.synonym||s.name,mgr:i,selected:m===i})}),$p.iface.select_from_list(o).then(function(e){r[l]&&(r[l].empty&&r[l].empty()||r[l]._manager!=e.mgr)&&(m=e.mgr,p=r,d=l,u=p._metadata.fields[d],m.form_selection({on_select:function(e){p[d]=e,p=null,d=null,u=null}},{selection:[t()]})),m=null,i=null,s=null,r=null,l=null})}if(a)return $p.iface.cancel_bubble(a)}function a(){h=!1,setTimeout(function(){h||($p.iface.popup.p&&$p.iface.popup.p.onmouseover&&($p.iface.popup.p.onmouseover=null),$p.iface.popup.p&&$p.iface.popup.p.onmouseout&&($p.iface.popup.p.onmouseout=null),$p.iface.popup.clear(),$p.iface.popup.hide())},300)}function i(){if(!(m instanceof EnumManager)){h=!0;var t=document.createElement("div"),i=e.hide_frm?"":"<a href='#' name='select' title='Форма выбора {F4}'>Показать все</a><a href='#' name='open' style='margin-left: 9px;' title='Открыть форму элемента {Ctrl+Shift+F4}'><i class='fa fa-external-link fa-fw'></i></a>";if(!e.hide_frm){var s=$p.current_acl.get_acl(m.class_name);s.indexOf("i")!=-1&&(i+=" <a href='#' name='add' title='Создать новый элемент {F8}'><i class='fa fa-plus fa-fwfa-fw'></i></a>")}if(u.type.types.length>1&&(i+=" <a href='#' name='type' title='Выбрать тип значения {Alt+T}'><i class='fa fa-level-up fa-fw'></i></a>"),i){t.innerHTML=i;for(var o=0;o<t.children.length;o++)t.children[o].onclick=n;$p.iface.popup.clear(),$p.iface.popup.attachObject(t),$p.iface.popup.show(dhx4.absLeft(_.getButton())-77,dhx4.absTop(_.getButton()),_.getButton().offsetWidth,_.getButton().offsetHeight),$p.iface.popup.p.onmouseover=function(){h=!0},$p.iface.popup.p.onmouseout=a}}}function s(e){return setTimeout(i,10),e.preventDefault(),!1}function o(n){if(!(m instanceof EnumManager))return 115==n.keyCode?(n.ctrlKey&&n.shiftKey?p[d].empty()||p[d].form_obj(e.pwnd):n.ctrlKey||n.shiftKey||m&&m.form_selection(g,{initial_value:p[d].ref,selection:[t()]}),$p.iface.cancel_bubble(n)):void 0}function r(e){setTimeout(function(){_&&_.getInput&&_.getInput().select()},50)}function l(e){_&&_.getBase&&(_.getBase().parentElement?p instanceof TabularSectionRow||e.forEach(function(e){e.name==d&&c(p[d])}):setTimeout(_.unload))}function c(e){if(e&&e instanceof DataObj&&!e.empty()){if(_.getOption(e.ref)||_.addOption(e.ref,e.presentation),_.getSelectedValue()==e.ref)return;_.setComboValue(e.ref)}else _.getSelectedValue()||(_.setComboValue(""),_.setComboText(""))}var p,d,u,m,f,h,_=this,g={on_select:e.on_select||function(e){p[d]=e}};e.pwnd&&e.pwnd.setModal&&(g.setModal=e.pwnd.setModal.bind(e.pwnd)),OCombo.superclass.constructor.call(_,e),e.on_select?(_.getBase().style.border="none",_.getInput().style.left="-3px",e.is_tabular||(_.getButton().style.right="9px")):_.getBase().style.marginBottom="4px",e.left&&(_.getBase().style.left=left+"px"),this.attachEvent("onChange",function(){p&&d&&(p[d]=this.getSelectedValue())}),this.attachEvent("onBlur",function(){!this.getSelectedValue()&&this.getComboText()&&this.setComboText("")}),this.attachEvent("onDynXLS",function(n){m||(m=_md.value_mgr(p,d,u.type)),m&&(_.clearAll(),(e.get_option_list||m.get_option_list).call(m,null,t(n)).then(function(e){_.addOption&&(_.addOption(e),_.openSelect())}))}),_.getButton().addEventListener("mouseover",i),_.getButton().addEventListener("mouseout",a),_.getBase().addEventListener("click",$p.iface.cancel_bubble),_.getBase().addEventListener("contextmenu",s),_.getInput().addEventListener("keyup",o),_.getInput().addEventListener("focus",r),this.attach=function(e){p&&(p instanceof TabularSectionRow?Object.unobserve(p._owner._owner,l):Object.unobserve(p,l)),p=e.obj,d=e.field,f=e.property,e.metadata?u=e.metadata:f?(u=p._metadata.fields[d]._clone(),u.type=f.type):u=p._metadata.fields[d],_.clearAll(),m=_md.value_mgr(p,d,u.type),(m||e.get_option_list)&&(e.get_option_list||m.get_option_list).call(m,p[d],t()).then(function(e){_.addOption&&(_.addOption(e),c(p[d]))}),p instanceof TabularSectionRow?Object.observe(p._owner._owner,l,["row"]):Object.observe(p,l,["update"])};var b=this.unload;this.unload=function(){a(),_.getButton().removeEventListener("mouseover",i),_.getButton().removeEventListener("mouseout",a),_.getBase().removeEventListener("click",$p.iface.cancel_bubble),_.getBase().removeEventListener("contextmenu",s),_.getInput().removeEventListener("keyup",o), +_.getInput().removeEventListener("focus",r),p&&(p instanceof TabularSectionRow?Object.unobserve(p._owner._owner,l):Object.unobserve(p,l)),_.conf&&_.conf.tm_confirm_blur&&clearTimeout(_.conf.tm_confirm_blur),p=null,d=null,u=null,m=null,g=null;try{b.call(_)}catch(e){}},e.obj&&e.field&&this.attach(e),this.enableFilteringMode("between","dummy",!1,!1),this.__define({value:{get:function(){if(p)return p[d]}}})}function ODateRangePicker(e,t){var n=this._cont=document.createElement("div");e instanceof dhtmlXCellObject?e.appendObject(this._cont):e.appendChild(this._cont),this._cont.className="odaterangepicker",this._cont.innerHTML='<i class="fa fa-calendar"></i>  <span></span>  <i class="fa fa-caret-down"></i>',this.__define({set_text:{value:function(){$("span",n).html(this.date_from.format("DD MMM YY")+" - "+this.date_till.format("DD MMM YY"))}},on:{value:function(e,t){return $(n).on(e,t)}},date_from:{get:function(){return $(n).data("daterangepicker").startDate},set:function(e){$(n).data("daterangepicker").setStartDate(e),this.set_text()}},date_till:{get:function(){return $(n).data("daterangepicker").endDate},set:function(e){$(n).data("daterangepicker").setEndDate(e),this.set_text()}}}),$(n).daterangepicker({startDate:t.date_from?moment(t.date_from):moment().subtract(29,"days"),endDate:moment(t.date_till),showDropdowns:!0,alwaysShowCalendars:!0,opens:"left",ranges:{"Сегодня":[moment(),moment()],"Вчера":[moment().subtract(1,"days"),moment().subtract(1,"days")],"Последние 7 дней":[moment().subtract(6,"days"),moment()],"Последние 30 дней":[moment().subtract(29,"days"),moment()],"Этот месяц":[moment().startOf("month"),moment().endOf("month")],"Прошлый месяц":[moment().subtract(1,"month").startOf("month"),moment().subtract(1,"month").endOf("month")]}},this.set_text.bind(this)),this.set_text()}function _clear_all(){$p.iface.docs.__define({clear_all:{value:function(){this.detachToolbar(),this.detachStatusBar(),this.detachObject(!0)},enumerable:!1},"Очистить":{get:function(){return this.clear_all},enumerable:!1},"Контейнер":{get:function(){return this.cell.querySelector(".dhx_cell_cont_layout")},enumerable:!1}})}function OTooolBar(e){function t(e){for(var t=0;t<c.children.length;t++)c.children[t].classList.remove("selected");e&&!this.classList.contains("selected")&&this.classList.add("selected")}function n(){s=!1,setTimeout(function(){s||$p.iface.popup.hide()},300)}function a(){e.onclick&&e.onclick.call(l,this.name.replace(e.name+"_",""),e.name)}var i,s,o,r,l=this,c=document.createElement("div");e.image_path||(e.image_path=dhtmlx.image_path),e.hasOwnProperty("class_name")?c.className=e.class_name:c.className="md_otooolbar",l.cell=c,l.buttons={},this.add=function(t){function p(e){if(e||(e=d),e.subdiv&&!o&&!r){for(;e.subdiv.firstChild;)e.subdiv.removeChild(e.subdiv.firstChild);e.subdiv.parentNode.removeChild(e.subdiv),e.subdiv=null}}var d=$p.iface.add_button(c,e,t);d.onclick=a,d.onmouseover=function(){t.title&&!t.sub&&(s=!0,$p.iface.popup.clear(),$p.iface.popup.attachHTML(t.title),$p.iface.popup.show(dhx4.absLeft(d),dhx4.absTop(d),d.offsetWidth,d.offsetHeight),$p.iface.popup.p.onmouseover=function(){s=!0},$p.iface.popup.p.onmouseout=n,e.on_popup&&e.on_popup($p.iface.popup,d))},d.onmouseout=n,l.buttons[t.name]=d,t.sub&&(d.onmouseover=function(){for(var n=0;n<d.parentNode.children.length;n++)if(d.parentNode.children[n]!=d&&d.parentNode.children[n].subdiv){p(d.parentNode.children[n]);break}if(r=!0,!this.subdiv){this.subdiv=document.createElement("div"),this.subdiv.className="md_otooolbar",i=$p.iface.get_offset(d),"right"==t.sub.align?this.subdiv.style.left=i.left+d.offsetWidth-(parseInt(t.sub.width.replace(/\D+/g,""))||56)+"px":this.subdiv.style.left=i.left+"px",this.subdiv.style.top=i.top+c.offsetHeight+"px",this.subdiv.style.height=t.sub.height||"198px",this.subdiv.style.width=t.sub.width||"56px";for(var n in t.sub.buttons){var s=$p.iface.add_button(this.subdiv,e,t.sub.buttons[n]);s.onclick=a}e.wrapper.appendChild(this.subdiv),this.subdiv.onmouseover=function(){o=!0},this.subdiv.onmouseout=function(){o=!1,setTimeout(p,500)},t.title&&$p.iface.popup.show(dhx4.absLeft(this.subdiv),dhx4.absTop(this.subdiv),this.subdiv.offsetWidth,this.subdiv.offsetHeight)}},d.onmouseout=function(){r=!1,setTimeout(p,500)})},this.select=function(n){for(var a=0;a<c.children.length;a++){var i=c.children[a];if(i.name==e.name+"_"+n)return void t.call(i,!0)}},this.get_selected=function(){for(var e=0;e<c.children.length;e++){var t=c.children[e];if(t.classList.contains("selected"))return t.name}},this.unload=function(){for(;c.firstChild;)c.removeChild(c.firstChild);e.wrapper.removeChild(c)},e.wrapper.appendChild(c),c.style.width=e.width||"28px",c.style.height=e.height||"150px",c.style.position="absolute",e.top&&(c.style.top=e.top),e.left&&(c.style.left=e.left),e.bottom&&(c.style.bottom=e.bottom),e.right&&(c.style.right=e.right),e.paddingRight&&(c.style.paddingRight=e.paddingRight),e.paddingLeft&&(c.style.paddingLeft=e.paddingLeft),e.buttons&&e.buttons.forEach(function(e){l.add(e)})}function eXcell_addr(e){if(e){var t,n=this,a=function(e){return eXcell_proto.input_keydown(e,n)},i=function(e){var t={grid:n.grid}._mixin(n.grid.get_cell_field());return wnd_address(t),$p.iface.cancel_bubble(e)};n.cell=e,n.grid=n.cell.parentNode.grid,n.open_selection=i,n.setValue=function(e){n.setCValue(e)},n.getValue=function(){return n.grid.get_cell_value()},n.edit=function(){var e;n.val=n.getValue(),n.cell.innerHTML='<div class="ref_div21"><input type="text" class="dhx_combo_edit" style="height: 20px;"><div class="ref_field21"> </div></div>',t=n.cell.firstChild,e=t.childNodes[0],e.value=n.val,e.onclick=$p.iface.cancel_bubble,e.readOnly=!0,e.focus(),e.onkeydown=a,t.childNodes[1].onclick=i},n.detach=function(){return n.setValue(n.getValue()),!$p.utils.is_equal(n.val,n.getValue())}}}function wnd_address(e){function t(){var e={name:"wnd_addr",wnd:{id:"wnd_addr",top:130,left:200,width:800,height:560,modal:!0,center:!0,pwnd:g,allow_close:!0,allow_minmax:!0,on_close:f,caption:_.shipping_address}};g&&g.getHeight&&e.wnd.height>g.getHeight()&&(e.wnd.height=g.getHeight()),h=$p.iface.dat_blank(null,e.wnd),h.elmnts.layout=h.attachLayout("2E"),h.elmnts.cell_frm=h.elmnts.layout.cells("a"),h.elmnts.cell_frm.setHeight("110"),h.elmnts.cell_frm.hideHeader(),h.elmnts.cell_frm.fixSize(0,1),h.elmnts.pgrid=h.elmnts.cell_frm.attachPropertyGrid(),h.elmnts.pgrid.setDateFormat("%d.%m.%Y %H:%i"),h.elmnts.pgrid.init(),h.elmnts.pgrid.parse(_._manager.get_property_grid_xml({" ":[{id:"delivery_area",path:"o.delivery_area",synonym:"Район доставки",type:"ref",txt:v.delivery_area.presentation},{id:"region",path:"o.region",synonym:"Регион",type:"ro",txt:v.region},{id:"city",path:"o.city",synonym:"Населенный пункт",type:"ed",txt:v.city},{id:"street",path:"o.street",synonym:"Улица, дом, корпус, литера, квартира",type:"ed",txt:v.street}]},v),function(){h.elmnts.pgrid.enableAutoHeight(!0),h.elmnts.pgrid.setInitWidthsP("40,60"),h.elmnts.pgrid.setSizes(),h.elmnts.pgrid.attachEvent("onPropertyChanged",m)},"xml"),h.elmnts.pgrid.get_cell_field=function(){return{obj:v,field:"delivery_area",on_select:a,pwnd:h,metadata:{synonym:"Район",tooltip:"Район (зона, направление) доставки для группировки при планировании и оптимизации маршрута геокодером",choice_groups_elm:"elm",type:{types:["cat.delivery_areas"],is_ref:!0}}}},h.elmnts.toolbar=h.attachToolbar({icons_path:dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()}),h.elmnts.toolbar.loadStruct('<toolbar><item id="btn_select" type="button" title="Установить адрес" text="<b>Выбрать</b>" /></toolbar>',function(){this.attachEvent("onclick",n)}),h.elmnts.cell_map=h.elmnts.layout.cells("b"),h.elmnts.cell_map.hideHeader();var t={center:new google.maps.LatLng(v.latitude,v.longitude),zoom:v.street?15:12,mapTypeId:google.maps.MapTypeId.ROADMAP};h.elmnts.map=h.elmnts.cell_map.attachMap(t),v.marker=new google.maps.Marker({map:h.elmnts.map,draggable:!0,animation:google.maps.Animation.DROP,position:t.center}),google.maps.event.addListener(v.marker,"click",d),google.maps.event.addListener(v.marker,"dragend",u),s()}function n(e){"btn_select"==e&&(_.delivery_area=v.delivery_area,l(),_.coordinates=JSON.stringify([v.latitude,v.longitude])),h.close()}function a(e){if(void 0!==e){var t,n=b;b=$p.utils.is_data_obj(e)?e:$p.cat.delivery_areas.get(e,!1),t=n!=b,$p.utils.is_data_obj(b)||(b=$p.cat.delivery_areas.get()),h.elmnts.pgrid.cells().setValue(e.presentation),i(t)}}function i(e){if(!v.delivery_area.empty()&&e&&(v.street=""),v.delivery_area.region?(v.region=v.delivery_area.region,h.elmnts.pgrid.cells("region",1).setValue(v.region)):e&&(v.region=""),v.delivery_area.city?(v.city=v.delivery_area.city,h.elmnts.pgrid.cells("city",1).setValue(v.city)):e&&(v.city=""),v.delivery_area.latitude&&v.delivery_area.longitude){var t=new google.maps.LatLng(v.delivery_area.latitude,v.delivery_area.longitude);h.elmnts.map.setCenter(t),v.marker.setPosition(t)}s()}function s(){h.elmnts.pgrid.cells("region",1).setValue(v.region),h.elmnts.pgrid.cells("city",1).setValue(v.city),h.elmnts.pgrid.cells("street",1).setValue(v.street)}function o(){var e=v.street?15:12;h.elmnts.map.getZoom()!=e&&h.elmnts.map.setZoom(e),p(function(e,t){if(t==google.maps.GeocoderStatus.OK){var n=e[0].geometry.location;h.elmnts.map.setCenter(n),v.marker.setPosition(n),v.latitude=n.lat(),v.longitude=n.lng(),v.postal_code=$p.ipinfo.components({},e[0].address_components).postal_code||""}})}function r(){return(v.street?v.street.replace(/,/g," ")+", ":"")+(v.city?v.city+", ":"")+(v.region?v.region+", ":"")+v.country+(v.postal_code?", "+v.postal_code:"")}function l(){_.shipping_address=r();var e='<КонтактнаяИнформация \t\t\t\txmlns="http://www.v8.1c.ru/ssl/contactinfo" \t\t\t\txmlns:xs="http://www.w3.org/2001/XMLSchema" \t\t\t\txmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" \t\t\t\tПредставление="%1"> \t\t\t\t\t<Комментарий/> \t\t\t\t\t<Состав xsi:type="Адрес" Страна="РОССИЯ"> \t\t\t\t\t\t<Состав xsi:type="АдресРФ">'.replace("%1",_.shipping_address);if(v.region&&(e+="\n<СубъектРФ>"+v.region+"</СубъектРФ>"),v.city&&(e+=v.city.indexOf("г.")!=-1||v.city.indexOf("г ")!=-1||v.city.indexOf(" г")!=-1?"\n<Город>"+v.city+"</Город>":"\n<НаселПункт>"+v.city+"</НаселПункт>"),v.street){var t,n,a,i,s,o=v.street.replace(/,/g," ");for(var l in $p.fias){if(1==$p.fias[l].type)for(var c in $p.fias[l].syn)if((n=o.indexOf($p.fias[l].syn[c]))!=-1){i=l,t=o.substr(n+$p.fias[l].syn[c].length).trim(),o=o.substr(0,n).trim();break}if(i)break}if(i||(i="1010",(n=o.indexOf(" "))!=-1&&(t=o.substr(n),o=o.substr(0,n))),e+="\n<Улица>"+o.trim()+"</Улица>",t){a=t.toLowerCase(),t="";for(var l in $p.fias){if(3==$p.fias[l].type)for(var c in $p.fias[l].syn)if((n=a.indexOf($p.fias[l].syn[c]))!=-1){s=l,t=a.substr(n+$p.fias[l].syn[c].length),a=a.substr(0,n);break}if(s)break}s||(s="2010",(n=a.indexOf(" "))!=-1&&(t=a.substr(n),a=a.substr(0,n))),e+='\n<ДопАдрЭл><Номер Тип="'+i+'" Значение="'+a.trim()+'"/></ДопАдрЭл>'}t&&(e+='\n<ДопАдрЭл><Номер Тип="'+s+'" Значение="'+t.trim()+'"/></ДопАдрЭл>')}v.postal_code&&(e+='<ДопАдрЭл ТипАдрЭл="10100000" Значение="'+v.postal_code+'"/>'),e+="</Состав> \t\t\t\t\t</Состав></КонтактнаяИнформация>",_.address_fields=e}function c(){function e(e){if(e.attributes&&2==e.attributes.length){var t={};return t[e.attributes[0].value]=e.attributes[1].value,t}}if(_.address_fields){v.xml=(new DOMParser).parseFromString(_.address_fields,"text/xml");var t,n={},a={building_room:""},i=[],s="СубъектРФ,Округ,СвРайМО,СвРайМО,ВнутригРайон,НаселПункт,Улица,Город,ДопАдрЭл,Адрес_по_документу,Местоположение".split(",");for(var o in s)n[s[o]]=v.xml.getElementsByTagName(s[o]);for(var o in n)for(var r in n[o])if("length"!=r&&n[o].hasOwnProperty(r))if(t=e(n[o][r]))a[o]||(a[o]=[]),a[o].push(t);else if(n[o][r].childNodes.length)for(var l in n[o][r].childNodes)"length"!=l&&n[o][r].childNodes.hasOwnProperty(l)&&((t=e(n[o][r].childNodes[l]))?(a[o]||(a[o]=[]),a[o].push(t)):n[o][r].childNodes[l].nodeValue&&(a[o]?a[o]+=" "+n[o][r].childNodes[l].nodeValue:a[o]=n[o][r].childNodes[l].nodeValue));for(var o in a["ДопАдрЭл"]){for(var r in $p.fias)4==r.length&&a["ДопАдрЭл"][o][r]&&(i[$p.fias[r].type]=$p.fias[r].name+" "+a["ДопАдрЭл"][o][r]);a["ДопАдрЭл"][o][101e5]&&(v.postal_code=a["ДопАдрЭл"][o][101e5])}v.address_fields=a,v.region=a["СубъектРФ"]||a["Округ"]||"",v.city=a["Город"]||a["НаселПункт"]||"",v.street=a["Улица"]||"";for(var o in i)v.street+=" "+i[o]}return new Promise(function(e,t){if($p.ipinfo||($p.ipinfo=new IPInfo),window.google&&window.google.maps)e();else{$p.load_script("//maps.google.com/maps/api/js?callback=$p.ipinfo.location_callback","script",function(){});var n=$p.eve.attachEvent("geo_google_ready",function(){a&&clearTimeout(a),n&&($p.eve.detachEvent(n),n=null,e())}),a=setTimeout(function(){n&&($p.eve.detachEvent(n),n=null),$p.msg.show_msg({type:"alert-warning",text:$p.msg.error_geocoding+" Google",title:$p.msg.main_title}),e()},1e4)}}).then(function(){v.coordinates.length?(v.latitude=v.coordinates[0],v.longitude=v.coordinates[1]):_.shipping_address?p(function(e,t){t==google.maps.GeocoderStatus.OK&&(v.latitude=e[0].geometry.location.lat(),v.longitude=e[0].geometry.location.lng())}):$p.ipinfo.latitude&&$p.ipinfo.longitude?(v.latitude=$p.ipinfo.latitude,v.longitude=$p.ipinfo.longitude):(v.latitude=55.635924,v.longitude=37.6066379,$p.msg.show_msg($p.msg.empty_geocoding))})}function p(e){var t=r();$p.ipinfo.ggeocoder.geocode({address:t},e)}function d(){null!=v.marker.getAnimation()?v.marker.setAnimation(null):(v.marker.setAnimation(google.maps.Animation.BOUNCE),setTimeout(function(){v.marker.setAnimation(null)},1500))}function u(e){$p.ipinfo.ggeocoder.geocode({latLng:e.latLng},function(t,n){if(n==google.maps.GeocoderStatus.OK&&t[0]){var a=t[0];h.setText(a.formatted_address),$p.ipinfo.components(v,a.address_components),s();var i=v.street?15:12;h.elmnts.map.getZoom()!=i&&(h.elmnts.map.setZoom(i),h.elmnts.map.setCenter(e.latLng)),v.latitude=e.latLng.lat(),v.longitude=e.latLng.lng()}})}function m(e,t,n){e&&(v.delivery_area.empty()?(t=n,$p.msg.show_msg({type:"alert",text:$p.msg.delivery_area_empty,title:$p.msg.addr_title}),setTimeout(function(){h.elmnts.pgrid.selectRowById("delivery_area")},50)):"delivery_area"==e?a(t):(v[h.elmnts.pgrid.getSelectedRowId()]=t,o()))}function f(t){return e.grid.editStop(),!t.error}var h,_=e.obj,g=e.pwnd,b=_.delivery_area,v={coordinates:_.coordinates?JSON.parse(_.coordinates):[],country:"Россия",region:"",city:"",street:"",postal_code:"",marker:{}};return v.__define("delivery_area",{get:function(){return b},set:function(e){a(e)}}),c().then(t),h}function AppEvents(){if(this.__define({init:{value:function(){$p.__define("job_prm",{value:new JobPrm,writable:!1}),$p.wsql.init_params()}},do_eventable:{value:function(e){function t(e,t){e=String(e).toLowerCase(),this._evnts.data[e]||(this._evnts.data[e]={});var n=$p.utils.generate_guid();return this._evnts.data[e][n]=t,n}function n(e){if(!e)return a.call(this);for(var t in this._evnts.data){var n=0;for(var i in this._evnts.data[t])i==e?(this._evnts.data[t][i]=null,delete this._evnts.data[t][i]):n++;0==n&&(this._evnts.data[t]=null,delete this._evnts.data[t])}}function a(){for(var e in this._evnts.data){for(var t in this._evnts.data[e])this._evnts.data[e][t]=null,delete this._evnts.data[e][t];this._evnts.data[e]=null,delete this._evnts.data[e]}}function i(e,t){if(e=String(e).toLowerCase(),null==this._evnts.data[e])return!0;var n=!0;for(var a in this._evnts.data[e])n=this._evnts.data[e][a].apply(this,t)&&n;return n}function s(){for(var e in this._evnts.evnts){var t=this._evnts.evnts[e].length;if(t){for(var n=0;n<t;n++)this.emit(e,this._evnts.evnts[e][n]);this._evnts.evnts[e].length=0}}this._evnts.timer=0}e.__define({_evnts:{value:{data:{},timer:0,evnts:{}}},on:{value:t},attachEvent:{value:t},off:{value:n},detachEvent:{value:n},detachAllEvents:{value:a},checkEvent:{value:function(e){return e=String(e).toLowerCase(),null!=this._evnts.data[e]}},callEvent:{value:i},emit:{value:i},emit_async:{value:function(e,t){this._evnts.evnts[e]||(this._evnts.evnts[e]=[]),this._evnts.evnts[e].push(t),this._evnts.timer&&clearTimeout(this._evnts.timer),this._evnts.timer=setTimeout(s.bind(this),4)}}})}}}),"undefined"!=typeof window&&window.dhx4){for(var e in dhx4)this[e]=dhx4[e],delete dhx4[e];window.dhx4=this}else"undefined"==typeof WorkerGlobalScope&&this.do_eventable(this)}function JobPrm(){function e(){return $p.wsql.get_user_param("rest_path")||$p.job_prm.rest_path||"/a/zd/%1/odata/standard.odata/"}function t(){function e(e){var t,n={},a=[];if("#"!==e.substr(0,1)&&"?"!==e.substr(0,1)||(e=e.substr(1)),e.length>2){t=decodeURI(e).split("&");for(var i in t)if(a=t[i].split("="),"m"==a[0])try{n[a[0]]=JSON.parse(a[1])}catch(e){n[a[0]]={}}else n[a[0]]=a[1]||""}return n}return e(location.search)._mixin(e(location.hash))}this.__define({parse_url:{value:t},offline:{value:!1,writable:!0},local_storage_prefix:{value:"",writable:!0},create_tables:{value:!0,writable:!0},url_prm:{value:"undefined"!=typeof window?t():{}},rest_url:{value:function(){var t=e(),n=$p.wsql.get_user_param("zone",$p.job_prm.zone_is_string?"string":"number");return n?t.replace("%1",n):t.replace("%1/","")}},irest_url:{value:function(){var t=e(),n=$p.wsql.get_user_param("zone",$p.job_prm.zone_is_string?"string":"number");return t=t.replace("odata/standard.odata","hs/rest"),n?t.replace("%1",n):t.replace("%1/","")}}}),$p.eve.callEvent("settings",[this]);for(var n in this)"url_prm"!==n&&"function"!=typeof this[n]&&this.url_prm.hasOwnProperty[n]&&(this[n]=this.url_prm[n])}function Modifiers(){var e=[];this.push=function(t){e.push(t)},this.detache=function(t){var n=e.indexOf(t);n!=-1&&e.splice(n,1)},this.clear=function(){e.length=0},this.execute=function(t){var n,a;return e.forEach(function(e){a="function"==typeof e?e(t):$p.injected_data[e](t),n!==!1&&(n=a)}),n},this.execute_external=function(e){var t=$p.wsql.get_user_param("modifiers");return t=t?t.split("\n").map(function(e){return e?new Promise(function(t,n){$p.load_script(e,"script",t)}):Promise.resolve()}):[],Promise.all(t).then(function(){this.execute(e)}.bind(this))}}function IPInfo(){function e(){this.geocode=function(e){return Promise.resolve(!1)}}var t,n,a,i="";this.__define({ipgeo:{value:function(){return $p.ajax.get("//api.sypexgeo.net/").then(function(e){return JSON.parse(e.response)}).catch($p.record_log)}},yageocoder:{get:function(){return t||(t=new e),t},enumerable:!1,configurable:!1},ggeocoder:{get:function(){return n},enumerable:!1,configurable:!1},addr:{get:function(){return i}},parts:{get:function(){return a}},components:{value:function(e,t){var n,a,i,s="",o="",r="";for(n in t){a=t[n];for(i in a.types)switch(a.types[i]){case"route":a.short_name.indexOf("Unnamed")==-1&&(s=a.short_name+(s?" "+s:""),o=a.long_name.replace("улица","").trim());break;case"administrative_area_level_1":e.region=a.long_name;break;case"administrative_area_level_2":e.city=a.short_name,e.city_long=a.long_name;break;case"locality":r=(r?r+" ":"")+a.short_name;break;case"street_number":s=(s?s+" ":"")+a.short_name;break;case"postal_code":e.postal_code=a.short_name}}return e.region&&e.region==e.city_long?e.city.indexOf(r)==-1?e.city=r:e.city="":r&&e.city.indexOf(r)==-1&&e.region.indexOf(r)==-1&&(s=r+", "+s),e.street&&e.street.indexOf(o)!=-1||(e.street=s),e}},location_callback:{value:function(){n=new google.maps.Geocoder,$p.eve.callEvent("geo_google_ready"),navigator.geolocation&&navigator.geolocation.getCurrentPosition(function(e){$p.ipinfo.latitude=e.coords.latitude,$p.ipinfo.longitude=e.coords.longitude;var t=new google.maps.LatLng($p.ipinfo.latitude,$p.ipinfo.longitude);n.geocode({latLng:t},function(e,t){t==google.maps.GeocoderStatus.OK&&(a=!e[1]||e[0].address_components.length>=e[1].address_components.length?e[0]:e[1],i=a.formatted_address,$p.eve.callEvent("geo_current_position",[$p.ipinfo.components({},a.address_components)]))})},$p.record_log,{timeout:3e4})}}})}function SpreadsheetDocument(e){this._attr={orientation:"portrait",title:"",content:document.createElement("DIV")},e&&"string"==typeof e?this.content=e:"object"==typeof e&&this._mixin(e),e=null}function HandsontableDocument(e,t){var n=function(){this._then&&this._then(this)}.bind(this);this._online=t&&t.allow_offline||navigator.onLine&&$p.wsql.pouch.authorized,e instanceof dhtmlXCellObject?(this._cont=document.createElement("div"),e.detachObject(!0),e.attachObject(this._cont)):this._cont=e,this._cont.classList.add("handsontable_wrapper"),this._online?this._cont.innerHTML=t.autorun?$p.msg.report_prepare:$p.msg.report_need_prepare:this._cont.innerHTML=$p.msg.report_need_online,this.then=function(e){return this._then=e,this},this.requery=function(e){this.hot&&this.hot.destroy(),e instanceof Error?this._cont.innerHTML=$p.msg.report_error+(e.name?" <b>"+e.name+"</b>":"")+(e.message?" "+e.message:""):(this._cont.innerHTML="",this.hot=new Handsontable(this._cont,e))},"function"!=typeof Handsontable&&this._online?$p.load_script("https://cdnjs.cloudflare.com/ajax/libs/pikaday/1.4.0/pikaday.min.js","script").then(function(){return $p.load_script("https://cdnjs.cloudflare.com/ajax/libs/numbro/1.9.2/numbro.min.js","script")}).then(function(){return $p.load_script("https://cdn.jsdelivr.net/g/zeroclipboard,handsontable@0.26(handsontable.min.js)","script")}).then(function(){return Promise.all([$p.load_script("https://cdn.jsdelivr.net/handsontable/0.26/handsontable.min.css","link"),$p.load_script("https://cdnjs.cloudflare.com/ajax/libs/numbro/1.9.2/languages/ru-RU.min.js","script")])}).then(n):setTimeout(n)}function Aes(e){"use strict";function t(e){return encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(e,t){return String.fromCharCode("0x"+t)})}function n(e){try{return decodeURIComponent(escape(e))}catch(t){return e}}function a(e){if("undefined"!=typeof btoa)return btoa(e);if("undefined"!=typeof Buffer)return new Buffer(e,"binary").toString("base64");throw new Error("No Base64 Encode")}function i(e){if("undefined"!=typeof atob)return atob(e);if("undefined"!=typeof Buffer)return new Buffer(e,"base64").toString("binary");throw new Error("No Base64 Decode")}var s=this;s.cipher=function(e,t){for(var n=4,a=t.length/n-1,i=[[],[],[],[]],o=0;o<4*n;o++)i[o%4][Math.floor(o/4)]=e[o];i=s.addRoundKey(i,t,0,n);for(var r=1;r<a;r++)i=s.subBytes(i,n),i=s.shiftRows(i,n),i=s.mixColumns(i,n),i=s.addRoundKey(i,t,r,n);i=s.subBytes(i,n),i=s.shiftRows(i,n),i=s.addRoundKey(i,t,a,n);for(var l=new Array(4*n),o=0;o<4*n;o++)l[o]=i[o%4][Math.floor(o/4)];return l},s.keyExpansion=function(e){for(var t=4,n=e.length/4,a=n+6,i=new Array(t*(a+1)),o=new Array(4),r=0;r<n;r++){var l=[e[4*r],e[4*r+1],e[4*r+2],e[4*r+3]];i[r]=l}for(var r=n;r<t*(a+1);r++){i[r]=new Array(4);for(var c=0;c<4;c++)o[c]=i[r-1][c];if(r%n==0){o=s.subWord(s.rotWord(o));for(var c=0;c<4;c++)o[c]^=s.rCon[r/n][c]}else n>6&&r%n==4&&(o=s.subWord(o));for(var c=0;c<4;c++)i[r][c]=i[r-n][c]^o[c]}return i},s.subBytes=function(e,t){for(var n=0;n<4;n++)for(var a=0;a<t;a++)e[n][a]=s.sBox[e[n][a]];return e},s.shiftRows=function(e,t){for(var n=new Array(4),a=1;a<4;a++){for(var i=0;i<4;i++)n[i]=e[a][(i+a)%t];for(var i=0;i<4;i++)e[a][i]=n[i]}return e},s.mixColumns=function(e,t){for(var n=0;n<4;n++){for(var a=new Array(4),i=new Array(4),s=0;s<4;s++)a[s]=e[s][n],i[s]=128&e[s][n]?e[s][n]<<1^283:e[s][n]<<1;e[0][n]=i[0]^a[1]^i[1]^a[2]^a[3],e[1][n]=a[0]^i[1]^a[2]^i[2]^a[3],e[2][n]=a[0]^a[1]^i[2]^a[3]^i[3],e[3][n]=a[0]^i[0]^a[1]^a[2]^i[3]}return e},s.addRoundKey=function(e,t,n,a){for(var i=0;i<4;i++)for(var s=0;s<a;s++)e[i][s]^=t[4*n+s][i];return e},s.subWord=function(e){for(var t=0;t<4;t++)e[t]=s.sBox[e[t]];return e},s.rotWord=function(e){for(var t=e[0],n=0;n<3;n++)e[n]=e[n+1];return e[3]=t,e},s.sBox=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22],s.rCon=[[0,0,0,0],[1,0,0,0],[2,0,0,0],[4,0,0,0],[8,0,0,0],[16,0,0,0],[32,0,0,0],[64,0,0,0],[128,0,0,0],[27,0,0,0],[54,0,0,0]],s.Ctr={},s.Ctr.encrypt=function(n,i,o){var r=16;128!=o&&192!=o&&256!=o&&(o=128),n=t(n),i=t(i||e);for(var l=o/8,c=new Array(l),p=0;p<l;p++)c[p]=p<i.length?i.charCodeAt(p):0;var d=s.cipher(c,s.keyExpansion(c));d=d.concat(d.slice(0,l-16));for(var u=new Array(r),m=(new Date).getTime(),f=m%1e3,h=Math.floor(m/1e3),_=Math.floor(65535*Math.random()),p=0;p<2;p++)u[p]=f>>>8*p&255;for(var p=0;p<2;p++)u[p+2]=_>>>8*p&255;for(var p=0;p<4;p++)u[p+4]=h>>>8*p&255;for(var g="",p=0;p<8;p++)g+=String.fromCharCode(u[p]);for(var b=s.keyExpansion(d),v=Math.ceil(n.length/r),x="",y=0;y<v;y++){for(var w=0;w<4;w++)u[15-w]=y>>>8*w&255;for(var w=0;w<4;w++)u[15-w-4]=y/4294967296>>>8*w;for(var k=s.cipher(u,b),$=y<v-1?r:(n.length-1)%r+1,j=new Array($),p=0;p<$;p++)j[p]=k[p]^n.charCodeAt(y*r+p),j[p]=String.fromCharCode(j[p]);x+=j.join(""),"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&y%1e3==0&&self.postMessage({progress:y/v})}return x=a(g+x)},s.Ctr.decrypt=function(a,o,r){var l=16;128!=r&&192!=r&&256!=r&&(r=128),a=i(a),o=t(o||e);for(var c=r/8,p=new Array(c),d=0;d<c;d++)p[d]=d<o.length?o.charCodeAt(d):0;var u=s.cipher(p,s.keyExpansion(p));u=u.concat(u.slice(0,c-16));for(var m=new Array(8),f=a.slice(0,8),d=0;d<8;d++)m[d]=f.charCodeAt(d);for(var h=s.keyExpansion(u),_=Math.ceil((a.length-8)/l),g=new Array(_),b=0;b<_;b++)g[b]=a.slice(8+b*l,8+b*l+l);a=g;for(var v="",b=0;b<_;b++){for(var x=0;x<4;x++)m[15-x]=b>>>8*x&255;for(var x=0;x<4;x++)m[15-x-4]=(b+1)/4294967296-1>>>8*x&255;for(var y=s.cipher(m,h),w=new Array(a[b].length),d=0;d<a[b].length;d++)w[d]=y[d]^a[b].charCodeAt(d),w[d]=String.fromCharCode(w[d]);v+=w.join(""),"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&b%1e3==0&&self.postMessage({progress:b/_})}return v=n(v)}}!function(e,t){"object"==typeof exports&&"undefined"!=typeof module&&"function"==typeof require?t(require("../moment")):"function"==typeof define&&define.amd?define(["../moment"],t):t(e.moment)}(this,function(e){"use strict";function t(e,t){var n=e.split("_");return t%10===1&&t%100!==11?n[0]:t%10>=2&&t%10<=4&&(t%100<10||t%100>=20)?n[1]:n[2]}function n(e,n,a){var i={mm:n?"минута_минуты_минут":"минуту_минуты_минут",hh:"час_часа_часов",dd:"день_дня_дней",MM:"месяц_месяца_месяцев",yy:"год_года_лет"};return"m"===a?n?"минута":"минуту":e+" "+t(i[a],+e)}var a=[/^янв/i,/^фев/i,/^мар/i,/^апр/i,/^ма[йя]/i,/^июн/i,/^июл/i,/^авг/i,/^сен/i,/^окт/i,/^ноя/i,/^дек/i],i=e.defineLocale("ru",{months:{format:"января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря".split("_"),standalone:"январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_")},monthsShort:{format:"янв._февр._мар._апр._мая_июня_июля_авг._сент._окт._нояб._дек.".split("_"),standalone:"янв._февр._март_апр._май_июнь_июль_авг._сент._окт._нояб._дек.".split("_")},weekdays:{standalone:"воскресенье_понедельник_вторник_среда_четверг_пятница_суббота".split("_"),format:"воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу".split("_"),isFormat:/\[ ?[Вв] ?(?:прошлую|следующую|эту)? ?\] ?dddd/},weekdaysShort:"вс_пн_вт_ср_чт_пт_сб".split("_"),weekdaysMin:"вс_пн_вт_ср_чт_пт_сб".split("_"),monthsParse:a,longMonthsParse:a,shortMonthsParse:a,monthsRegex:/^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i,monthsShortRegex:/^(январ[ья]|янв\.?|феврал[ья]|февр?\.?|марта?|мар\.?|апрел[ья]|апр\.?|ма[йя]|июн[ья]|июн\.?|июл[ья]|июл\.?|августа?|авг\.?|сентябр[ья]|сент?\.?|октябр[ья]|окт\.?|ноябр[ья]|нояб?\.?|декабр[ья]|дек\.?)/i,monthsStrictRegex:/^(январ[яь]|феврал[яь]|марта?|апрел[яь]|ма[яй]|июн[яь]|июл[яь]|августа?|сентябр[яь]|октябр[яь]|ноябр[яь]|декабр[яь])/i,monthsShortStrictRegex:/^(янв\.|февр?\.|мар[т.]|апр\.|ма[яй]|июн[ья.]|июл[ья.]|авг\.|сент?\.|окт\.|нояб?\.|дек\.)/i,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D MMMM YYYY г.",LLL:"D MMMM YYYY г., HH:mm",LLLL:"dddd, D MMMM YYYY г., HH:mm"},calendar:{sameDay:"[Сегодня в] LT",nextDay:"[Завтра в] LT",lastDay:"[Вчера в] LT",nextWeek:function(e){if(e.week()===this.week())return 2===this.day()?"[Во] dddd [в] LT":"[В] dddd [в] LT";switch(this.day()){case 0:return"[В следующее] dddd [в] LT";case 1:case 2:case 4:return"[В следующий] dddd [в] LT";case 3:case 5:case 6:return"[В следующую] dddd [в] LT"}},lastWeek:function(e){if(e.week()===this.week())return 2===this.day()?"[Во] dddd [в] LT":"[В] dddd [в] LT";switch(this.day()){case 0:return"[В прошлое] dddd [в] LT";case 1:case 2:case 4:return"[В прошлый] dddd [в] LT";case 3:case 5:case 6:return"[В прошлую] dddd [в] LT"}},sameElse:"L"},relativeTime:{future:"через %s",past:"%s назад",s:"несколько секунд",m:n,mm:n,h:"час",hh:n,d:"день",dd:n,M:"месяц",MM:n,y:"год",yy:n},meridiemParse:/ночи|утра|дня|вечера/i,isPM:function(e){return/^(дня|вечера)$/.test(e)},meridiem:function(e,t,n){return e<4?"ночи":e<12?"утра":e<17?"дня":"вечера"},ordinalParse:/\d{1,2}-(й|го|я)/,ordinal:function(e,t){switch(t){case"M":case"d":case"DDD":return e+"-й";case"D":return e+"-го";case"w":case"W":return e+"-я";default:return e}},week:{dow:1,doy:7}});return i}),Object.defineProperties(Object.prototype,{__define:{value:function(e,t){return t?Object.defineProperty(this,e,t):Object.defineProperties(this,e),this}},_extend:{value:function(e){var t=function(){};t.prototype=e.prototype,this.prototype=new t,this.prototype.constructor=this,this.__define("superclass",{value:e.prototype,enumerable:!1})}},_mixin:{value:function(e,t,n){var a,i,s={};if(t&&t.length)for(a=0;a<t.length;a++)i=t[a],n&&n.indexOf(i)!=-1||"undefined"!=typeof s[i]&&s[i]==e[i]||(this[i]=e[i]);else for(i in e)n&&n.indexOf(i)!=-1||"undefined"!=typeof s[i]&&s[i]==e[i]||(this[i]=e[i]);return this}},_clone:{value:function(){if(!this||"object"!=typeof this)return this;var e,t,n="function"==typeof this.pop?[]:{};for(e in this)this.hasOwnProperty(e)&&(t=this[e],t?"function"==typeof t||t instanceof DataObj||t instanceof DataManager||t instanceof Date?n[e]=t:"object"==typeof t?n[e]=t._clone():n[e]=t:n[e]=t);return n}}}),Number.prototype.round||(Number.prototype.round=function(e){var t=Math.pow(10,e);return Math.round(this*t)/t}),Number.prototype.pad||(Number.prototype.pad=function(e){for(var t=String(this);t.length<(e||2);)t="0"+t;return t}),Object.observe||Object.unobserve||Object.getNotifier||Object.prototype.__define({observe:{value:function(e,t){e._observers||e.__define({_observers:{value:[],enumerable:!1},_notis:{value:[],enumerable:!1}}),e._observers.push(t)},enumerable:!1},unobserve:{value:function(e,t){if(e._observers){t||(e._observers.length=0);for(var n=0;n<e._observers.length;n++)if(e._observers[n]===t){e._observers.splice(n,1);break}}},enumerable:!1},getNotifier:{value:function(e){var t;return{notify:function(n){e._observers&&n&&(n.object||(n.object=e),e._notis.push(n),n=null,t&&clearTimeout(t),t=setTimeout(function(){e._notis.length&&(e._observers.forEach(function(t){t(e._notis)}),e._notis.length=0),t=!1},4))}}},enumerable:!1}});var $p=new MetaEngine;$p.__define({iface:{value:new InterfaceObjs,writable:!1},current_user:{get:function(){return $p.cat&&$p.cat.users?$p.cat.users.by_id($p.wsql.get_user_param("user_name")):$p.utils.blank.guid; +}},current_acl:{get:function(){var e,t;return $p.cat&&$p.cat.users_acl&&($p.cat.users_acl.find_rows({owner:$p.current_user},function(t){return e=t,!1}),t=$p.CatUsers_acl.prototype),t||(t={}),e||(this.utils.blank.users_acl?e=this.utils.blank.users_acl:(e=this.utils.blank.users_acl=Object.create(t),e.__define({acl_objs:{value:{_obj:[],each:function(){},find_rows:function(){}}}}))),t.hasOwnProperty("role_available")||t.__define({role_available:{value:function(e){return this.acl_objs._obj.some(function(t){return t.type==e})}},get_acl:{value:function(e){var t=e.split(".");return this._acl&&this._acl[t[0]]&&this._acl[t[0]][t[1]]?this._acl[t[0]][t[1]]:"e"}}}),e}},load_script:{value:function(e,t,n){return new Promise(function(a,i){var s=document.createElement(t);"script"==t?(s.type="text/javascript",s.src=e,s.async=!0,s.addEventListener("load",n?function(){n(),a()}:a,!1)):(s.type="text/css",s.rel="stylesheet",s.href=e),document.head.appendChild(s),"script"!=t&&a()})}}}),"undefined"!=typeof window&&window.dhx4&&(dhx4.dateFormat.ru="%d.%m.%Y",dhx4.dateLang="ru",dhx4.dateStrings={ru:{monthFullName:["Январь","Февраль","Март","Апрель","Maй","Июнь","Июль","Август","Сентябрь","Oктябрь","Ноябрь","Декабрь"],monthShortName:["Янв","Фев","Maр","Aпр","Maй","Июн","Июл","Aвг","Сен","Окт","Ноя","Дек"],dayFullName:["Воскресенье","Понедельник","Вторник","Среда","Четверг","Пятница","Суббота"],dayShortName:["Вс","Пн","Вт","Ср","Чт","Пт","Сб"]}}),$p.fias=function(){},function(e){e.toString=function(){return"Коды адресного классификатора"},e.types=["владение","здание","помещение"],e[1010]={name:"дом",type:1,order:1,fid:2,syn:[" д."," д "," дом"]},e[1020]={name:"владение",type:1,order:2,fid:1,syn:[" вл."," вл "," влад."," влад "," владен."," владен "," владение"]},e[1030]={name:"домовладение",type:1,order:3,fid:3},e[1050]={name:"корпус",type:2,order:1,syn:[" к."," к "," корп."," корп ","корпус"]},e[1060]={name:"строение",type:2,order:2,fid:1,syn:[" стр."," стр "," строен."," строен ","строение"]},e[1080]={name:"литера",type:2,order:3,fid:3,syn:[" л."," л "," лит."," лит ","литера"]},e[1070]={name:"сооружение",type:2,order:4,fid:2,syn:[" соор."," соор "," сооруж."," сооруж ","сооружение"]},e[1040]={name:"участок",type:2,order:5,syn:[" уч."," уч ","участок"]},e[2010]={name:"квартира",type:3,order:1,syn:["кв.","кв ","кварт.","кварт ","квартира","-"]},e[2030]={name:"офис",type:3,order:2,syn:["оф.","оф ","офис","-"]},e[2040]={name:"бокс",type:3,order:3},e[2020]={name:"помещение",type:3,order:4},e[2050]={name:"комната",type:3,order:5,syn:["комн.","комн ","комната"]},e[101e5]={name:"Почтовый индекс"},e[102e5]={name:"Адресная точка"},e[103e5]={name:"Садовое товарищество"},e[104e5]={name:"Элемент улично-дорожной сети, планировочной структуры дополнительного адресного элемента"},e[105e5]={name:"Промышленная зона"},e[106e5]={name:"Гаражно-строительный кооператив"},e[107e5]={name:"Территория"}}($p.fias),function(e){e.store_url_od="https://chrome.google.com/webstore/detail/hcncallbdlondnoadgjomnhifopfaage",e.argument_is_not_ref="Аргумент не является ссылкой",e.addr_title="Ввод адреса",e.cache_update_title="Обновление кеша браузера",e.cache_update="Выполняется загрузка измененных файлов<br/>и их кеширование в хранилище браузера",e.cancel="Отмена",e.delivery_area_empty="Укажите район доставки",e.empty_login_password="Не указаны имя пользователя или пароль",e.empty_response="Пустой ответ сервера",e.empty_geocoding="Пустой ответ геокодера. Вероятно, отслеживание адреса запрещено в настройках браузера",e.error_geocoding="Ошибка геокодера",e.error_auth="Авторизация пользователя не выполнена",e.error_critical="Критическая ошибка",e.error_metadata="Ошибка загрузки метаданных конфигурации",e.error_network="Ошибка сети или сервера - запрос отклонен",e.error_rights="Ограничение доступа",e.error_low_acl="Недостаточно прав для выполнения операции",e.file_size="Запрещена загрузка файлов<br/>размером более ",e.file_confirm_delete="Подтвердите удаление файла ",e.file_new_date="Файлы на сервере обновлены<br /> Рекомендуется закрыть браузер и войти<br />повторно для применения обновления",e.file_new_date_title="Версия файлов",e.init_catalogues="Загрузка справочников с сервера",e.init_catalogues_meta=": Метаданные объектов",e.init_catalogues_tables=": Реструктуризация таблиц",e.init_catalogues_nom=": Базовые типы + номенклатура",e.init_catalogues_sys=": Технологические справочники",e.init_login="Укажите имя пользователя и пароль",e.requery="Повторите попытку через 1-2 минуты",e.limit_query="Превышено число обращений к серверу<br/>Запросов за минуту:%1<br/>Лимит запросов:%2<br/>"+e.requery,e.long_operation="Длительная операция",e.logged_in="Авторизован под именем: ",e.log_out_title="Отключиться от сервера?",e.log_out_break="<br/>Завершить синхронизацию?",e.sync_title="Обмен с сервером",e.sync_complite="Синхронизация завершена",e.main_title="Окнософт: заказ дилера ",e.mark_delete_confirm="Пометить объект %1 на удаление?",e.mark_undelete_confirm="Снять пометку удаления с объекта %1?",e.meta={cat:"Справочник",doc:"Документ",cch:"План видов характеристик",cacc:"Планы счетов",tsk:"Задача",ireg:"Регистр сведений",areg:"Регистр накопления",bp:"Бизнес процесс",ts_row:"Строка табличной части",dp:"Обработка",rep:"Отчет"},e.meta_cat="Справочники",e.meta_doc="Документы",e.meta_cch="Планы видов характеристик",e.meta_cacc="Планы счетов",e.meta_tsk="Задачи",e.meta_ireg="Регистры сведений",e.meta_areg="Регистры накопления",e.meta_mgr="Менеджер",e.meta_cat_mgr="Менеджер справочников",e.meta_doc_mgr="Менеджер документов",e.meta_enn_mgr="Менеджер перечислений",e.meta_ireg_mgr="Менеджер регистров сведений",e.meta_areg_mgr="Менеджер регистров накопления",e.meta_accreg_mgr="Менеджер регистров бухгалтерии",e.meta_dp_mgr="Менеджер обработок",e.meta_task_mgr="Менеджер задач",e.meta_bp_mgr="Менеджер бизнес-процессов",e.meta_reports_mgr="Менеджер отчетов",e.meta_charts_of_accounts_mgr="Менеджер планов счетов",e.meta_charts_of_characteristic_mgr="Менеджер планов видов характеристик",e.meta_extender="Модификаторы объектов и менеджеров",e.modified_close="Объект изменен<br/>Закрыть без сохранения?",e.mandatory_title="Обязательный реквизит",e.mandatory_field="Укажите значение реквизита '%1'",e.no_metadata="Не найдены метаданные объекта '%1'",e.no_selected_row="Не выбрана строка табличной части '%1'",e.no_dhtmlx="Библиотека dhtmlx не загружена",e.not_implemented="Не реализовано в текущей версии",e.offline_request="Запрос к серверу в автономном режиме",e.onbeforeunload="Окнософт: легкий клиент. Закрыть программу?",e.order_sent_title="Подтвердите отправку заказа",e.order_sent_message="Отправленный заказ нельзя изменить.<br/>После проверки менеджером<br/>он будет запущен в работу",e.report_error="<i class='fa fa-exclamation-circle fa-2x fa-fw'></i> Ошибка",e.report_prepare="<i class='fa fa-spinner fa-spin fa-2x fa-fw'></i> Подготовка отчета",e.report_need_prepare="<i class='fa fa-info fa-2x fa-fw'></i> Нажмите 'Сформировать' для получения отчета",e.report_need_online="<i class='fa fa-plug fa-2x fa-fw'></i> Нет подключения. Отчет недоступен в автономном режиме",e.request_title="Запрос регистрации",e.request_message="Заявка зарегистрирована. После обработки менеджером будет сформировано ответное письмо",e.select_from_list="Выбор из списка",e.select_grp="Укажите группу, а не элемент",e.select_elm="Укажите элемент, а не группу",e.select_file_import="Укажите файл для импорта",e.srv_overload="Сервер перегружен",e.sub_row_change_disabled="Текущая строка подчинена продукции.<br/>Строку нельзя изменить-удалить в документе<br/>только через построитель",e.sync_script="Обновление скриптов приложения:",e.sync_data="Синхронизация с сервером выполняется:<br />* при первом старте программы<br /> * при обновлении метаданных<br /> * при изменении цен или технологических справочников",e.sync_break="Прервать синхронизацию",e.sync_no_data="Файл не содержит подходящих элементов для загрузки",e.tabular_will_cleared="Табличная часть '%1' будет очищена. Продолжить?",e.unsupported_browser_title="Браузер не поддерживается",e.unsupported_browser="Несовместимая версия браузера<br/>Рекомендуется Google Chrome",e.supported_browsers="Рекомендуется Chrome, Safari или Opera",e.unsupported_mode_title="Режим не поддерживается",e.unsupported_mode="Программа не установлена<br/> в <a href='"+e.store_url_od+"'>приложениях Google Chrome</a>",e.unknown_error="Неизвестная ошибка в функции '%1'",e.value="Значение"}($p.msg),DataManager.prototype.__define({family_name:{get:function(){return $p.msg["meta_"+this.class_name.split(".")[0]+"_mgr"].replace($p.msg.meta_mgr+" ","")}},table_name:{get:function(){return this.class_name.replace(".","_")}},find_rows:{value:function(e,t){return $p._find_rows.call(this,this.by_ref,e,t)}},extra_fields:{value:function(e){var t=$p.cat.destinations||$p.cch.destinations,n=_md.class_name_to_1c(this.class_name).replace(".","_"),a=[];return t&&t.find_rows({predefined_name:n},function(e){var t=e.extra_fields||e.ДополнительныеРеквизиты;return t&&t.each(function(e){e._deleted||e.ПометкаУдаления||a.push(e.property||e.Свойство)}),!1}),a}},extra_properties:{value:function(e){return[]}},obj_constructor:{value:function(e){var t=this.class_name.split("."),n=t[0].charAt(0).toUpperCase()+t[0].substr(1)+t[1].charAt(0).toUpperCase()+t[1].substr(1);return e?n+e.charAt(0).toUpperCase()+e.substr(1)+"Row":n}}}),DataManager.prototype.sync_grid=function(e,t){function n(){if("function"==typeof e.custom_selection)return e.custom_selection(e);if("ram"==i.cachable){if("get_tree"==e.action)return $p.wsql.promise(i.get_sql_struct(e),[]).then($p.iface.data_to_tree);if("get_selection"==e.action)return $p.wsql.promise(i.get_sql_struct(e),[]).then(function(t){return $p.iface.data_to_grid.call(i,t,e)})}else if(0==i.cachable.indexOf("doc")){if("get_tree"==e.action)return i.pouch_tree(e);if("get_selection"==e.action)return i.pouch_selection(e)}else{if("get_tree"==e.action)return i.rest_tree(e);if("get_selection"==e.action)return i.rest_selection(e)}}function a(e){return new Promise(function(n,a){"string"==typeof e?("{"==e.substr(0,1)&&(e=JSON.parse(e)),t&&t.parse?(t.xmlFileUrl="exec",t.parse(e,function(){n(e)},"xml")):n(e)):t instanceof dhtmlXTreeView&&t.loadStruct?t.loadStruct(e,function(){n(e)}):n(e)})}var i=this;return n().then(a).catch($p.record_log)},DataManager.prototype.get_option_list=function(e,t){function n(t){return $p.utils.is_equal(t.value,e)&&(t.selected=!0),t}var a,i,s,o=this,r=[];if(t.presentation&&(a=o.metadata().input_by_string)&&(i=t.presentation.like,delete t.presentation,t.or=[],a.forEach(function(e){s={},s[e]={like:i},t.or.push(s)})),"ram"==o.cachable||t&&t._local)return o.find_rows(t,function(e){r.push(n({text:e.presentation,value:e.ref}))}),Promise.resolve(r);if("e1cib"!=o.cachable)return o.pouch_find_rows(t).then(function(e){return e.forEach(function(e){r.push(n({text:e.presentation,value:e.ref}))}),r});var l={selection:t,top:t._top},c=o instanceof DocManager||o instanceof BusinessProcessManager;return delete t._top,c?l.fields=["ref","date","number_doc"]:o.metadata().main_presentation_name?l.fields=["ref","name"]:l.fields=["ref","id"],_rest.load_array(l,o).then(function(e){return e.forEach(function(e){r.push(n({text:c?e.number_doc+" от "+$p.moment(e.date).format($p.moment._masks.ldt):e.name||e.id,value:e.ref}))}),r})},DataManager.prototype.tabular_captions=function(e,t){},DataManager.prototype.get_property_grid_xml=function(e,t,n){var a,i,s,o,r,l,c,p=this,d="<rows>",u=function(){if(!e)if(s=p.metadata(),s.form&&s.form.obj&&s.form.obj.head)e=s.form.obj.head;else{if(e={" ":[]},t instanceof CatObj?(s.code_length&&e[" "].push("id"),s.main_presentation_name&&e[" "].push("name")):t instanceof DocObj&&(e[" "].push("number_doc"),e[" "].push("date")),!t.is_folder)for(a in s.fields)"predefined_name"==a||s.fields[a].hide||e[" "].push(a);s.tabular_sections&&s.tabular_sections.extra_fields&&(e["Дополнительные реквизиты"]=[])}},m=function(e,t){l=$p.utils.is_data_obj(e)?e.presentation:e,t.type.is_ref||(t.type.date_part?l=$p.moment(l).format($p.moment._masks[t.type.date_part]):"boolean"==t.type.types[0]&&(l=l?"1":"0"))},f=function(e){r=_md.control_by_type(s.type,e),m(e,s)},h=function(e,a){if(a){var i=e.property||e.param||e.Параметр||e.Свойство,u=void 0!=e.value?e.value:e.Значение;i.empty()?(c=a+"|empty",r="ro",l="",s={synonym:"?"}):(s={synonym:i.presentation,type:i.type},c=a+"|"+i.ref,f(u),"edn"==r&&(r="calck"),i.mandatory&&(r+='" class="cell_mandatory'))}else if("object"==typeof e)c=e.id,s=n&&n.metadata&&n.metadata[c],s?e.synonym&&(s.synonym=e.synonym):s={synonym:e.synonym},r=e.type,l="",e.hasOwnProperty("txt")?l=e.txt:void 0!==(o=t[c])&&m(o,s.type?s:_md.get(p.class_name,c));else if(n&&n.metadata&&void 0!==(s=n.metadata[e]))c=e,f(o=t[e]);else{if(void 0===(o=t[e]))return;s=_md.get(p.class_name,c=e),f(o)}d+='<row id="'+c+'"><cell>'+(s.synonym||s.name)+'</cell><cell type="'+r+'">'+l+"</cell></row>"};u();for(a in e){" "!=a&&(d+='<row open="1"><cell>'+a+"</cell>");for(i in e[a])h(e[a][i]);if(n&&a==n.title&&t[n.ts]){var _,g=p.extra_fields(t),b="property,param,Свойство,Параметр".split(","),v=t[n.ts]._owner._metadata.tabular_sections[t[n.ts]._name].fields;b.some(function(e){if(v[e])return _=e,!0})&&(t[n.ts].forEach(function(e){var t=g.indexOf(e[_]);t!=-1&&g.splice(t,1)}),g.forEach(function(e){var a=t[n.ts].add();a[_]=e})),t[n.ts].find_rows(n.selection,function(e){h(e,n.ts)})}" "!=a&&(d+="</row>")}return d+="</rows>"},DataManager.prototype.print=function(e,t,n){function a(e){n&&n.progressOff&&n.progressOff(),e&&e.focus()}if(n&&n.progressOn&&n.progressOn(),setTimeout(a,3e3),this._printing_plates[t]instanceof DataObj&&(t=this._printing_plates[t]),t instanceof DataObj&&t.execute)return e instanceof DataObj?t.execute(e).then(a):this.get(e,!0,!0).then(t.execute.bind(t)).then(a);var i={};return $p.ajax.default_attr(i,$p.job_prm.irest_url()),i.url+=this.rest_name+"(guid'"+$p.utils.fix_guid(e)+"')/Print(model="+t+", browser_uid="+$p.wsql.get_user_param("browser_uid")+")",$p.ajax.get_and_show_blob(i.url,i,"get").then(a)},DataManager.prototype.printing_plates=function(){var e={},t=this;return t._printing_plates||(t.metadata().printing_plates?t._printing_plates=t.metadata().printing_plates:("ram"==t.metadata().cachable||t.metadata().cachable&&0==t.metadata().cachable.indexOf("doc"))&&(t._printing_plates={})),!t._printing_plates&&$p.ajax.authorized?($p.ajax.default_attr(e,$p.job_prm.irest_url()),e.url+=t.rest_name+"/Print()",$p.ajax.get_ex(e.url,e).then(function(e){return t._printing_plates=JSON.parse(e.response),t._printing_plates}).catch(function(){}).then(function(e){return e||(t._printing_plates={})})):Promise.resolve(t._printing_plates)},RefDataManager._extend(DataManager),RefDataManager.prototype.__define({push:{value:function(e,t){t&&t!=e.ref?(delete this.by_ref[e.ref],this.by_ref[t]=e):this.by_ref[e.ref]=e}},each:{value:function(e){for(var t in this.by_ref)if(t&&t!=$p.utils.blank.guid&&1==e.call(this,this.by_ref[t]))break}},forEach:{value:function(e){return this.each.call(this,e)}},get:{value:function(e,t,n){var a=this.by_ref[e]||this.by_ref[e=$p.utils.fix_guid(e)];if(!a){if(n&&!t)return;a=new($p[this.obj_constructor()])(e,this,(!0))}return t===!1?a:void 0===t&&e===$p.utils.blank.guid?a:a.is_new()?a.load():t?Promise.resolve(a):a}},create:{value:function(e,t,n){e&&"object"==typeof e||(e={}),e.ref&&$p.utils.is_guid(e.ref)&&!$p.utils.is_empty_guid(e.ref)||(e.ref=$p.utils.generate_guid());var a=this.by_ref[e.ref];if(!a)if(a=new($p[this.obj_constructor()])(e,this),!t&&e.ref&&e.presentation&&2==Object.keys(e).length);else{a instanceof DocObj&&a.date==$p.utils.blank.date&&(a.date=new Date);var i=this.handle_event(a,"after_create");if(this instanceof DocManager||this instanceof TaskManager||this instanceof BusinessProcessManager?a.number_doc||a.new_number_doc():!a.id&&a._metadata.code_length&&a.new_number_doc(),i===!1)return Promise.resolve(a);if("object"==typeof i&&i.then)return i;if("e1cib"==this.cachable&&t){var s={};return $p.ajax.default_attr(s,$p.job_prm.irest_url()),s.url+=this.rest_name+"/Create()",$p.ajax.get_ex(s.url,s).then(function(e){return a._mixin(JSON.parse(e.response),void 0,["ref"])})}}return n?a:Promise.resolve(a)}},unload_obj:{value:function(e){delete this.by_ref[e],this.alatable.some(function(t,n,a){if(t.ref==e)return a.splice(n,1),!0})}},find:{value:function(e,t){return $p._find(this.by_ref,e,t)}},load_array:{value:function(e,t){for(var n,a,i=[],s=0;s<e.length;s++){if(n=$p.utils.fix_guid(e[s]),a=this.by_ref[n])(a.is_new()||t)&&(a._mixin(e[s]),a._set_loaded());else{if("update_only"==t)continue;a=new($p[this.obj_constructor()])(e[s],this),t&&a._set_loaded()}i.push(a)}return i}},first_folder:{value:function(e){for(var t in this.by_ref){var n=this.by_ref[t];if(n.is_folder&&(!e||$p.utils.is_equal(e,n.owner)))return n}return this.get()}},get_sql_struct:{value:function(e){function t(){function t(){var e=[],t="_t_.ref, _t_.`_deleted`";return r.form&&r.form.selection?r.form.selection.fields.forEach(function(t){e.push(t)}):o instanceof DocManager?(e.push("posted"),e.push("date"),e.push("number_doc")):(r.hierarchical&&r.group_hierarchy?e.push("is_folder"):e.push("0 as is_folder"),o instanceof ChartOfAccountManager?(e.push("id"),e.push("name as presentation")):r.main_presentation_name?e.push("name as presentation"):r.code_length?e.push("id as presentation"):e.push("'...' as presentation"),r.has_owners&&e.push("owner"),r.code_length&&e.push("id")),e.forEach(function(e){t+=e.indexOf(" as ")!=-1?", "+e:_md.sql_mask(e,!0)}),t}function n(){var e,t="";if(r.form&&r.form.selection)for(var n in r.form.selection.fields)r.form.selection.fields[n].indexOf(" as ")!=-1&&r.form.selection.fields[n].indexOf("_t_.")==-1&&(e=r.form.selection.fields[n].split(" as "),e[0]=e[0].split("."),e[0].length>1&&(t&&(t+="\n"),t+="left outer join "+e[0][0]+" on "+e[0][0]+".ref = _t_."+e[1]));return t}function a(){var t;return t=o instanceof ChartOfAccountManager?" WHERE ("+(u?0:1):r.hierarchical?r.has_owners?" WHERE ("+(c||u?1:0)+" OR _t_.parent = '"+p+"') AND ("+(l==$p.utils.blank.guid?1:0)+" OR _t_.owner = '"+l+"') AND ("+(u?0:1):" WHERE ("+(c||u?1:0)+" OR _t_.parent = '"+p+"') AND ("+(u?0:1):r.has_owners?" WHERE ("+(l==$p.utils.blank.guid?1:0)+" OR _t_.owner = '"+l+"') AND ("+(u?0:1):" WHERE ("+(u?0:1),o.sql_selection_where_flds?t+=o.sql_selection_where_flds(u):o instanceof DocManager?t+=" OR _t_.number_doc LIKE '"+u+"'":((r.main_presentation_name||o instanceof ChartOfAccountManager)&&(t+=" OR _t_.name LIKE '"+u+"'"),r.code_length&&(t+=" OR _t_.id LIKE '"+u+"'")),t+=") AND (_t_.ref != '"+$p.utils.blank.guid+"')",e.selection&&("function"==typeof e.selection||e.selection.forEach(function(e){for(var n in e)if("function"==typeof e[n])t+="\n AND "+e[n](o,n)+" ";else if(r.fields.hasOwnProperty(n)||"ref"===n)if(e[n]===!0)t+="\n AND _t_."+n+" ";else if(e[n]===!1)t+="\n AND (not _t_."+n+") ";else if("object"==typeof e[n])if($p.utils.is_data_obj(e[n])||$p.utils.is_guid(e[n]))t+="\n AND (_t_."+n+" = '"+e[n]+"') ";else{var a,i=Object.keys(e[n]),s=e[n][i[0]],l=r.fields[n];l&&l.type.is_ref&&(a=_md.value_mgr({},n,l.type,!0,s)),t+="not"==i[0]?"\n AND (not _t_."+n+" = '"+s+"') ":"in"==i[0]?"\n AND (_t_."+n+" in ("+e[n].in.reduce(function(e,t){return e&&(e+=","),e+="number"==typeof t?t.toString():"'"+t+"'"},"")+")) ":"\n AND (_t_."+n+" = '"+s+"') "}else t+="string"==typeof e[n]?"\n AND (_t_."+n+" = '"+e[n]+"') ":"\n AND (_t_."+n+" = "+e[n]+") ";else"is_folder"==n&&r.hierarchical&&r.group_hierarchy})),t}function i(){return o instanceof ChartOfAccountManager?"ORDER BY id":r.hierarchical?r.group_hierarchy?"ORDER BY _t_.is_folder desc, is_initial_value, presentation":"ORDER BY _t_.parent desc, is_initial_value, presentation":"ORDER BY is_initial_value, presentation"}function s(){function t(t){t&&(m=e.set_parent=t.parent.ref,p=m,c=!1),u&&u.indexOf("%")==-1&&(u="%"+u+"%")}r.has_owners&&(l=e.owner,e.selection&&"function"!=typeof e.selection&&e.selection.forEach(function(e){e.owner&&(l="object"==typeof e.owner?e.owner.valueOf():e.owner,delete e.owner)}),l||(l=$p.utils.blank.guid)),d!=$p.utils.blank.guid&&c&&r.hierarchical?t(o.get(d,!1)):t()}var l,c=!e.parent,p=e.parent||$p.utils.blank.guid,d=e.initial_value||$p.utils.blank.guid,u=e.filter||"",m=$p.utils.blank.guid;s();var f;return f=o.sql_selection_list_flds?o.sql_selection_list_flds(d):("SELECT %2, case when _t_.ref = '"+d+"' then 0 else 1 end as is_initial_value FROM `"+o.table_name+"` AS _t_ %j %3 %4 LIMIT 300").replace("%2",t()).replace("%j",n()),f.replace("%3",a()).replace("%4",i())}function n(){var t="CREATE TABLE IF NOT EXISTS ";if(e&&e.postgres){t+=o.table_name+" (ref uuid PRIMARY KEY NOT NULL, _deleted boolean",o instanceof DocManager?t+=", posted boolean, date timestamp with time zone, number_doc character(11)":(r.code_length&&(t+=", id character("+r.code_length+")"),t+=", name character varying(50), is_folder boolean");for(i in r.fields)i.length>30?r.fields[i].short_name?s=r.fields[i].short_name:(c++,s=i[0]+c+i.substr(i.length-27)):s=i,t+=", "+s+_md.sql_type(o,i,r.fields[i].type,!0)+_md.sql_composite(r.fields,i,s,!0);for(i in r.tabular_sections)t+=", ts_"+i+" JSON"}else{t+="`"+o.table_name+"` (ref CHAR PRIMARY KEY NOT NULL, `_deleted` BOOLEAN",t+=o instanceof DocManager?", posted boolean, date Date, number_doc CHAR":", id CHAR, name CHAR, is_folder BOOLEAN";for(i in r.fields)t+=_md.sql_mask(i)+_md.sql_type(o,i,r.fields[i].type)+_md.sql_composite(r.fields,i);for(i in r.tabular_sections)t+=", `ts_"+i+"` JSON"}return t+=")"}function a(){var e=["ref","_deleted"],t="INSERT INTO `"+o.table_name+"` (ref, `_deleted`",n="(?";"cat"==o.class_name.substr(0,3)?(t+=", id, name, is_folder",e.push("id"),e.push("name"),e.push("is_folder")):"doc"==o.class_name.substr(0,3)&&(t+=", posted, date, number_doc",e.push("posted"),e.push("date"),e.push("number_doc"));for(i in r.fields)t+=_md.sql_mask(i),e.push(i);for(i in r.tabular_sections)t+=", `ts_"+i+"`",e.push("ts_"+i);for(t+=") VALUES ",i=1;i<e.length;i++)n+=", ?";return n+=")",t+=n,{sql:t,fields:e,values:n}}var i,s,o=this,r=o.metadata(),l={},c=0,p=e&&e.action?e.action:"create_table";return"create_table"==p?l=n():["insert","update","replace"].indexOf(p)!=-1?l[o.table_name]=a():"select"==p?l="SELECT * FROM `"+o.table_name+"` WHERE ref = ?":"select_all"==p?l="SELECT * FROM `"+o.table_name+"`":"delete"==p?l="DELETE FROM `"+o.table_name+"` WHERE ref = ?":"drop"==p?l="DROP TABLE IF EXISTS `"+o.table_name+"`":"get_tree"==p?l=!e.filter||e.filter.is_folder?"SELECT ref, parent, name as presentation FROM `"+o.table_name+"` WHERE is_folder order by parent, name":"SELECT ref, parent, name as presentation FROM `"+o.table_name+"` order by parent, name":"get_selection"==p&&(l=t()),l}},caption_flds:{value:function(e){var t=e.metadata||this.metadata(),n='<column id="%1" width="%2" type="%3" align="%4" sort="%5">%6</column>',a=[],i="";if(t.form&&t.form.selection?a=t.form.selection.cols:this instanceof DocManager?(a.push(new Col_struct("date","160","ro","left","server","Дата")),a.push(new Col_struct("number_doc","140","ro","left","server","Номер")),t.fields.note&&a.push(new Col_struct("note","*","ro","left","server",t.fields.note.synonym)),t.fields.responsible&&a.push(new Col_struct("responsible","*","ro","left","server",t.fields.responsible.synonym))):this instanceof ChartOfAccountManager?(a.push(new Col_struct("id","140","ro","left","server","Код")),a.push(new Col_struct("presentation","*","ro","left","server","Наименование"))):a.push(new Col_struct("presentation","*","ro","left","server","Наименование")),e.get_header&&a.length){i="<head>";for(var s in a)i+=n.replace("%1",a[s].id).replace("%2",a[s].width).replace("%3",a[s].type).replace("%4",a[s].align).replace("%5",a[s].sort).replace("%6",a[s].caption);i+="</head>"}return{head:i,acols:a}}},load_cached_server_array:{value:function(e,t){var n,a=[],i=this,s=t?{class_name:i.class_name,rest_name:t}:i,o=!t;if(e.forEach(function(e){n=i.get(e.ref||e,!1,!0),(!n||o&&n.is_new())&&a.push(e.ref||e)}),a.length){var r={url:"",selection:{ref:{in:a}}};return o&&(r.fields=["ref"]),$p.rest.build_select(r,s),$p.ajax.get_ex(r.url,r).then(function(t){var n=JSON.parse(t.response);if(o)n=n.value;else{n=n.data;for(var a in n)!n[a].ref&&n[a].id&&(n[a].ref=n[a].id),n[a].Код&&(n[a].id=n[a].Код,delete n[a].Код),n[a]._not_set_loaded=!0}return i.load_array(n),e})}return Promise.resolve(e)}},predefined:{value:function(e){return this._predefined||(this._predefined={}),this._predefined[e]||(this._predefined[e]=this.get(),this.find_rows({predefined_name:e},function(t){return this._predefined[e]=t,!1})),this._predefined[e]}}}),DataProcessorsManager._extend(DataManager),DataProcessorsManager.prototype.__define({create:{value:function(){return new($p[this.obj_constructor()])({},this)}},unload_obj:{value:function(){}}}),EnumManager._extend(RefDataManager),EnumManager.prototype.__define({get:{value:function(e){if(e instanceof EnumObj)return e;e&&e!=$p.utils.blank.guid||(e="_");var t=this[e];return t||(t=new EnumObj({name:e},this)),t}},push:{value:function(e,t){this.__define(t,{value:e})}},each:{value:function(e){this.alatable.forEach(function(t){t.ref&&"_"!=t.ref&&t.ref!=$p.utils.blank.guid&&e.call(this[t.ref])}.bind(this))}}}),EnumManager.prototype.get_sql_struct=function(e){var t="CREATE TABLE IF NOT EXISTS ",n=e&&e.action?e.action:"create_table";return e&&e.postgres?"create_table"==n?t+=this.table_name+" (ref character varying(255) PRIMARY KEY NOT NULL, sequence INT, synonym character varying(255))":["insert","update","replace"].indexOf(n)!=-1?(t={},t[this.table_name]={sql:"INSERT INTO "+this.table_name+" (ref, sequence, synonym) VALUES ($1, $2, $3)",fields:["ref","sequence","synonym"],values:"($1, $2, $3)"}):"delete"==n&&(t="DELETE FROM "+this.table_name+" WHERE ref = $1"):"create_table"==n?t+="`"+this.table_name+"` (ref CHAR PRIMARY KEY NOT NULL, sequence INT, synonym CHAR)":["insert","update","replace"].indexOf(n)!=-1?(t={},t[this.table_name]={sql:"INSERT INTO `"+this.table_name+"` (ref, sequence, synonym) VALUES (?, ?, ?)",fields:["ref","sequence","synonym"],values:"(?, ?, ?)"}):"delete"==n&&(t="DELETE FROM `"+this.table_name+"` WHERE ref = ?"),t},EnumManager.prototype.get_option_list=function(e,t){function n(t){return $p.utils.is_equal(t.value,e)&&(t.selected=!0),t}var a,i=[],s="";if(t)for(var o in t)"_"!=o.substr(0,1)&&("ref"==o?a=t[o].hasOwnProperty("in")?t[o].in:t[o]:s=t[o]);return"object"==typeof s&&(s=s.like?s.like:""),s=s.toLowerCase(),this.alatable.forEach(function(e){if(!s||e.synonym&&e.synonym.toLowerCase().indexOf(s)!=-1){if(a)if(Array.isArray(a)){if(!a.some(function(t){return t.name==e.ref||t.ref==e.ref||t==e.ref}))return}else if(a.name!=e.ref&&a.ref!=e.ref&&a!=e.ref)return;i.push(n({text:e.synonym||"",value:e.ref}))}}),Promise.resolve(i)},RegisterManager._extend(DataManager),RegisterManager.prototype.__define({get_sql_struct:{value:function(e){function t(){function t(){var e=[],t="_t_.ref";if(r.form&&r.form.selection)r.form.selection.fields.forEach(function(t){e.push(t)});else for(var n in r.dimensions)e.push(n);return e.forEach(function(e){t+=e.indexOf(" as ")!=-1?", "+e:_md.sql_mask(e,!0)}),t}function n(){var e,t="";if(r.form&&r.form.selection)for(var n in r.form.selection.fields)r.form.selection.fields[n].indexOf(" as ")!=-1&&r.form.selection.fields[n].indexOf("_t_.")==-1&&(e=r.form.selection.fields[n].split(" as "),e[0]=e[0].split("."),e[0].length>1&&(t&&(t+="\n"),t+="left outer join "+e[0][0]+" on "+e[0][0]+".ref = _t_."+e[1]));return t}function a(){var t=" WHERE ("+(s?0:1);return o.sql_selection_where_flds&&(t+=o.sql_selection_where_flds(s)),t+=")",e.selection&&("function"==typeof e.selection||e.selection.forEach(function(e){for(var n in e)if("function"==typeof e[n])t+="\n AND "+e[n](o,n)+" ";else if(r.fields.hasOwnProperty(n))if(e[n]===!0)t+="\n AND _t_."+n+" ";else if(e[n]===!1)t+="\n AND (not _t_."+n+") ";else if("object"==typeof e[n])if($p.utils.is_data_obj(e[n]))t+="\n AND (_t_."+n+" = '"+e[n]+"') ";else{var a,i=Object.keys(e[n]),s=e[n][i[0]],l=r.fields[n];l&&l.type.is_ref&&(a=_md.value_mgr({},n,l.type,!0,s)),t+="not"==i[0]?"\n AND (not _t_."+n+" = '"+s+"') ":"\n AND (_t_."+n+" = '"+s+"') "}else t+="string"==typeof e[n]?"\n AND (_t_."+n+" = '"+e[n]+"') ":"\n AND (_t_."+n+" = "+e[n]+") ";else"is_folder"==n&&r.hierarchical&&r.group_hierarchy})),t}function i(){return""}var s=e.filter||"";s&&s.indexOf("%")==-1&&(s="%"+s+"%");var l;return l=o.sql_selection_list_flds?o.sql_selection_list_flds():("SELECT %2 FROM `"+o.table_name+"` AS _t_ %j %3 %4 LIMIT 300").replace("%2",t()).replace("%j",n()),l.replace("%3",a()).replace("%4",i())}function n(){var t="CREATE TABLE IF NOT EXISTS ",n=!0;if(e&&e.postgres){t+=o.table_name+" (",r.splitted&&(t+="zone integer",n=!1);for(s in r.dimensions)n?(t+=s,n=!1):t+=", "+s,t+=_md.sql_type(o,s,r.dimensions[s].type,!0)+_md.sql_composite(r.dimensions,s,"",!0);for(s in r.resources)t+=", "+s+_md.sql_type(o,s,r.resources[s].type,!0)+_md.sql_composite(r.resources,s,"",!0);for(s in r.attributes)t+=", "+s+_md.sql_type(o,s,r.attributes[s].type,!0)+_md.sql_composite(r.attributes,s,"",!0);t+=", PRIMARY KEY (",n=!0,r.splitted&&(t+="zone",n=!1);for(s in r.dimensions)n?(t+=s,n=!1):t+=", "+s}else{t+="`"+o.table_name+"` (ref CHAR PRIMARY KEY NOT NULL, `_deleted` BOOLEAN";for(s in r.dimensions)t+=_md.sql_mask(s)+_md.sql_type(o,s,r.dimensions[s].type);for(s in r.resources)t+=_md.sql_mask(s)+_md.sql_type(o,s,r.resources[s].type);for(s in r.attributes)t+=_md.sql_mask(s)+_md.sql_type(o,s,r.attributes[s].type)}return t+=")"}function a(){var e="INSERT OR REPLACE INTO `"+o.table_name+"` (",t=[],n=!0;for(s in r.dimensions)n?(e+=s,n=!1):e+=", "+s,t.push(s);for(s in r.resources)e+=", "+s,t.push(s);for(s in r.attributes)e+=", "+s,t.push(s);for(e+=") VALUES (?",s=1;s<t.length;s++)e+=", ?";return e+=")",{sql:e,fields:t}}function i(){var t="SELECT * FROM `"+o.table_name+"` WHERE ",n=!0;e._values=[];for(var a in r.dimensions)n?n=!1:t+=" and ",t+="`"+a+"`=?",e._values.push(e[a]);return n&&(t+="1"),t}var s,o=this,r=o.metadata(),l={},c=e&&e.action?e.action:"create_table";return"create_table"==c?l=n():c in{insert:"",update:"",replace:""}?l[o.table_name]=a():"select"==c?l=i():"select_all"==c?l=i():"delete"==c?l="DELETE FROM `"+o.table_name+"` WHERE ref = ?":"drop"==c?l="DROP TABLE IF EXISTS `"+o.table_name+"`":"get_selection"==c&&(l=t()),l}},get_ref:{value:function(e){if(e instanceof RegisterRow&&(e=e._obj),e.ref)return e.ref;var t="",n=this.metadata().dimensions;for(var a in n)t+=t?"¶":"",t+=n[a].type.is_ref?$p.utils.fix_guid(e[a]):!e[a]&&n[a].type.digits?"0":n[a].date_part?$p.moment(e[a]||$p.utils.blank.date).format($p.moment.defaultFormatUtc):void 0!=e[a]?String(e[a]):"$";return t}},caption_flds:{value:function(e){var t=e.metadata||this.metadata(),n='<column id="%1" width="%2" type="%3" align="%4" sort="%5">%6</column>',a=[],i="";if(t.form&&t.form.selection)a=t.form.selection.cols;else for(var s in t.dimensions)a.push(new Col_struct(s,"*","ro","left","server",t.dimensions[s].synonym));if(e.get_header&&a.length){i="<head>";for(var o in a)i+=n.replace("%1",a[o].id).replace("%2",a[o].width).replace("%3",a[o].type).replace("%4",a[o].align).replace("%5",a[o].sort).replace("%6",a[o].caption);i+="</head>"}return{head:i,acols:a}}},create:{value:function(e){e&&"object"==typeof e||(e={});var t=this.by_ref[e.ref];if(!t){t=new($p[this.obj_constructor()])(e,this);var n=this.handle_event(t,"after_create");if(n===!1)return Promise.resolve(t);if("object"==typeof n&&n.then)return n}return Promise.resolve(t)}}}),InfoRegManager._extend(RegisterManager),InfoRegManager.prototype.slice_first=function(e){},InfoRegManager.prototype.slice_last=function(e){},AccumRegManager._extend(RegisterManager),CatManager._extend(RefDataManager),CatManager.prototype.by_name=function(e){var t;return this.find_rows({name:e},function(e){return t=e,!1}),t||(t=this.get()),t},CatManager.prototype.by_id=function(e){var t;return this.find_rows({id:e},function(e){return t=e,!1}),t||(t=this.get()),t},CatManager.prototype.path=function(e){ +var t,n=[];if(t=e instanceof DataObj?e:this.get(e,!1,!0),t&&n.push({ref:t.ref,presentation:t.presentation}),t&&this.metadata().hierarchical)for(;;){if(t=t.parent,t.empty())break;n.push({ref:t.ref,presentation:t.presentation})}return n},ChartOfCharacteristicManager._extend(CatManager),ChartOfAccountManager._extend(CatManager),DocManager._extend(RefDataManager),TaskManager._extend(CatManager),BusinessProcessManager._extend(CatManager),LogManager._extend(InfoRegManager),MetaObjManager._extend(CatManager),MetaFieldManager._extend(CatManager),SchemeSettingsManager._extend(CatManager),DataObj.prototype._getter=function(e){var t,n=this._metadata.fields[e].type,a=this._obj?this._obj[e]:"";return"type"==e&&"object"==typeof a?a:"ref"==e?a:n.is_ref?n.digits&&"number"==typeof a?a:n.hasOwnProperty("str_len")&&!$p.utils.is_guid(a)?a:(t=_md.value_mgr(this._obj,e,n))?$p.utils.is_data_mgr(t)?t.get(a,!1):$p.utils.fetch_type(a,t):a?(console.log([e,n,this._obj]),null):void 0:n.date_part?$p.utils.fix_date(this._obj[e],!0):n.digits?$p.utils.fix_number(this._obj[e],!n.hasOwnProperty("str_len")):"boolean"==n.types[0]?$p.utils.fix_boolean(this._obj[e]):this._obj[e]||""},DataObj.prototype.__setter=function(e,t){var n,a=this._metadata.fields[e].type;"type"==e&&t.types?this._obj[e]=t:"ref"==e?this._obj[e]=$p.utils.fix_guid(t):a.is_ref?a.digits&&"number"==typeof t||a.hasOwnProperty("str_len")&&"string"==typeof t&&!$p.utils.is_guid(t)?this._obj[e]=t:(this._obj[e]=$p.utils.fix_guid(t),n=_md.value_mgr(this._obj,e,a,!1,t),n?n instanceof EnumManager?"string"==typeof t?this._obj[e]=t:t?"object"==typeof t&&(this._obj[e]=t.ref||t.name||""):this._obj[e]="":t&&t.presentation?(!t.type||t instanceof DataObj||delete t.type,n.create(t)):$p.utils.is_data_mgr(n)||(this._obj[e]=$p.utils.fetch_type(t,n)):"object"!=typeof t&&(this._obj[e]=t)):a.date_part?this._obj[e]=$p.utils.fix_date(t,!0):a.digits?this._obj[e]=$p.utils.fix_number(t,!a.hasOwnProperty("str_len")):"boolean"==a.types[0]?this._obj[e]=$p.utils.fix_boolean(t):this._obj[e]=t},DataObj.prototype.__notify=function(e){this._data._silent||Object.getNotifier(this).notify({type:"update",name:e,oldValue:this._obj[e]})},DataObj.prototype._setter=function(e,t){this._obj[e]!=t&&(this.__notify(e),this.__setter(e,t),this._data._modified=!0)},DataObj.prototype._getter_ts=function(e){return this._ts_(e)},DataObj.prototype._setter_ts=function(e,t){var n=this._ts_(e);n instanceof TabularSection&&Array.isArray(t)&&n.load(t)},DataObj.prototype.__define({valueOf:{value:function(){return this.ref}},toJSON:{value:function(){return this._obj}},toString:{value:function(){return this.presentation}},_metadata:{get:function(){return this._manager.metadata()}},_deleted:{get:function(){return!!this._obj._deleted}},_modified:{get:function(){return!!this._data&&!!this._data._modified}},is_new:{value:function(){return this._data._is_new}},_set_loaded:{value:function(e){return this._manager.push(this,e),this._data._modified=!1,this._data._is_new=!1,this}},mark_deleted:{value:function(e){return this._obj._deleted=!!e,this.save(),this.__notify("_deleted"),this}},ref:{get:function(){return this._obj.ref},set:function(e){this._obj.ref=$p.utils.fix_guid(e)},enumerable:!0,configurable:!0},empty:{value:function(){return $p.utils.is_empty_guid(this._obj.ref)}},load:{value:function(){var e=function(){return e=null,this._data._modified=!1,this}.bind(this);return this.ref==$p.utils.blank.guid?(this instanceof CatObj?this.id="000000000":this.number_doc="000000000",Promise.resolve(this)):this._manager.cachable&&"e1cib"!=this._manager.cachable?$p.wsql.pouch.load_obj(this).then(e):_rest.load_obj(this).then(e)}},unload:{value:function(){var e,t=this._obj;this._manager.unload_obj(this.ref),this._observers&&(this._observers.length=0),this._notis&&(this._notis.length=0);for(e in this._metadata.tabular_sections)this[e].clear(!0);for(e in this)this.hasOwnProperty(e)&&delete this[e];for(e in t)delete t[e];["_ts_","_obj","_data"].forEach(function(e){delete this[e]}.bind(this)),e=t=null}},save:{value:function(e,t,n){if(this instanceof DocObj&&"boolean"==typeof e){var a=this.posted;this.posted=e}var i,s=this._manager.handle_event(this,"before_save"),o=function(){return s===!1?this instanceof DocObj&&"boolean"==typeof a&&this.posted!=a&&(this.posted=a):this._data._modified=!1,i=null,s=null,o=null,this}.bind(this);if(s===!1)return Promise.reject(o());if(s instanceof Promise||"object"==typeof s&&s.then)return s.then(o);if(this._metadata.hierarchical&&!this._obj.parent&&(this._obj.parent=$p.utils.blank.guid),this instanceof DocObj||this instanceof TaskObj||this instanceof BusinessProcessObj?($p.utils.blank.date==this.date&&(this.date=new Date),this.number_doc||this.new_number_doc()):this.id||this.new_number_doc(),$p.msg&&$p.msg.show_msg)for(var r in this._metadata.fields)if(this._metadata.fields[r].mandatory&&!this._obj[r])return $p.msg.show_msg({title:$p.msg.mandatory_title,type:"alert-error",text:$p.msg.mandatory_field.replace("%1",this._metadata.fields[r].synonym)}),s=!1,Promise.reject(o());return i=this._manager.cachable&&"e1cib"!=this._manager.cachable?$p.wsql.pouch.save_obj:_rest.save_irest,i(this,{post:e,operational:t,attachments:n}).then(function(e){return e._manager.handle_event(e,"after_save")}).then(o)}},get_attachment:{value:function(e){return this._manager.get_attachment(this.ref,e)}},save_attachment:{value:function(e,t,n){return this._manager.save_attachment(this.ref,e,t,n).then(function(t){return this._attachments||(this._attachments={}),this._attachments[e]&&t.stub||(this._attachments[e]=t),t}.bind(this))}},delete_attachment:{value:function(e){return this._manager.delete_attachment(this.ref,e).then(function(t){return this._attachments&&delete this._attachments[e],t}.bind(this))}},_silent:{value:function(e){"boolean"==typeof e?this._data._silent=e:(this._data._silent=!0,setTimeout(function(){this._data._silent=!1}.bind(this)))}},print:{value:function(e,t){return this._manager.print(this,e,t)}}}),CatObj._extend(DataObj),CatObj.prototype.__define("id",{get:function(){return this._obj.id||""},set:function(e){this.__notify("id"),this._obj.id=e},enumerable:!0}),CatObj.prototype.__define("name",{get:function(){return this._obj.name||""},set:function(e){this.__notify("name"),this._obj.name=String(e)},enumerable:!0}),DocObj._extend(DataObj),DocObj.prototype.__define({posted:{get:function(){return this._obj.posted||!1},set:function(e){this.__notify("posted"),this._obj.posted=$p.utils.fix_boolean(e)},enumerable:!0}}),doc_props_date_number(DocObj.prototype),DataProcessorObj._extend(DataObj),TaskObj._extend(CatObj),doc_props_date_number(TaskObj.prototype),BusinessProcessObj._extend(CatObj),doc_props_date_number(BusinessProcessObj.prototype),EnumObj._extend(DataObj),EnumObj.prototype.__define({order:{get:function(){return this._obj.sequence},set:function(e){this._obj.sequence=parseInt(e)},enumerable:!0},name:{get:function(){return this._obj.ref},set:function(e){this._obj.ref=String(e)},enumerable:!0},synonym:{get:function(){return this._obj.synonym||""},set:function(e){this._obj.synonym=String(e)},enumerable:!0},presentation:{get:function(){return this.synonym||this.name}},empty:{value:function(){return!this.ref||"_"==this.ref}}}),RegisterRow._extend(DataObj),RegisterRow.prototype.__define({_metadata:{get:function(){var e=this._manager.metadata();return e.fields||(e.fields={}._mixin(e.dimensions)._mixin(e.resources)._mixin(e.attributes)),e}},ref:{get:function(){return this._manager.get_ref(this)},enumerable:!0},presentation:{get:function(){return this._metadata.obj_presentation||this._metadata.synonym}}}),TabularSection.prototype.toString=function(){return"Табличная часть "+this._owner._manager.class_name+"."+this._name},TabularSection.prototype.get=function(e){return this._obj[e]?this._obj[e]._row:null},TabularSection.prototype.count=function(){return this._obj.length},TabularSection.prototype.clear=function(e){for(var t in this._obj)delete this._obj[t];return this._obj.length=0,e||this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name}),this},TabularSection.prototype.del=function(e,t){var n,a=this._obj;if("undefined"!=typeof e){if("number"==typeof e)n=e;else if(a[e.row-1]._row===e)n=e.row-1;else for(var i in a)if(a[i]._row===e){n=Number(i),delete a[i]._row;break}void 0!=n&&(a.splice(n,1),a.forEach(function(e,t){e.row=t+1}),t||this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name}),this._owner._data._modified=!0)}},TabularSection.prototype.find=function(e,t){var n=$p._find(this._obj,e,t);if(n)return n._row},TabularSection.prototype.find_rows=function(e,t){var n=this,a=t?function(e){return t.call(n,e._row)}:null;return $p._find_rows.call(n,n._obj,e,a)},TabularSection.prototype.swap=function(e,t){var n=this._obj[e];this._obj[e]=this._obj[t],this._obj[t]=n,this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name})},TabularSection.prototype.add=function(e,t){var n=new($p[this._owner._manager.obj_constructor(this._name)])(this);e||(e={});for(var a in n._metadata.fields)n[a]=e[a]||"";return n._obj.row=this._obj.push(n._obj),n._obj.__define("_row",{value:n,enumerable:!1}),t||this._owner._data._silent||Object.getNotifier(this._owner).notify({type:"rows",tabular:this._name}),e=null,this._owner._data._modified=!0,n},TabularSection.prototype.each=function(e){var t=this;t._obj.forEach(function(n){return e.call(t,n._row)})},TabularSection.prototype.forEach=TabularSection.prototype.each,TabularSection.prototype.group_by=function(e,t){try{var n=this.aggregate(e,t,"SUM",!0);return this.clear(!0).load(n)}catch(e){}},TabularSection.prototype.sort=function(e){"string"==typeof e&&(e=e.split(","));var t="select * from ? order by ",n=!0;e.forEach(function(e){e=e.trim().replace(/\s{1,}/g," ").split(" "),n?n=!1:t+=", ",t+="`"+e[0]+"`",e[1]&&(t+=" "+e[1])});try{return n=$p.wsql.alasql(t,[this._obj]),this.clear(!0).load(n)}catch(e){$p.record_log(e)}},TabularSection.prototype.aggregate=function(e,t,n,a){if("string"==typeof e&&(e=e.split(",")),"string"==typeof t&&(t=t.split(",")),n||(n="sum"),!e.length&&1==t.length&&"sum"==n)return this._obj.reduce(function(e,n,a,i){return e+n[t[0]]},0);var i,s=!0;t.forEach(function(e){i?i+=", "+n+"(`"+e+"`) `"+e+"`":i="select "+n+"(`"+e+"`) `"+e+"`"}),e.forEach(function(e){i?i+=", `"+e+"`":i="select `"+e+"`"}),i+=" from ? ",e.forEach(function(e){s?(i+="group by ",s=!1):i+=", ",i+="`"+e+"`"});try{return s=$p.wsql.alasql(i,[this._obj]),a||(s=1==t.length?s.length?s[0][t[0]]:0:s.length?s[0]:{}),s}catch(e){$p.record_log(e)}},TabularSection.prototype.load=function(e){var t,n=this;return n.clear(!0),e instanceof TabularSection?t=e._obj:Array.isArray(e)&&(t=e),t&&t.forEach(function(e){n.add(e,!0)}),this._owner._data._silent||Object.getNotifier(n._owner).notify({type:"rows",tabular:n._name}),n},TabularSection.prototype.sync_grid=function(e,t){for(var n={rows:[]},a=[],i=0;i<e.getColumnCount();i++)a.push(e.getColumnId(i));if(e.clearAll(),this.find_rows(t,function(e){var t=[];a.forEach(function(n){$p.utils.is_data_obj(e[n])?t.push(e[n].presentation):t.push(e[n])}),n.rows.push({id:e.row,data:t})}),e.objBox)try{e.parse(n,"json"),e.callEvent("onGridReconstructed",[])}catch(e){}},TabularSection.prototype.toJSON=function(){return this._obj},TabularSectionRow.prototype.__define("_metadata",{get:function(){return this._owner._owner._metadata.tabular_sections[this._owner._name]},enumerable:!1}),TabularSectionRow.prototype.__define("row",{get:function(){return this._obj.row||0},enumerable:!0}),TabularSectionRow.prototype.__define("_clone",{value:function(){return new($p[this._owner._owner._manager.obj_constructor(this._owner._name)])(this._owner)._mixin(this._obj)},enumerable:!1}),TabularSectionRow.prototype._getter=DataObj.prototype._getter,TabularSectionRow.prototype._setter=function(e,t){if(this._obj[e]!=t&&(t||this._obj[e]!=$p.utils.blank.guid)){if(this._owner._owner._data._silent||Object.getNotifier(this._owner._owner).notify({type:"row",row:this,tabular:this._owner._name,name:e,oldValue:this._obj[e]}),this._metadata.fields[e].choice_type){var n;n=2==this._metadata.fields[e].choice_type.path.length?this[this._metadata.fields[e].choice_type.path[1]]:this._owner._owner[this._metadata.fields[e].choice_type.path[0]],n&&n.type&&(t=$p.utils.fetch_type(t,n.type))}DataObj.prototype.__setter.call(this,e,t),this._owner._owner._data._modified=!0}};var _rest=$p.rest=new Rest;DataManager.prototype.__define("rest_name",{get:function(){var e=this.class_name.split("."),t={cat:"Catalog",doc:"Document",ireg:"InformationRegister",areg:"AccumulationRegister",cch:"ChartOfCharacteristicTypes",cacc:"ChartOfAccounts",tsk:"Task",bp:"BusinessProcess"};return t[e[0]]+"_"+_md.syns_1с(e[1])},enumerable:!1}),DataManager.prototype.rest_tree=function(e){var t,n,a=this,i=a.metadata(),s=[];return $p.ajax.default_attr(e,!i.irest&&$p.job_prm.rest?$p.job_prm.rest_url():$p.job_prm.irest_url()),e.url+=this.rest_name+"?allowedOnly=true&$format=json&$top=1000&$select=Ref_Key,DeletionMark,Parent_Key,Description&$filter=IsFolder eq true",$p.ajax.get_ex(e.url,e).then(function(e){return JSON.parse(e.response)}).then(function(e){for(var a=0;a<e.value.length;a++)n=e.value[a],t={ref:n.Ref_Key,_deleted:n.DeletionMark,parent:n.Parent_Key,presentation:n.Description},s.push(t);return $p.iface.data_to_tree(s)})},DataManager.prototype.rest_selection=function(e){if("get_tree"==e.action)return this.rest_tree(e);var t,n,a,i,s,o,r=this,l=r.metadata(),c=[],p=[];return s=function(){var e="$select=Ref_Key,DeletionMark";return l.form&&l.form.selection?l.form.selection.fields.forEach(function(e){c.push(e)}):r instanceof DocManager?(c.push("posted"),c.push("date"),c.push("number_doc")):r instanceof TaskManager?(c.push("name as presentation"),c.push("date"),c.push("number_doc"),c.push("completed")):r instanceof BusinessProcessManager?(c.push("date"),c.push("number_doc"),c.push("started"),c.push("finished")):(l.hierarchical&&l.group_hierarchy?c.push("is_folder"):c.push("0 as is_folder"),l.main_presentation_name?c.push("name as presentation"):l.code_length?c.push("id as presentation"):c.push("'...' as presentation"),l.has_owners&&c.push("owner"),l.code_length&&c.push("id")),c.forEach(function(t){var n;if(t.indexOf(" as ")!=-1)if(n=t.split(" as ")[0].split("."),1==n.length)t=n[0];else{if("_t_"!=n[0])return;t=n[1]}"0"!=t&&(a=_md.syns_1с(t),_md.get(r.class_name,t).type.is_ref&&a.indexOf("_Key")==-1&&_md.get(r.class_name,t).type.types.length&&_md.get(r.class_name,t).type.types[0].indexOf("enm.")==-1&&(a+="_Key"),e+=","+a)}),c.push("ref"),c.push("_deleted"),e}(),$p.ajax.default_attr(e,!l.irest&&$p.job_prm.rest?$p.job_prm.rest_url():$p.job_prm.irest_url()),e.url+=(l.irest&&l.irest.selection?l.irest.selection:this.rest_name)+"?allowedOnly=true&$format=json&$top=1000&"+s,_md.get(r.class_name,"date")&&(e.date_from||e.date_till)&&(e.url+="&$filter="+_rest.filter_date("Date",e.date_from,e.date_till),o=!0),l.hierarchical&&e.parent&&(e.url+=o?" and ":"&$filter=",e.url+="Parent_Key eq guid'"+e.parent+"'",o=!0),l.has_owners&&e.owner&&(e.url+=o?" and ":"&$filter=",e.url+="Owner_Key eq guid'"+e.owner+"'",o=!0),e.filter&&(e.url+=o?" and ":"&$filter=",e.url+="$filter eq '"+e.filter+"'",o=!0),$p.ajax.get_ex(e.url,e).then(function(e){return JSON.parse(e.response)}).then(function(s){for(var o=0;o<s.value.length;o++)n=s.value[o],t={},c.forEach(function(e){var s;if("ref"==e)return void(t[e]=n.Ref_Key);if(e.indexOf(" as ")!=-1?(s=e.split(" as ")[1],e=e.split(" as ")[0].split("."),e=e[e.length-1]):s=e,a=_md.syns_1с(e),i=_md.get(r.class_name,e))if(a.indexOf("_Key")==-1&&i.type.is_ref&&i.type.types.length&&i.type.types[0].indexOf("enm.")==-1&&(a+="_Key"),i.type.date_part)t[s]=$p.moment(n[a]).format($p.moment._masks[i.type.date_part]);else if(i.type.is_ref)if(n[a]&&n[a]!=$p.utils.blank.guid){var o=_md.value_mgr(t,e,i.type,!1,n[a]);o?t[s]=o.get(n[a]).presentation:t[s]=""}else t[s]="";else t[s]=n[a]}),p.push(t);return $p.iface.data_to_grid.call(r,p,e)})},InfoRegManager.prototype.rest_slice_last=function(e){e.period||(e.period=$p.utils.date_add_day(new Date,1));var t=this,n=t.metadata(),a="Period=datetime'"+$p.moment(e.period).format($p.moment._masks.iso)+"'",i="";for(var s in n.dimensions)if(void 0!==e[s]){var o=_md.syns_1с(s),r=n.dimensions[s];o.indexOf("_Key")==-1&&r.type.is_ref&&r.type.types.length&&r.type.types[0].indexOf("enm.")==-1?(o+="_Key",i&&(i+=" and "),i+=o+" eq guid'"+e[s].ref+"'"):(i&&(i+=" and "),i+=r.type.digits?o+" eq "+$p.utils.fix_number(e[s]):r.type.date_part?o+" eq datetime'"+$p.moment(e[s]).format($p.moment._masks.iso)+"'":o+" eq '"+e[s]+"'")}return i&&(a+=",Condition='"+i+"'"),$p.ajax.default_attr(e,$p.job_prm.rest_url()),e.url+=this.rest_name+"/SliceLast(%sl)?allowedOnly=true&$format=json&$top=1000".replace("%sl",a),_rest.ajax_to_data(e,t).then(function(e){return t.load_array(e)})},DataObj.prototype.to_atom=function(e){function t(e){var t=e._metadata.fields,i=e instanceof TabularSectionRow?"\n\t<d:":"\n<d:";for(n in t){if(a=t[n],r=_md.syns_1с(n),l=e[n],l instanceof EnumObj)l=l.empty()?"":l.name;else if(l instanceof DataObj)r.indexOf("_Key")==-1&&(r+="_Key"),l=l.ref;else if(a.type.date_part)l=l.getFullYear()<1e3?"0001-01-01T00:00:00Z":$p.moment(l).format($p.moment.defaultFormatUtc);else if(void 0==l)continue;p+=i+r+">"+l+"</d:"+r+">"}}var n,a,i,s,o,r,l,c='<entry><category term="StandardODATA.%n" scheme="http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"/>\t\t\t\t\n<title type="text"/><updated>%d</updated><author/><summary/><content type="application/xml">\t\t\t\t\n<m:properties xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">\t\t\t%p\t\t\t\n</m:properties></content></entry>'.replace("%n",this._manager.rest_name).replace("%d",$p.moment().format($p.moment.defaultFormatUtc)),p="\n<d:Ref_Key>"+this.ref+"</d:Ref_Key>\n<d:DeletionMark>"+this._deleted+"</d:DeletionMark>";this instanceof DocObj?(p+="\n<d:Date>"+$p.moment(this.date).format($p.moment.defaultFormatUtc)+"</d:Date>",p+="\n<d:Number>"+this.number_doc+"</d:Number>"):(this._metadata.main_presentation_name&&(p+="\n<d:Description>"+this.name+"</d:Description>"),this._metadata.code_length&&(p+="\n<d:Code>"+this.id+"</d:Code>"),this._metadata.hierarchical&&this._metadata.group_hierarchy&&(p+="\n<d:IsFolder>"+this.is_folder+"</d:IsFolder>")),t(this);for(i in this._metadata.tabular_sections)o=this._metadata.tabular_sections[i],r="StandardODATA."+this._manager.rest_name+"_"+_md.syns_1с(i)+"_RowType",s=this[i],s.count()?(p+="\n<d:"+_md.syns_1с(i)+' m:type="Collection('+r+')">',s.each(function(e){p+='\n\t<d:element m:type="'+r+'">',p+="\n\t<d:LineNumber>"+e.row+"</d:LineNumber>",t(e),p+="\n\t</d:element>"}),p+="\n</d:"+_md.syns_1с(i)+">"):p+="\n<d:"+_md.syns_1с(i)+' m:type="Collection('+r+')" />';return c.replace("%p",p)},DataManager.prototype.__define({pouch_load_array:{value:function(e,t){var n={limit:e.length+1,include_docs:!0,keys:e.map(function(e){return this.class_name+"|"+e}.bind(this))};return t&&(n.attachments=!0,n.binary=!0),this.pouch_db.allDocs(n).then(function(e){return $p.wsql.pouch.load_changes(e,{})})}},pouch_load_view:{value:function(e){var t,n=this,a=[],i={limit:1e3,include_docs:!0,startkey:n.class_name+"|",endkey:n.class_name+"|￿"};return new Promise(function(s,o){function r(l,c){c?c.rows.length?(i.startkey=c.rows[c.rows.length-1].key,i.skip=1,c.rows.forEach(function(e){t=e.doc,key=t._id.split("|"),t.ref=key[1],a.push(t)}),n.load_array(a),a.length=0,n.pouch_db.query(e,i,r)):s():l&&o(l)}n.pouch_db.query(e,i,r)})}},pouch_db:{get:function(){return this.cachable.indexOf("_remote")!=-1?$p.wsql.pouch.remote[this.cachable.replace("_remote","")]:$p.wsql.pouch.local[this.cachable]||$p.wsql.pouch.remote[this.cachable]}},pouch_find_rows:{value:function(e){var t,n,a,i,s,o,r=this,l=[],c=0,p=0,d=0,u={limit:100,include_docs:!0,startkey:r.class_name+"|",endkey:r.class_name+"|￿"};return e&&(e._top?(s=e._top,delete e._top):s=300,e._raw&&(n=e._raw,delete e._raw),e._total_count&&(i=e._total_count,delete e._total_count),e._view&&(a=e._view,delete e._view),e._key&&("des"==e._key._order_by?(u.startkey=e._key.endkey||e._key+"￿",u.endkey=e._key.startkey||e._key,u.descending=!0):(u.startkey=e._key.startkey||e._key,u.endkey=e._key.endkey||e._key+"￿")),"number"==typeof e._skip&&(p=e._skip,delete e._skip),e._attachments&&(u.attachments=!0,u.binary=!0,delete e._attachments)),i&&(o=!0,i=0,Object.keys(e).length<=1&&e._key&&e._key.hasOwnProperty("_search"))?(u.include_docs=!1,u.limit=1e5,r.pouch_db.query(a,u).then(function(t){return t.rows.forEach(function(t){if(!e._key._search||t.key[t.key.length-1].toLowerCase().indexOf(e._key._search)!=-1){if(i++,p&&(d++,d<p))return;if(s&&(c++,c>s))return;l.push(t.id)}}),delete u.startkey,delete u.endkey,u.descending&&delete u.descending,u.keys=l,u.include_docs=!0,r.pouch_db.allDocs(u)}).then(function(e){return{rows:e.rows.map(function(e){var t=e.doc;return t.ref=t._id.split("|")[1],n||(delete t._id,delete t._rev),t}),_total_count:i}})):new Promise(function(m,f){function h(a,h){h?h.rows.length?(u.startkey=h.rows[h.rows.length-1].key,u.skip=1,h.rows.forEach(function(a){t=a.doc,key=t._id.split("|"),t.ref=key[1],n||(delete t._id,delete t._rev),$p._selection.call(r,t,e)&&(o&&i++,p&&(d++,d<p)||s&&(c++,c>s)||l.push(t))}),s&&c>s&&!o?m(n?l:r.load_array(l)):_()):m(o?{rows:n?l:r.load_array(l),_total_count:i}:n?l:r.load_array(l)):a&&f(a)}function _(){a?r.pouch_db.query(a,u,h):r.pouch_db.allDocs(u,h)}_()})}},pouch_selection:{value:function(e){var t,n,a,i=this,s=e.metadata||i.metadata(),o=["ref","_deleted"],r={_raw:!0,_total_count:!0,_top:e.count||30,_skip:e.start||0},l=[];if(s.form&&s.form.selection?s.form.selection.fields.forEach(function(e){o.push(e)}):i instanceof DocManager?(o.push("posted"),o.push("date"),o.push("number_doc")):i instanceof TaskManager?(o.push("name as presentation"),o.push("date"),o.push("number_doc"),o.push("completed")):i instanceof BusinessProcessManager?(o.push("date"),o.push("number_doc"),o.push("started"),o.push("finished")):(s.hierarchical&&s.group_hierarchy?o.push("is_folder"):o.push("0 as is_folder"),s.main_presentation_name?o.push("name as presentation"):s.code_length?o.push("id as presentation"):o.push("'...' as presentation"),s.has_owners&&o.push("owner"),s.code_length&&o.push("id")),_md.get(i.class_name,"date")&&(e.date_from||e.date_till)&&(e.date_from||(e.date_from=new Date("2015-01-01")),e.date_till||(e.date_till=$p.utils.date_add_day(new Date,1)),r.date={between:[e.date_from,e.date_till]}),s.hierarchical&&e.parent&&(r.parent=e.parent),e.selection)if(Array.isArray(e.selection))e.selection.forEach(function(e){for(a in e)"_"==a[0]&&"_view"!=a&&"_key"!=a||(r[a]=e[a])});else for(a in e.selection)"_"==a[0]&&"_view"!=a&&"_key"!=a||(r[a]=e.selection[a]);return r._key&&r._key._drop_date&&r.date&&delete r.date,!e.filter||r._key&&r._key._search||(1==s.input_by_string.length?r[s.input_by_string]={like:e.filter}:(r.or=[],s.input_by_string.forEach(function(t){var n={};n[t]={like:e.filter},r.or.push(n)}))),r._key&&r._key._order_by&&(r._key._order_by=e.direction),i.pouch_find_rows(r).then(function(s){return s.hasOwnProperty("_total_count")&&s.hasOwnProperty("rows")&&(e._total_count=s._total_count,s=s.rows),s.forEach(function(e){t={},o.forEach(function(s){if("ref"==s)return void(t[s]=e[s]);if(s.indexOf(" as ")!=-1?(a=s.split(" as ")[1],s=s.split(" as ")[0].split("."),s=s[s.length-1]):a=s,n=_md.get(i.class_name,s))if(n.type.date_part)t[a]=$p.moment(e[s]).format($p.moment._masks[n.type.date_part]);else if(n.type.is_ref)if(e[s]&&e[s]!=$p.utils.blank.guid){var o=_md.value_mgr(t,s,n.type,!1,e[s]);o?t[a]=o.get(e[s]).presentation:t[a]=""}else t[a]="";else"number"==typeof e[s]&&n.type.fraction_figits?t[a]=e[s].toFixed(n.type.fraction_figits):t[a]=e[s]}),l.push(t)}),$p.iface.data_to_grid.call(i,l,e)}).catch($p.record_log)}},pouch_tree:{value:function(e){return this.pouch_find_rows({is_folder:!0,_raw:!0,_top:e.count||300,_skip:e.start||0}).then(function(e){return e.sort(function(e,t){return e.parent==$p.utils.blank.guid&&t.parent!=$p.utils.blank.guid?-1:t.parent==$p.utils.blank.guid&&e.parent!=$p.utils.blank.guid?1:e.name<t.name?-1:e.name>t.name?1:0}),e.map(function(e){return{ref:e.ref,parent:e.parent,presentation:e.name}})}).then($p.iface.data_to_tree)}},save_attachment:{value:function(e,t,n,a){a||(a={type:"text/plain"}),n instanceof Blob||a.indexOf("text")!=-1||(n=new Blob([n],{type:a}));var i,s=this.pouch_db;return e=this.class_name+"|"+$p.utils.fix_guid(e),s.get(e).then(function(e){e&&(i=e._rev)}).catch(function(e){if(404!=e.status)throw e}).then(function(){return s.putAttachment(e,t,i,n,a)})}},get_attachment:{value:function(e,t){return this.pouch_db.getAttachment(this.class_name+"|"+$p.utils.fix_guid(e),t)}},delete_attachment:{value:function(e,t){var n,a=this.pouch_db;return e=this.class_name+"|"+$p.utils.fix_guid(e),a.get(e).then(function(e){e&&(n=e._rev)}).catch(function(e){if(404!=e.status)throw e}).then(function(){return a.removeAttachment(e,t,n)})}}}),DataObj.prototype.__define({new_number_doc:{value:function(e){if(this._metadata.code_length){e||(e=($p.current_acl&&$p.current_acl.prefix||"")+(this.organization&&this.organization.prefix?this.organization.prefix:$p.wsql.get_user_param("zone")+"-"));var t=this,n="",a=this.date instanceof Date?this.date.getFullYear():0,i=this._metadata.code_length-e.length;return"ram"==this._manager.cachable?Promise.resolve(this.new_cat_id(e)):t._manager.pouch_db.query("doc/number_doc",{limit:1,include_docs:!1,startkey:[t._manager.class_name,a,e+"￿"],endkey:[t._manager.class_name,a,e],descending:!0}).then(function(a){if(a.rows.length){for(var s=a.rows[0].key[2],o=s.length-1;o>0&&!isNaN(parseInt(s[o]));o--)n=s[o]+n;n=(parseInt(n||0)+1).toFixed(0)}else n="1";for(;n.length<i;)n="0"+n;return t instanceof DocObj||t instanceof TaskObj||t instanceof BusinessProcessObj?t.number_doc=e+n:t.id=e+n,t})}}},new_cat_id:{value:function(e){e||(e=($p.current_acl&&$p.current_acl.prefix||"")+(this.organization&&this.organization.prefix?this.organization.prefix:$p.wsql.get_user_param("zone")+"-"));var t=this._metadata.code_length-e.length,n=this instanceof DocObj||this instanceof TaskObj||this instanceof BusinessProcessObj?"number_doc":"id",a="",i=$p.wsql.alasql("select top 1 "+n+" as id from ? where "+n+" like '"+e+"%' order by "+n+" desc",[this._manager.alatable]);if(i.length){for(var s=i[0].id||"",o=s.length-1;o>0&&!isNaN(parseInt(s[o]));o--)a=s[o]+a;a=(parseInt(a||0)+1).toFixed(0)}else a="1";for(;a.length<t;)a="0"+a;return this[n]=e+a,this}}}),$p.iface.OBtnAuthSync=function(){function e(){$p.wsql.pouch.authorized?dhtmlx.confirm({title:$p.msg.log_out_title,text:$p.msg.logged_in+$p.wsql.pouch.authorized+$p.msg.log_out_break,cancel:$p.msg.cancel,callback:function(e){e&&$p.wsql.pouch.log_out()}}):$p.iface.frm_auth({modal_dialog:!0})}function t(e){e&&a?clearTimeout(a):i.forEach(function(t){e?t.buttons.sync.innerHTML='<i class="fa fa-refresh fa-spin md-fa-lg"></i>':$p.wsql.pouch.authorized?t.buttons.sync.innerHTML='<i class="fa fa-refresh md-fa-lg"></i>':t.buttons.sync.innerHTML='<i class="fa fa-ban md-fa-lg"></i>'}),a=e?setTimeout(t,3e3):0}function n(){i.forEach(function(e){$p.wsql.pouch.authorized?(e.buttons.auth.title="Отключиться от сервера",e.buttons.auth.innerHTML='<span class="span_user">'+$p.wsql.pouch.authorized+"</span>",e.buttons.sync.title="Синхронизация выполняется...",e.buttons.sync.innerHTML='<i class="fa fa-refresh md-fa-lg"></i>'):(e.buttons.auth.title="Войти на сервер и включить синхронизацию данных",e.buttons.auth.innerHTML=' <i class="fa fa-sign-in md-fa-lg"></i><span class="span_user">Вход...</span>',e.buttons.sync.title="Синхронизация не выполняется - пользователь не авторизован на сервере",e.buttons.sync.innerHTML='<i class="fa fa-ban md-fa-lg"></i>')})}var a,i=[];this.bind=function(t){return t.buttons.auth.onclick=e,t.buttons.sync.onclick=null,i.push(t),setTimeout(n),t},$p.on({pouch_load_data_start:function(e){$p.iface.sync||$p.iface.wnd_sync(),$p.iface.sync.create($p.eve.stepper),$p.eve.stepper.frm_sync.setItemValue("text_bottom","Читаем справочники"),e.hasOwnProperty("local_rows")&&e.local_rows<10?($p.eve.stepper.wnd_sync.setText("Первый запуск - подготовка данных"),$p.eve.stepper.frm_sync.setItemValue("text_processed","Загрузка начального образа")):($p.eve.stepper.wnd_sync.setText("Загрузка данных из IndexedDB"),$p.eve.stepper.frm_sync.setItemValue("text_processed","Извлечение начального образа")),t(!0)},pouch_load_data_page:function(e){if(t(!0),$p.eve.stepper.wnd_sync){var n=e.docs_written||e.page*e.limit;$p.eve.stepper.frm_sync.setItemValue("text_current","Обработано элементов: "+n+" из "+e.total_rows),$p.eve.stepper.frm_sync.setItemValue("text_bottom","Текущий запрос: "+e.page+" ("+(100*n/e.total_rows).toFixed(0)+"%)")}},pouch_change:function(e,n){t(!0)},pouch_load_data_loaded:function(e){$p.eve.stepper.wnd_sync&&(e.docs_written?$p.iface.sync.close():$p.iface.sync.close())},pouch_load_data_error:function(e){t(),$p.eve.stepper.wnd_sync&&$p.iface.sync.close()},log_in:function(e){n()},log_out:function(){n()}})};var eXcell_proto=new eXcell;eXcell_proto.input_keydown=function(e,t){function n(e){t.source.on_select&&t.source.on_select.call(t.source,e)}if(8===e.keyCode||46===e.keyCode)t.setValue(""),t.grid.editStop(),t.source.on_select&&t.source.on_select.call(t.source,"");else if(9===e.keyCode||13===e.keyCode)t.grid.editStop();else if(115===e.keyCode)t.cell.firstChild.childNodes[1].onclick(e);else if(113===e.keyCode)if(t.source.tabular_section){if(t.mgr=_md.value_mgr(t.source.row,t.source.col,t.source.row._metadata.fields[t.source.col].type),t.mgr){var a=t.source.row[t.source.col];t.mgr.form_obj(t.source.wnd,{o:a,on_select:n})}}else if(1==t.fpath.length&&(t.mgr=_md.value_mgr(t.source.o._obj,t.fpath[0],t.source.o._metadata.fields[t.fpath[0]].type),t.mgr)){var a=t.source.o[t.fpath[0]];t.mgr.form_obj(t.source.wnd,{o:a,on_select:n})}return $p.iface.cancel_bubble(e)},eXcell_ocombo.prototype=eXcell_proto,window.eXcell_ocombo=eXcell_ocombo,window.eXcell_ref=eXcell_ocombo,window.eXcell_refc=eXcell_ocombo,eXcell_pwd.prototype=eXcell_proto,window.eXcell_pwd=eXcell_pwd,dhtmlXCalendarObject.prototype._dateToStr=function(e,t){return e instanceof Date&&e.getFullYear()<1e3?"":window.dhx4.date2str(e,t||this._dateFormat,this._dateStrings())},eXcell_dhxCalendar.prototype.edit=function(){var e=this.grid.getPosition(this.cell);this.grid._grid_calendarA._show(!1,!1),this.grid._grid_calendarA.setPosition(e[0],e[1]+this.cell.offsetHeight),this.grid._grid_calendarA._last_operation_calendar=!1,this.grid.callEvent("onCalendarShow",[this.grid._grid_calendarA,this.cell.parentNode.idd,this.cell._cellIndex]),this.cell._cediton=!0,this.val=this.cell.val,this.val instanceof Date&&this.val.getFullYear()<1e3&&(this.val=new Date),this._val=this.cell.innerHTML;var t=this.grid._grid_calendarA.draw;this.grid._grid_calendarA.draw=function(){},this.grid._grid_calendarA.setDateFormat(this.grid._dtmask||"%d.%m.%Y"),this.grid._grid_calendarA.setDate(this.val||new Date),this.grid._grid_calendarA.draw=t},eXcell_dhxCalendar.prototype.setCValue=function(e,t){this.cell.innerHTML=e instanceof Date?this.grid._grid_calendarA._dateToStr(e):e,this.grid._grid_calendarA.getFormatedDate(this.grid._dtmask||"%d/%m/%Y",e).toString(),this.grid.callEvent("onCellChanged",[this.cell.parentNode.idd,this.cell._cellIndex,arguments.length>1?t:e])},function(){function e(e,t,n,a){if(n.indexOf("odata/standard.odata")!=-1||n.indexOf("/hs/rest")!=-1){var i,s;$p.ajax.authorized?(i=$p.ajax.username,s=$p.aes.Ctr.decrypt($p.ajax.password)):$p.job_prm.guest_name?(i=$p.job_prm.guest_name,s=$p.aes.Ctr.decrypt($p.job_prm.guest_pwd)):(i=$p.wsql.get_user_param("user_name"),s=$p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd"))),e.open(t,n,a,i,s),e.withCredentials=!0,e.setRequestHeader("Authorization","Basic "+btoa(unescape(encodeURIComponent(i+":"+s)))); +}else e.open(t,n,a)}dhx4.ajax._call=function(t,n,a,i,s,o,r){var l=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),c=null!=navigator.userAgent.match(/AppleWebKit/)&&null!=navigator.userAgent.match(/Qt/)&&null!=navigator.userAgent.match(/Safari/);if(1==i&&(l.onreadystatechange=function(){if(4==l.readyState||1==c&&3==l.readyState){if((200!=l.status||""==l.responseText)&&!dhx4.callEvent("onAjaxError",[{xmlDoc:l,filePath:n,async:i}]))return;window.setTimeout(function(){"function"==typeof s&&s.apply(window,[{xmlDoc:l,filePath:n,async:i}]),null!=o&&("undefined"!=typeof o.postData?dhx4.ajax.postLong(o.url,o.postData,s):dhx4.ajax.getLong(o.url,s)),s=null,l=null},1)}}),"GET"==t&&(n+=this._dhxr(n)),l.open(t,n,i),e(l,t,n,i),null!=r)for(var p in r)l.setRequestHeader(p,r[p]);else"POST"==t||"PUT"==t||"DELETE"==t?l.setRequestHeader("Content-Type","application/x-www-form-urlencoded"):"GET"==t&&(a=null);return l.setRequestHeader("X-Requested-With","XMLHttpRequest"),l.send(a),1!=i&&(4==l.readyState||1==c&&3==l.readyState)&&(200==l.status&&""!=l.responseText||dhx4.callEvent("onAjaxError",[{xmlDoc:l,filePath:n,async:i}])),{xmlDoc:l,filePath:n,async:i}},dhtmlx.ajax.prototype.send=function(t,n,a){var i=this.getXHR();if("function"==typeof a&&(a=[a]),"object"==typeof n){var s=[];for(var o in n){var r=n[o];null!==r&&r!==dhtmlx.undefined||(r=""),s.push(o+"="+encodeURIComponent(r))}n=s.join("&")}n&&!this.post&&(t=t+(t.indexOf("?")!=-1?"&":"?")+n,n=null),e(i,this.post?"POST":"GET",t,!this._sync),this.post&&i.setRequestHeader("Content-type","application/x-www-form-urlencoded");var l=this;return i.onreadystatechange=function(){if(!i.readyState||4==i.readyState){if(a&&l)for(var e=0;e<a.length;e++)a[e]&&a[e].call(l.master||l,i.responseText,i.responseXML,i);l.master=null,a=l=null}},i.send(n||null),i}}(),dhtmlXCellObject.prototype.is_visible=function(){var e=this.cell.getBoundingClientRect();return e.right>0&&e.bottom>0},$p.iface.data_to_grid=function(e,t){function n(e){var t;return t=e.hasOwnProperty("posted")?e.posted?"cell_doc_posted":"cell_doc":e.is_folder?"cell_ref_folder":"cell_ref_elm",e._deleted&&(t+="_deleted"),t}function a(e){return e instanceof Date?e.getHours()||e.getMinutes()?$p.moment(e).format($p.moment._masks.date_time):$p.moment(e).format($p.moment._masks.date):"number"==typeof e?e:$p.iface.normalize_xml(e||"")}if(this.data_to_grid)return this.data_to_grid(e,t);var i="<?xml version='1.0' encoding='UTF-8'?><rows total_count='%1' pos='%2' set_parent='%3'>".replace("%1",t._total_count||e.length).replace("%2",t.start).replace("%3",t.set_parent||""),s=this.caption_flds(t);return i+=s.head,e.forEach(function(e){i+='<row id="'+e.ref+'"><cell class="'+n(e)+'">'+a(e[s.acols[0].id])+"</cell>";for(var t=1;t<s.acols.length;t++)i+="<cell>"+a(e[s.acols[t].id])+"</cell>";i+="</row>"}),i+"</rows>"},$p.iface.data_to_tree=function(e){function t(n,a){var i={id:a.ref,text:a.presentation,items:[]};n.push(i),$p._find_rows(e,{parent:a.ref},function(e){t(i.items,e)}),i.items.length||delete i.items}var n=[{id:$p.utils.blank.guid,text:"..."}];return $p._find_rows(e,{parent:$p.utils.blank.guid},function(e){t(n,e)}),n},$p.iface.ODropdownList=ODropdownList,dhtmlXCellObject.prototype.attachDynTree=function(e,t,n){this.setCollapsedText&&this.setCollapsedText("Дерево"),t||(t={is_folder:!0});var a=this.attachTreeView();return a.__define({filter:{get:function(){},set:function(e){t=e},enumerable:!1,configurable:!1}}),setTimeout(function(){e.sync_grid({action:"get_tree",filter:t},a).then(function(e){n&&n(e)})}),a},OCombo._extend(dhtmlXCombo),$p.iface.OCombo=OCombo,$p.iface.select_from_list=function(e,t){return new Promise(function(n,a){function i(e){"cancel"!=e&&(s=c.getSelectedRowId()),l.close()}Array.isArray(e)&&e.length?1==e.length&&n(e[0]):n(void 0);var s,o,r={name:"wnd_select_from_list",wnd:{id:"wnd_select_from_list",width:300,height:300,modal:!0,center:!0,caption:$p.msg.select_from_list,allow_close:!0,on_close:function(){return s&&n(e[parseInt(s)-1]),!0}}},l=$p.iface.dat_blank(null,r.wnd),c=l.attachGrid(),p=l.attachToolbar({items:[{id:"select",type:"button",text:$p.msg.select_from_list},{id:"cancel",type:"button",text:"Отмена"}],onClick:i});c.setIconsPath(dhtmlx.image_path),c.setImagePath(dhtmlx.image_path),c.setHeader($p.msg.value),c.setColTypes("ro"),c.enableAutoWidth(!0,1200,600),c.attachEvent("onRowDblClicked",i),c.enableMultiselect(!!t),c.setNoHeader(!0),c.init(),p.addSpacer("select"),l.hideHeader(),l.cell.offsetParent.querySelector(".dhxwin_brd").style.border="none",e.forEach(function(e,t){var n;n="object"==typeof e?e.presentation||e.text||e.toString():e.toString(),c.addRow(1+t,n),e.selected&&(o=1+t)}),o&&c.selectRowById(o)})},$p.iface.ODateRangePicker=ODateRangePicker,dhtmlXCellObject.prototype.attachHeadFields=function(e){function t(e){if(a)u.entBox&&!u.entBox.parentElement?setTimeout(u.destructor):e.forEach(function(e){"unload"==e.type?d&&d.close?d.close():u.destructor():u.forEachRow(function(t){t==e.name&&u.cells(t,1).setValue(a[e.name])})});else{var i=[];e.forEach(function(e){i.indexOf[e.object]==-1&&(i.push(e.object),Object.unobserve(e.object,t),c&&c instanceof TabularSection&&Object.unobserve(e.object,n))}),i=null}}function n(t){var n;t.forEach(function(t){!n&&u.clearAll&&l==t.tabular&&(n=!0,u.clearAll(),u.parse(o.get_property_grid_xml(i,a,{title:e.ts_title,ts:l,selection:r,metadata:s}),function(){},"xml"))})}var a,i,s,o,r,l,c,p,d=this,u=d.attachGrid(),m=u.destructor;return new dhtmlXPropertyGrid(u),u.setInitWidthsP("40,60"),u.setDateFormat("%d.%m.%Y %H:%i"),u.init(),u.setSizes(),u.attachEvent("onPropertyChanged",function(e,t,n){if(e||u&&u.getSelectedRowId())return p.on_select(t)}),u.attachEvent("onCheckbox",function(e,t,n){return void 0!=a[e]?p.on_select(n,{obj:a,field:e}):e.split("|").length>1?p.on_select(n,u.get_cell_field(e)):void 0}),u.attachEvent("onKeyPress",function(e,t,n){switch(e){case 13:case 9:u.editStop&&u.editStop();break;case 46:}}),e.read_only&&u.setEditable(!1),u.__define({selection:{get:function(){return r},set:function(e){r=e,this.reload()}},reload:{value:function(){n([{tabular:l}])}},get_cell_field:{value:function(e){if(a){var t={row_id:e||u.getSelectedRowId()},n=t.row_id.split("|");if(n.length<2)return{obj:a,field:n[0]}._mixin(p);var i;return r?a[n[0]].find_rows(r,function(e){if(e.property==n[1]||e.param==n[1]||e.Свойство==n[1]||e.Параметр==n[1])return i=e,!1}):i=a[n[0]].find(n[1]),i?(t.obj=i,i["Значение"]?(t.field="Значение",t.property=i.Свойство||i.Параметр):(t.field="value",t.property=i.property||i.param),t._mixin(p)):void 0}},enumerable:!1},_obj:{get:function(){return a}},_owner_cell:{get:function(){return d}},destructor:{value:function(){a&&Object.unobserve(a,t),c&&c instanceof TabularSection&&Object.unobserve(c,n),a=null,c=null,s=null,o=null,p=null,m.call(u)}},attach:{value:function(e){a&&Object.unobserve(a,t),c&&c instanceof TabularSection&&Object.unobserve(a,n),e.oxml&&(i=e.oxml),e.selection&&(r=e.selection),a=e.obj,s=e.metadata||a._metadata.fields,o=a._manager,l=e.ts||"",c=l?a[l]:a.extra_fields||a["ДополнительныеРеквизиты"],c&&!l&&(l=a.extra_fields?"extra_fields":"ДополнительныеРеквизиты"),p={on_select:function(e,t){if(t||(t=u.get_cell_field()),t){var n=o.handle_event(a,"value_change",{field:t.field,value:e,tabular_section:t.row_id?l:"",grid:u,cell:u.cells(t.row_id||t.field,1),wnd:p.pwnd});return"boolean"!=typeof n&&(t.obj[t.field]=e,n=!0),n}},pwnd:e.pwnd||d},Object.observe(a,t,["update","unload"]),c&&c instanceof TabularSection&&Object.observe(a,n,["row","rows"]),l&&!e.ts_title&&(e.ts_title=a._metadata.tabular_sections[l].synonym),n([{tabular:l}])}}}),e&&u.attach(e),u},dhtmlXGridObject.prototype.get_cell_value=function(){var e=this.get_cell_field();if(e&&e.obj)return e.obj[e.field]},dhtmlXCellObject.prototype.attachTabular=function(e){function t(e){var t=f.getSelectedRowId();return t&&!isNaN(Number(t))?Number(t)-1:void(e||$p.msg.show_msg({type:"alert-warning",text:$p.msg.no_selected_row.replace("%1",o._metadata.tabular_sections[r].synonym||r),title:(o._metadata.obj_presentation||o._metadata.synonym)+": "+o.presentation}))}function n(e,t,n,a,i){if(2!=e||a==i)return!0;var s=f.get_cell_field(),l=c.handle_event(o,"value_change",{field:s.field,value:a,tabular_section:r,grid:f,row:s.obj,cell:t&&n?f.cells(t,n):f.getSelectedCellIndex()>=0?f.cells():null,wnd:g.pwnd});return"boolean"!=typeof l&&(s.obj[s.field]=a,l=!0),l}function a(e){f.clearAll&&e.some(function(e){if("rows"==e.type&&e.tabular==r)return l.sync_grid(f,m),!0})}function i(e){if(e.length>20)try{l.sync_grid(f,m)}catch(e){}else e.forEach(function(e){r==e.tabular&&(e.row&&f.getSelectedRowId()==e.row.row?void 0!=f.getColIndexById(e.name)&&f.cells(e.row.row,f.getColIndexById(e.name)).setCValue($p.utils.is_data_obj(e.row[e.name])?e.row[e.name].presentation:e.row[e.name]):l.sync_grid(f,m))})}function s(e){if(e.clipboardData.types.indexOf("text/plain")!=-1)try{$p.eve.callEvent("tabular_paste",[{obj:o,grid:f,tsname:r,e:e,data:e.clipboardData.getData("text/plain")}])}catch(e){return}}var o=e.obj,r=e.ts,l=o[r],c=o._manager,p=e.metadata||c.metadata().tabular_sections[r].fields,d=this,u=e.ts_captions||{},m=e.selection;if(e.ts_captions||_md.ts_captions(c.class_name,r,u)){var f=this.attachGrid(),h=this.attachToolbar(),_=f.destructor,g={on_select:function(e){n(2,null,null,e)},pwnd:e.pwnd||d,is_tabular:!0};return f.setDateFormat("%d.%m.%Y %H:%i"),f.enableAccessKeyMap(),f._add_row=function(){if(!e.read_only){var t;if(m)for(var n in m)p[n]&&("object"!=typeof m[n]||$p.is_data_obj(m[n]))&&(t||(t={}),t[n]=m[n]);var a=l.add(t);if(c.handle_event(o,"add_row",{tabular_section:r,grid:f,row:a,wnd:g.pwnd})===!1)return;setTimeout(function(){f.selectRowById(a.row)},100)}},f._del_row=function(){if(!e.read_only){var n=t();if(void 0!=n){if(c.handle_event(o,"del_row",{tabular_section:r,grid:f,row:n,wnd:g.pwnd})===!1)return;l.del(n),setTimeout(function(){f.selectRowById(n<l.count()?n+1:n)},100)}}},h.setIconsPath(dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()),h.loadStruct(e.toolbar_struct||$p.injected_data["toolbar_add_del.xml"],function(){this.attachEvent("onclick",function(e){switch(e){case"btn_add":f._add_row();break;case"btn_delete":f._del_row()}})}),f.setIconsPath(dhtmlx.image_path),f.setImagePath(dhtmlx.image_path),f.setHeader(u.headers),u.min_widths&&f.setInitWidths(u.widths),u.min_widths&&f.setColumnMinWidth(u.min_widths),u.aligns&&f.setColAlign(u.aligns),f.setColSorting(u.sortings),f.setColTypes(u.types),f.setColumnIds(u.fields.join(",")),f.enableAutoWidth(!0,1200,600),f.enableEditTabOnly(!0),f.init(),e.read_only&&(f.setEditable(!1),h.forEachItem(function(e){["btn_add","btn_delete"].indexOf(e)!=-1&&h.disableItem(e)})),f.__define({selection:{get:function(){return m},set:function(e){m=e,a([{tabular:r,type:"rows"}])}},destructor:{value:function(){o&&(Object.unobserve(o,i),Object.unobserve(o,a)),o=null,l=null,p=null,c=null,g=null,d.detachToolbar(),f.entBox.removeEventListener("paste",s),_.call(f)}},get_cell_field:{value:function(){if(l){var e,n,a=t(!0),i=f.getSelectedCellIndex();if(void 0!=a?e=l.get(a):f._last&&(e=l.get(f._last.row)),i>=0?n=f.getColumnId(i):f._last&&(n=f.getColumnId(f._last.cindex)),e&&n)return{obj:e,field:n,metadata:p[n]}._mixin(g)}}},refresh_row:{value:function(e){f.selectRowById(e.row),f.forEachCell(e.row,function(t,n){var a=e[f.getColumnId(n)];t.setCValue($p.utils.is_data_obj(a)?a.presentation:a)})}}}),f.attachEvent("onEditCell",n),f.attachEvent("onRowSelect",function(e,t){l&&(f._last={row:e-1,cindex:t})}),a([{tabular:r,type:"rows"}]),Object.observe(o,i,["row"]),Object.observe(o,a,["rows"]),f.entBox.addEventListener("paste",s),f}},$p.iface.Toolbar_filter=function(e){function t(){i&&clearTimeout(i),i=setTimeout(function(){i&&a.call_event()},500)}function n(e,t){"min"==t?a.сalendar.setSensitiveRange(e.value,null):a.сalendar.setSensitiveRange(null,e.value)}var a=this,i=0,s="desktop"==$p.job_prm.device_type?300:120,o={};e.pos||(e.pos=6),a.__define({custom_selection:{get:function(){return o},enumerable:!1,configurable:!1},toolbar:{get:function(){return e.toolbar},enumerable:!1,configurable:!1},call_event:{value:function(){i&&(clearTimeout(i),i=0),e.onchange.call(a,a.get_filter())}}}),a.toolbar.addText("div_filter",e.pos,""),a.div=a.toolbar.objPull[a.toolbar.idPrefix+"div_filter"],e.pos++,(e.manager instanceof DocManager||e.manager instanceof BusinessProcessManager||e.manager instanceof TaskManager||e.period)&&(s="desktop"==$p.job_prm.device_type?180:120,a.toolbar.addInput("input_date_from",e.pos,"","desktop"==$p.job_prm.device_type?80:72),e.pos++,a.toolbar.addText("lbl_date_till",e.pos,"-"),e.pos++,a.toolbar.addInput("input_date_till",e.pos,"","desktop"==$p.job_prm.device_type?80:72),e.pos++,a.input_date_from=a.toolbar.getInput("input_date_from"),a.input_date_from.onclick=function(){n(a.input_date_till,"max")},a.input_date_till=a.toolbar.getInput("input_date_till"),a.input_date_till.onclick=function(){n(a.input_date_from,"min")},a.сalendar=new dhtmlXCalendarObject([a.input_date_from,a.input_date_till]),a.сalendar.attachEvent("onclick",a.call_event),e.date_from||(e.date_from=new Date((new Date).getFullYear().toFixed()+"-01-01")),e.date_till||(e.date_till=$p.utils.date_add_day(new Date,1)),a.input_date_from.value=$p.moment(e.date_from).format("L"),a.input_date_till.value=$p.moment(e.date_till).format("L"),"doc"!=e.manager.cachable||e.custom_selection||(o._view={get value(){return"doc/by_date"}},o._key={get value(){var t=a.get_filter(!0);return{startkey:[e.manager.class_name,t.date_from.getFullYear(),t.date_from.getMonth()+1,t.date_from.getDate()],endkey:[e.manager.class_name,t.date_till.getFullYear(),t.date_till.getMonth()+1,t.date_till.getDate()],_drop_date:!0,_order_by:!0,_search:t.filter.toLowerCase()}}})),e.hide_filter?a.input_date_till?a.toolbar.addSpacer("input_date_till"):a.toolbar.addSpacer("div_filter"):(a.toolbar.addSeparator("filter_sep",e.pos),e.pos++,a.toolbar.addInput("input_filter",e.pos,"",s),a.input_filter=a.toolbar.getInput("input_filter"),a.input_filter.onchange=a.call_event,a.input_filter.onclick=function(){var e=a.input_filter.value;setTimeout(function(){e!=a.input_filter.value&&a.call_event()})},a.input_filter.onkeydown=t,a.input_filter.type="search",a.input_filter.setAttribute("placeholder","Фильтр"),a.toolbar.addSpacer("input_filter"))},$p.iface.Toolbar_filter.prototype.__define({get_filter:{value:function(e){var t,n,a={date_from:this.input_date_from?$p.utils.date_add_day(dhx4.str2date(this.input_date_from.value),0,!0):"",date_till:this.input_date_till?$p.utils.date_add_day(dhx4.str2date(this.input_date_till.value),1,!0):"",filter:this.input_filter?this.input_filter.value:""};if(!e)for(t in this.custom_selection)a.selection||(a.selection=[]),n={},n[t]=this.custom_selection[t].value,a.selection.push(n);return a}},add_filter:{value:function(e){var t=this.toolbar.getPosition("input_filter")-2,n=dhx4.newId(),a=(this.toolbar.getWidth("input_filter")/2).round(0);this.toolbar.setWidth("input_filter",a),this.toolbar.addText("lbl_"+n,t,e.text||""),t++,this.toolbar.addInput("input_"+n,t,"",a),this.custom_selection[e.name]=this.toolbar.getInput("input_"+n)}}}),$p.iface.dat_blank=function(e,t){t||(t={});var n,a=(e||$p.iface.w).createWindow({id:dhx4.newId(),left:t.left||700,top:t.top||20,width:t.width||220,height:t.height||300,move:!0,park:!t.allow_close,center:!!t.center,resize:!0,caption:t.caption||"Tools"}),i={x:(e||$p.iface.w).vp.clientWidth,y:(e||$p.iface.w).vp.clientHeight};return a.getPosition()[0]+a.getDimension()[0]>i.x?(i.x=i.x-a.getDimension()[0],n=!0):i.x=a.getPosition()[0],a.getPosition()[1]+a.getDimension()[1]>i.y?(i.y=i.y-a.getDimension()[1],n=!0):i.y=a.getPosition()[1],n&&(i.x<0||i.y<0?a.maximize():a.setPosition(i.x,i.y)),e=null,t.hasOwnProperty("allow_minmax")&&!t.allow_minmax&&a.button("minmax").hide(),t.allow_close?a.button("park").hide():a.button("close").hide(),a.attachEvent("onClose",function(){var e="function"!=typeof t.on_close||t.on_close(a);if(e)return t.pwnd_modal&&t.pwnd&&t.pwnd.setModal&&t.pwnd.setModal(1),e}),a.setIconCss("without_icon"),a.cell.parentNode.children[1].classList.add("dat_gui"),$p.iface.bind_help(a,t.help_path),a.elmnts={grids:{}},a.wnd_options=function(e){var t=a.getPosition(),n=a.getDimension(),i=a.isParked();e.left=t[0],e.top=t[1],e.width=n[0],e.parked=i,i||(e.height=n[1])},a.bottom_toolbar=function(e){var t={wrapper:a.cell,width:"100%",height:"28px",bottom:"0px",left:"0px",name:"tb_bottom",buttons:[{name:"btn_cancel",text:"Отмена",title:"Закрыть без сохранения",width:"60px",float:"right"},{name:"btn_ok",b:"Ок",title:"Применить изменения",width:"30px",float:"right"}],onclick:function(e){return!1}}._mixin(e),n=new OTooolBar(t),i=a.attachStatusBar({height:12});return i.style.zIndex=-1e3,i.firstChild.style.backgroundColor="transparent",i.firstChild.style.border="none",n},t.modal&&(t.pwnd&&t.pwnd.setModal&&(t.pwnd_modal=t.pwnd.isModal(),t.pwnd.setModal(0)),a.setModal(1)),a},$p.iface.pgrid_on_select=function(e){if(void 0!==e){var t=this.grid instanceof dhtmlXGridObject?this.grid:this,n=t.getUserData("","source"),a=t.getSelectedRowId();if(void 0!=n.o[a])"number"==typeof n.o[a]?n.o[a]=$p.utils.fix_number(e,!0):n.o[a]=e;else if(a.indexOf("fprms")>-1){var i=$p._find(n.o.fprms,a.split("|")[1]);i.value=e}t.cells().setValue($p.utils.is_data_obj(e)?e.presentation:e||""),n.grid_on_change&&n.grid_on_change.call(t,a,e)}},$p.iface.pgrid_on_change=function(e,t,n){e&&$p.iface.pgrid_on_select.call(this,t)},$p.iface.pgrid_on_checkbox=function(e,t,n){var a=this.grid instanceof dhtmlXGridObject?this.grid:this,i=a.getUserData("","source");void 0!=i.o[e]&&(i.o[e]=n),i.grid_on_change&&i.grid_on_change(e,n)},$p.iface.frm_auth=function(e,t,n){function a(n,a){$p.ajax.username=n,$p.ajax.password=$p.aes.Ctr.encrypt(a),n?($p.wsql.get_user_param("user_name")!=n&&$p.wsql.set_user_param("user_name",n),$p.wsql.pouch.log_in(n,a).then(function(){$p.wsql.get_user_param("enable_save_pwd")?$p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd"))!=a&&$p.wsql.set_user_param("user_pwd",$p.aes.Ctr.encrypt(a)):""!=$p.wsql.get_user_param("user_pwd")&&$p.wsql.set_user_param("user_pwd",""),$p.eve.logged_in=!0,e.modal_dialog?s.close():t&&t()}).catch(function(e){l=!0,o.onerror(e)}).then(function(){$p.iface.sync&&$p.iface.sync.close(),s&&s.progressOff&&(s.progressOff(),!l&&e.hide_header&&s.hideHeader()),$p.iface.cell_tree&&!l&&$p.iface.cell_tree.expand()})):this.validate()}function i(e){if(l=!1,this.resetValidateCss(),"guest"==this.getCheckedValue("type")){var t=this.getItemValue("guest"),n="";$p.job_prm.guests&&$p.job_prm.guests.length&&$p.job_prm.guests.some(function(e){if(e.username==t)return n=$p.aes.Ctr.decrypt(e.password),!0}),a.call(this,t,n)}else"auth"==this.getCheckedValue("type")&&a.call(this,this.getItemValue("login"),this.getItemValue("password"))}e||(e={});var s,o,r,l;e.modal_dialog?(e.options||(e.options={name:"frm_auth",caption:"Вход на сервер",width:360,height:300,center:!0,allow_close:!0,allow_minmax:!0,modal:!0}),s=$p.iface.dat_blank(e._dxw,e.options),s.attachEvent("onClose",function(e){return l?n&&n(err):t&&t(),!0}),o=s.attachForm()):(s=e.cell||$p.iface.docs,o=$p.iface.auth=s.attachForm(),$p.msg.show_msg($p.msg.init_login,s)),o.loadStruct($p.injected_data["form_auth.xml"],function(){var t;if($p.job_prm.guests&&$p.job_prm.guests.length){var n=$p.job_prm.guests.map(function(e){var n={text:e.username,value:e.username};return $p.wsql.get_user_param("user_name")==e.username&&(n.selected=!0,t=e.username),n});t||(n[0].selected=!0,t=n[0].value),o.reloadOptions("guest",n)}$p.wsql.get_user_param("user_name")&&$p.wsql.get_user_param("user_name")!=t&&(o.setItemValue("login",$p.wsql.get_user_param("user_name")),o.setItemValue("type","auth"),$p.wsql.get_user_param("enable_save_pwd")&&$p.wsql.get_user_param("user_pwd")&&o.setItemValue("password",$p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd")))),e.modal_dialog||((r=((s.getWidth?s.getWidth():s.cell.offsetWidth)-500)/2)>=10?o.cont.style.paddingLeft=r.toFixed()+"px":o.cont.style.paddingLeft="20px"),setTimeout(function(){dhx4.callEvent("on_draw_auth",[o]),($p.wsql.get_user_param("autologin")||e.try_auto)&&(t||$p.wsql.get_user_param("user_name")&&$p.wsql.get_user_param("user_pwd"))&&i.call(o)})}),o.attachEvent("onButtonClick",i),o.attachEvent("onKeyDown",function(e,t,n,a){13==t.keyCode&&("password"!=n&&"guest"!=this.getCheckedValue("type")||i.call(this))}),o.onerror=function(e){$p.ajax.authorized=!1;var t=e.message.toLowerCase();t.indexOf("auth")!=-1?($p.msg.show_msg({title:$p.msg.main_title+$p.version,type:"alert-error",text:$p.msg.error_auth}),o.setItemValue("password",""),o.validate()):t.indexOf("gateway")==-1&&t.indexOf("net")==-1||$p.msg.show_msg({title:$p.msg.main_title+$p.version,type:"alert-error",text:$p.msg.error_network})}},$p.iface.open_settings=function(e){var t=e||("undefined"!=typeof event?event:void 0);t&&t.preventDefault();var n=$p.job_prm.parse_url();return $p.iface.set_hash(n.obj,n.ref,n.frm,"settings"),$p.iface.cancel_bubble(t)},$p.iface.swith_view=function(e){var t,n=$p.iface,a=function(e){function t(e,t){return e.text>t.text?1:e.text<t.text?-1:void 0}if(n.tree){if(n.tree._view!=e&&["rep","cal"].indexOf(e)==-1){if(n.tree.deleteChildItems(0),"oper"==e){var a,i,s={id:0,item:[{id:"oper_cat",text:$p.msg.meta_cat,open:!0,item:[]},{id:"oper_doc",text:$p.msg.meta_doc,item:[]},{id:"oper_cch",text:$p.msg.meta_cch,item:[]},{id:"oper_cacc",text:$p.msg.meta_cacc,item:[]},{id:"oper_tsk",text:$p.msg.meta_tsk,item:[]}]},o=s.item[0].item;for(a in $p.cat)"function"!=typeof $p.cat[a]&&(i=$p.cat[a].metadata(),i.hide||o.push({id:"oper.cat."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),o=s.item[1].item;for(a in $p.doc)"function"!=typeof $p.doc[a]&&(i=$p.doc[a].metadata(),i.hide||o.push({id:"oper.doc."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),o=s.item[2].item;for(a in $p.cch)"function"!=typeof $p.cch[a]&&(i=$p.cch[a].metadata(),i.hide||o.push({id:"oper.cch."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),o=s.item[3].item;for(a in $p.cacc)"function"!=typeof $p.cacc[a]&&(i=$p.cacc[a].metadata(),i.hide||o.push({id:"oper.cacc."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),o=s.item[4].item;for(a in $p.tsk)"function"!=typeof $p.tsk[a]&&(i=$p.tsk[a].metadata(),i.hide||o.push({id:"oper.tsk."+a,text:i.synonym||i.name,tooltip:i.illustration||i.list_presentation}));o.sort(t),n.tree.parse(s,function(){var e=$p.job_prm.parse_url();e.obj&&n.tree.selectItem(e.view+"."+e.obj,!0)},"json")}else n.tree.loadXML(n.tree.tree_filteres,function(){});n.tree._view=e}}else{var r=$p.job_prm.parse_url();if(r.obj){var l=r.obj.split(".");if(l.length>1){var c=$p.md.mgr_by_class_name(r.obj);"function"==typeof n.docs.close&&n.docs.close(),c&&c.form_list(n.docs,{})}}}};return 0==e.indexOf(n.docs.getViewName())?n.docs.getViewName():(t=n.docs.showView(e),1==t&&("cal"!=e||window.dhtmlXScheduler||($p.load_script("dist/dhtmlxscheduler.min.js","script",function(){scheduler.config.first_hour=8,scheduler.config.last_hour=22,n.docs.scheduler=n.docs.attachScheduler(new Date("2015-11-20"),"week","scheduler_here"),n.docs.scheduler.attachEvent("onBeforeViewChange",function(e,t,n,a){return"timeline"!=n||($p.msg.show_not_implemented(),!1)})}),$p.load_script("dist/dhtmlxscheduler.css","link"))),a(e),void("def"==e?n.main.showStatusBar():n.main.hideStatusBar()))},$p.iface.OTooolBar=OTooolBar,$p.iface.add_button=function(e,t,n){var a=document.createElement("div"),i="";return a.name=(t?t.name+"_":"")+n.name,e.appendChild(a),a.className=0==n.name.indexOf("sep_")?"md_otooolbar_sep":"md_otooolbar_button",n.hasOwnProperty("class_name")&&a.classList.add(n.class_name),n.img&&(i='<img src="'+(t?t.image_path:"")+n.img+'">'),n.b?i+='<b style="vertical-align: super;"> '+n.b+"</b>":n.text?i+='<span style="vertical-align: super;"> '+n.text+"</span>":n.css&&a.classList.add(n.css),a.innerHTML=i,n.float&&(a.style.float=n.float),n.clear&&(a.style.clear=n.clear),n.width&&(a.style.width=n.width),n.paddingRight&&(a.style.paddingRight=n.paddingRight),n.paddingLeft&&(a.style.paddingLeft=n.paddingLeft),n.tooltip&&(a.title=n.tooltip),a},"undefined"!=typeof window&&"dhtmlx"in window&&(eXcell_addr.prototype=eXcell_proto,window.eXcell_addr=eXcell_addr),DataManager.prototype.form_obj=function(e,t){function n(){h||((e instanceof dhtmlXLayoutCell||e instanceof dhtmlXSideBarCell||e instanceof dhtmlXCarouselCell)&&(t.bind_pwnd||t.Приклеить)?("function"==typeof e.close&&e.close(!0),m=e,m.close=function(t){var n=m||e;(t||d())&&(n&&(n.elmnts&&["vault","vault_pop"].forEach(function(e){n.elmnts[e]&&n.elmnts[e].unload&&n.elmnts[e].unload()}),v&&v.class_name&&$p.eve.callEvent("frm_close",[v.class_name,y&&y._obj?y.ref:""]),n.conf&&(n.detachToolbar(),n.detachStatusBar(),n.conf.unloading=!0,n.detachObject(!0))),p(t))},m.elmnts={grids:{}}):(f={name:"wnd_obj_"+v.class_name,wnd:{top:80+40*Math.random(),left:120+80*Math.random(),width:700,height:400,modal:!0,center:!1,pwnd:e,allow_close:!0,allow_minmax:!0,on_close:u,caption:x.obj_presentation||x.synonym}},m=$p.iface.dat_blank(null,f.wnd)),m.ref||m.__define({ref:{get:function(){return y?y.ref:$p.utils.blank.guid},enumerable:!1,configurable:!0},set_text:{value:function(e){if(t&&t.set_text||m&&m.setText){var n=y.presentation;if(!n)return;y instanceof CatObj?n=(x.obj_presentation||x.synonym)+": "+n:y instanceof DocObj&&(n+=y.posted?" (проведен)":" (не проведен)"),y._modified&&n.lastIndexOf("*")!=n.length-1?n+=" *":y._modified||n.lastIndexOf("*")!=n.length-1||(n=n.replace(" *","")),(e||g!==n)&&(g=n,t.set_text?t.set_text(n):m.setText(n))}},enumerable:!1,configurable:!0}}),m.elmnts.frm_tabs=m.attachTabbar({arrows_mode:"auto",offsets:{top:0,right:0,bottom:0,left:0}}),m.elmnts.frm_tabs.addTab("tab_header"," Реквизиты ",null,null,!0),m.elmnts.tabs={tab_header:m.elmnts.frm_tabs.cells("tab_header")},m.elmnts.frm_toolbar=m.attachToolbar(),m.elmnts.frm_toolbar.setIconsPath(dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()),m.elmnts.frm_toolbar.loadStruct(t.toolbar_struct||$p.injected_data["toolbar_obj.xml"],function(){m===e&&(this.cont.style.top="4px"),this.addSpacer("btn_unpost"),this.attachEvent("onclick",t.toolbar_click||s);var n=$p.current_acl.get_acl(v.class_name);v instanceof DocManager&&n.indexOf("p")!=-1?(this.enableItem("btn_post"),t.toolbar_struct||this.setItemText("btn_save_close","<b>Провести и закрыть</b>")):this.hideItem("btn_post"),v instanceof DocManager&&n.indexOf("o")!=-1?this.enableItem("btn_unpost"):this.hideItem("btn_unpost"),n.indexOf("e")==-1&&(this.hideItem("btn_save_close"),this.disableItem("btn_save")),t.on_select&&this.setItemText("btn_save_close","Записать и выбрать"),v instanceof CatManager||v instanceof DocManager?(v.printing_plates().then(function(e){for(var t in e)m.elmnts.frm_toolbar.addListOption("bs_print",t,"~","button",e[t].toString())}),m.elmnts.vault_pop=new dhtmlXPopup({toolbar:this,id:"btn_files"}),m.elmnts.vault_pop.attachEvent("onShow",r)):this.disableItem("bs_print"),m!=e&&this.hideItem("btn_close")}),h=!0)}function a(e){y&&m&&m.set_text()}function i(){if(h||(clearTimeout(_),n()),m.set_text(),!t.hide_header&&m.showHeader&&m.showHeader(),t.draw_tabular_sections)t.draw_tabular_sections(y,m,l);else if(!y.is_folder)if(x.form&&x.form.obj&&x.form.obj.tabular_sections_order)x.form.obj.tabular_sections_order.forEach(function(e){l(e)});else for(var e in x.tabular_sections)"extra_fields"!==e&&y[e]instanceof TabularSection&&l(e);if(t.draw_pg_header)t.draw_pg_header(y,m);else{var i=$p.current_acl.get_acl(v.class_name);m.elmnts.pg_header=m.elmnts.tabs.tab_header.attachHeadFields({obj:y,pwnd:m,read_only:i.indexOf("e")==-1}),m.attachEvent("onResizeFinish",function(e){m.elmnts.pg_header.enableAutoHeight(!1,m.elmnts.tabs.tab_header._getHeight()-20,!0)})}return Object.observe(y,a,["update","row"]),{wnd:m,o:y}}function s(e){"btn_save_close"==e?c("close"):"btn_save"==e?c("save"):"btn_post"==e?c("post"):"btn_unpost"==e?c("unpost"):"btn_close"==e?m.close():"btn_go_connection"==e?o():"prn_"==e.substr(0,4)?v.print(y,e,m):"btn_import"==e?v.import(null,y):"btn_export"==e&&v.export({items:[y],pwnd:m,obj:!0})}function o(){$p.msg.show_not_implemented()}function r(){m.elmnts.vault||(m.elmnts.vault=m.elmnts.vault_pop.attachVault(400,250,{_obj:y,buttonClear:!1,autoStart:!0,filesLimit:10,mode:"pouch"}),m.elmnts.vault.conf.wnd=m)}function l(e,t){if(_md.ts_captions(v.class_name,e)){m.elmnts.frm_tabs.addTab("tab_"+e," "+x.tabular_sections[e].synonym+" "),m.elmnts.tabs["tab_"+e]=m.elmnts.frm_tabs.cells("tab_"+e);var n=$p.current_acl.get_acl(v.class_name);if(m.elmnts.grids[e]=m.elmnts.tabs["tab_"+e].attachTabular({obj:y,ts:e,pwnd:m,read_only:n.indexOf("e")==-1,toolbar_struct:t}),n.indexOf("e")==-1){var a=m.elmnts.tabs["tab_"+e].getAttachedToolbar();a.disableItem("btn_add"),a.disableItem("btn_delete")}}}function c(e){m.progressOn();var n;y instanceof DocObj&&("post"==e?n=!0:"unpost"==e?n=!1:"close"==e&&$p.current_acl.get_acl(v.class_name).indexOf("p")!=-1&&(n=!0)),y.save(n).then(function(){m.progressOff(),"close"==e?(t.on_select&&t.on_select(y),m.close()):m.set_text()}).catch(function(e){m.progressOff(),e instanceof Error&&$p.record_log(e)})}function p(n){t&&t.on_close&&!n&&t.on_close(),n||(delete m.ref,delete m.set_text,Object.unobserve(y,a),v=m=y=x=f=e=t=null)}function d(){return!(y._modified&&!b)||(dhtmlx.confirm({title:y.presentation,text:$p.msg.modified_close,cancel:$p.msg.cancel,callback:function(e){e&&(b=!0,"ram"==y._manager.cachable?this.close():y.is_new()?(y.unload(),this.close()):(setTimeout(y.load.bind(y),100),this.close()))}.bind(m)}),!1)}function u(e){if(d())return setTimeout(p),e&&e.elmnts&&["vault","vault_pop"].forEach(function(t){e.elmnts[t]&&e.elmnts[t].unload&&e.elmnts[t].unload()}),v&&v.class_name&&$p.eve.callEvent("frm_close",[v.class_name,y&&y._obj?y.ref:""]),!0}var m,f,h,_,g,b,v=this,x=v.metadata(),y=t.o;return _=setTimeout(n),$p.utils.is_data_obj(y)?y.is_new()&&t.on_select?v.create({},!0).then(function(e){return y=e,e=null,i()}):y.is_new()&&!y.empty()?y.load().then(i):Promise.resolve(i()):(e&&e.progressOn&&e.progressOn(),v.get(t.hasOwnProperty("ref")?t.ref:t,!0,!0).then(function(t){return y=t,t=null,e&&e.progressOff&&e.progressOff(),i()}).catch(function(t){e&&e.progressOff&&e.progressOff(),m.close(),$p.record_log(t)}))},DataObj.prototype.form_obj=function(e,t){return t||(t={}),t.o=this,this._manager.form_obj(e,t)},DataProcessorsManager.prototype.form_rep=function(e,t){function n(){if((e instanceof dhtmlXLayoutCell||e instanceof dhtmlXSideBarCell||e instanceof dhtmlXCarouselCell)&&(t.bind_pwnd||t.Приклеить)){if(o==e&&o._mgr==c)return;"function"==typeof e.close&&e.close(!0),o=e,o.close=function(t){var n=o||e;(t||check_modified())&&(n&&n.conf&&(n.detachToolbar(),n.detachStatusBar(),n.conf.unloading=!0,n.detachObject(!0)),s(t))},o.elmnts={grids:{}}}else r={name:"wnd_rep_"+c.class_name,wnd:{top:80+40*Math.random(),left:120+80*Math.random(),width:700,height:400,modal:!0,center:!1,pwnd:e,allow_close:!0,allow_minmax:!0,on_close:frm_close,caption:p.obj_presentation||p.synonym}},o=$p.iface.dat_blank(null,r.wnd);o._mgr=c,o.report=c.create(),o.set_text||o.__define({set_text:{value:function(e){if(t&&t.set_text||o&&o.setText){var n=p.obj_presentation||p.synonym;(e||l!==n)&&(l=n,t.set_text?t.set_text(n):o.setText(n))}},configurable:!0}}),o.elmnts.layout=o.attachLayout({pattern:"2U",cells:[{id:"a",text:"Отчет",header:!1},{id:"b",text:"Параметры",collapsed_text:"Параметры",width:220}],offsets:{top:0,right:0,bottom:0,left:0}}),o.elmnts.frm_toolbar=o.attachToolbar(),o.elmnts.frm_toolbar.setIconsPath(dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()),o.elmnts.frm_toolbar.loadStruct(t.toolbar_struct||$p.injected_data["toolbar_rep.xml"],function(){o===e&&(this.cont.style.top="4px"),this.addSpacer("btn_run"),this.attachEvent("onclick",t.toolbar_click||a)}),o.set_text(),!t.hide_header&&o.showHeader&&o.showHeader(),o.elmnts.table=new $p.HandsontableDocument(o.elmnts.layout.cells("a"),{ +allow_offline:o.report.allow_offline,autorun:!1}).then(function(e){if(!e._online)return o.elmnts.table=null}),o.elmnts.frm_prm=document.createElement("DIV"),o.elmnts.frm_prm.style="height: 100%; min-height: 300px; width: 100%",o.elmnts.layout.cells("b").attachObject(o.elmnts.frm_prm),o.report.daterange=new $p.iface.ODateRangePicker(o.elmnts.frm_prm,t)}function a(e){"btn_close"==e?o.close():"btn_run"==e&&o.report.build().then(i).catch(i)}function i(e){o.elmnts.table.requery(e)}function s(n){t&&t.on_close&&!n&&t.on_close(),n||(delete o.set_text,o.elmnts.table&&o.elmnts.table.hot.destroy(),o.report.daterange&&o.report.daterange.remove(),o.report=null,c=o=p=r=e=t=null)}var o,r,l,c=this,p=c.metadata();return t||(t={}),t.date_from||(t.date_from=new Date((new Date).getFullYear().toFixed()+"-01-01")),t.date_till||(t.date_till=new Date((new Date).getFullYear().toFixed()+"-12-31")),n(),o},DataManager.prototype.form_selection=function(e,t){function n(){return e instanceof dhtmlXCellObject?(e instanceof dhtmlXTabBarCell||"function"!=typeof e.close||e.close(!0),f=e,f.close=function(t){(f||e)&&((f||e).detachToolbar(),(f||e).detachStatusBar(),(f||e).conf&&((f||e).conf.unloading=!0),(f||e).detachObject(!0)),p(t)},t.hide_header||setTimeout(function(){f.showHeader()})):(f=$p.iface.w.createWindow(null,0,0,700,500),f.centerOnScreen(),f.setModal(1),f.button("park").hide(),f.button("minmax").show(),f.button("minmax").enable(),f.attachEvent("onClose",d)),$p.iface.bind_help(f),f.setText&&!t.hide_text&&f.setText("Список "+(h.class_name.indexOf("doc.")==-1?'справочника "':'документов "')+(_.list_presentation||_.synonym)+'"'),document.body.addEventListener("keydown",a,!1),f.elmnts={},!t.status_bar&&t.smart_rendering||(f.elmnts.status_bar=f.attachStatusBar()),t.smart_rendering||f.elmnts.status_bar.setText("<div id='"+h.class_name.replace(".","_")+"_select_recinfoArea'></div>"),f.elmnts.toolbar=f.attachToolbar(),f.elmnts.toolbar.setIconsPath(dhtmlx.image_path+"dhxtoolbar"+dhtmlx.skin_suffix()),f.elmnts.toolbar.loadStruct(t.toolbar_struct||$p.injected_data["toolbar_selection.xml"],function(){this.attachEvent("onclick",o),f===e&&(this.cont.parentElement.classList.add("dhx_cell_toolbar_no_borders"),this.cont.parentElement.classList.remove("dhx_cell_toolbar_def"),this.cont.style.top="4px");var n={manager:h,toolbar:this,onchange:i,hide_filter:t.hide_filter,custom_selection:t.custom_selection};t.date_from&&(n.date_from=t.date_from),t.date_till&&(n.date_till=t.date_till),t.period&&(n.period=t.period),f.elmnts.filter=new $p.iface.Toolbar_filter(n);var a=$p.current_acl.get_acl(h.class_name);a.indexOf("i")==-1&&this.hideItem("btn_new"),a.indexOf("v")==-1&&this.hideItem("btn_edit"),a.indexOf("d")==-1&&this.hideItem("btn_delete"),y||(this.hideItem("btn_select"),this.hideItem("sep1"),$p.iface.docs&&$p.iface.docs.getViewName&&"oper"==$p.iface.docs.getViewName()&&this.addListOption("bs_more","btn_order_list","~","button","<i class='fa fa-briefcase fa-lg fa-fw'></i> Список заказов")),this.addListOption("bs_more","btn_import","~","button","<i class='fa fa-upload fa-lg fa-fw'></i> Загрузить из файла"),this.addListOption("bs_more","btn_export","~","button","<i class='fa fa-download fa-lg fa-fw'></i> Выгрузить в файл"),h.printing_plates?h.printing_plates().then(function(e){var t;for(var n in e)f.elmnts.toolbar.addListOption("bs_print",n,"~","button",e[n].toString()),t=!0;t||f.elmnts.toolbar.hideItem("bs_print")}):f.elmnts.toolbar.hideItem("bs_print"),s()}),f._mgr=h,f}function a(e){function t(){var e;return $p.iface.w.forEachWindow(function(t){t==f||!t.isModal()&&$p.iface.w.getTopmostWindow()!=t||(e=!0)}),e}if(f&&f.is_visible&&f.is_visible())if(e.ctrlKey&&70==e.keyCode){if(!t())return setTimeout(function(){f.elmnts.filter.input_filter&&"desktop"==$p.job_prm.device_type&&f.elmnts.filter.input_filter.focus()}),$p.iface.cancel_bubble(e)}else if(e.shiftKey&&116==e.keyCode){if(!t())return setTimeout(function(){f.elmnts.grid.reload()}),e.preventDefault&&e.preventDefault(),$p.iface.cancel_bubble(e)}else 27==e.keyCode&&(t()||setTimeout(function(){f.close()}))}function i(e){f&&f.elmnts&&(g&&(e.filter||e.hide_tree?f.elmnts.cell_tree.collapse():f.elmnts.cell_tree.expand()),f.elmnts.grid.reload())}function s(){var e,n,a,i,s,o;g?(e=f.attachLayout("2U"),a=e.cells("b"),a.hideHeader(),n=f.elmnts.cell_tree=e.cells("a"),n.setWidth("220"),n.hideHeader(),i=f.elmnts.tree=n.attachDynTree(h,null,function(){setTimeout(function(){s&&s.reload&&s.reload()},20)}),i.attachEvent("onSelect",function(e,t){t&&(this.do_not_reload?delete this.do_not_reload:setTimeout(function(){s&&s.reload&&s.reload()},20))}),i.attachEvent("onDblClick",function(e){r(e)})):(a=f,setTimeout(function(){s&&s.reload&&s.reload()},20)),s=f.elmnts.grid=a.attachGrid(),s.setIconsPath(dhtmlx.image_path),s.setImagePath(dhtmlx.image_path),s.attachEvent("onBeforeSorting",m),s.attachEvent("onBeforePageChanged",function(){return!!this.getRowsNum()}),s.attachEvent("onXLE",function(){a.progressOff()}),s.attachEvent("onXLS",function(){a.progressOn()}),s.attachEvent("onDynXLS",function(e,t){var n=u(e,t);if(n)return h.sync_grid(n,s),!1}),s.attachEvent("onRowDblClicked",function(e,t){if(i&&i.items[e]){i.selectItem(e);var n=i.getParentId(e);n&&n!=$p.utils.blank.guid&&i.openItem(n)}else r(e)}),t.smart_rendering?s.enableSmartRendering(!0,50):(s.setPagingWTMode(!0,!0,!0,[20,30,60]),s.enablePaging(!0,30,8,h.class_name.replace(".","_")+"_select_recinfoArea"),s.setPagingSkin("toolbar",dhtmlx.skin)),$p.iface.docs&&$p.iface.docs.getViewName&&"oper"==$p.iface.docs.getViewName()&&s.enableMultiselect(!0),s.reload=function(){var e=u();return e?(a.progressOn(),s.clearAll(),h.sync_grid(e,s).then(function(n){if("object"==typeof n)$p.msg.check_soap_result(n);else if(!o){if(e.initial_value){var r=n.indexOf("set_parent"),l=n.indexOf("'>",r),c=n.substr(r+12,l-r-12);$p.utils.is_guid(c)&&g&&(i.do_not_reload=!0,i.selectItem(c,!1)),s.selectRowById(e.initial_value)}else e.parent&&$p.utils.is_guid(e.parent)&&g&&(i.do_not_reload=!0,i.selectItem(e.parent,!1));s.setColumnMinWidth(200,s.getColIndexById("presentation")),s.enableAutoWidth(!0,1200,600),s.setSizes(),o=!0,f.elmnts.filter.input_filter&&"desktop"==$p.job_prm.device_type&&f.elmnts.filter.input_filter.focus(),t.on_grid_inited&&t.on_grid_inited()}v&&o&&s.setSortImgState(!0,b,v),a.progressOff()})):Promise.resolve()}}function o(e){if(!t.toolbar_click||t.toolbar_click(e,f,h)!==!1)if("btn_select"==e)r();else if("btn_new"==e)h.create({},!0).then(function(e){t.on_new?t.on_new(e,f):$p.job_prm.keep_hash?e.form_obj(f):(e._set_loaded(e.ref),$p.iface.set_hash(h.class_name,e.ref))});else if("btn_edit"==e){var n=f.elmnts.grid.getSelectedRowId();n?t.on_edit?t.on_edit(h,n,f):$p.job_prm.keep_hash?h.form_obj(f,{ref:n}):$p.iface.set_hash(h.class_name,n):$p.msg.show_msg({type:"alert-warning",text:$p.msg.no_selected_row.replace("%1",""),title:$p.msg.main_title})}else"prn_"==e.substr(0,4)?l(e):"btn_order_list"==e?$p.iface.set_hash("","","","def"):"btn_delete"==e?c():"btn_import"==e?h.import():"btn_export"==e?h.export(f.elmnts.grid.getSelectedRowId()):"btn_requery"==e&&(x={},f.elmnts.grid.reload())}function r(n){n||(n=f.elmnts.grid.getSelectedRowId());var a;if(t.selection&&t.selection.forEach(function(e){for(var t in e)"is_folder"==t&&(a=e[t])}),f.elmnts.tree&&f.elmnts.tree.items[n]&&f.elmnts.tree.getSelectedId()!=n)return void f.elmnts.tree.selectItem(n,!0);if(n&&a===!0&&f.elmnts.grid.cells(n,0).cell.classList.contains("cell_ref_elm"))return void $p.msg.show_msg($p.msg.select_grp);if(!n&&f.elmnts.tree||f.elmnts.tree&&f.elmnts.tree.getSelectedId()==n){if(a===!1)return void $p.msg.show_msg($p.msg.select_elm);n=f.elmnts.tree.getSelectedId()}n&&(t.on_edit?t.on_edit(h,n,f):y?h.get(n,!0).then(function(t){f.close(),y.call(e.grid||e,t)}):$p.job_prm.keep_hash?h.form_obj(f,{ref:n}):$p.iface.set_hash(h.class_name,n))}function l(e){var t=f.elmnts.grid.getSelectedRowId();t?h.print(t,e,f):$p.msg.show_msg({type:"alert-warning",text:$p.msg.no_selected_row.replace("%1",""),title:$p.msg.main_title})}function c(){var e=f.elmnts.grid.getSelectedRowId();e?h.get(e,!0,!0).then(function(e){dhtmlx.confirm({title:$p.msg.main_title,text:e._deleted?$p.msg.mark_undelete_confirm.replace("%1",e.presentation):$p.msg.mark_delete_confirm.replace("%1",e.presentation),cancel:"Отмена",callback:function(t){t&&e.mark_deleted(!e._deleted)}})}):$p.msg.show_msg({type:"alert-warning",text:$p.msg.no_selected_row.replace("%1",""),title:$p.msg.main_title})}function p(n){document.body.removeEventListener("keydown",a),t&&t.on_close&&!n&&t.on_close(),n||(h=f=_=x=y=e=t=null)}function d(){return setTimeout(p,10),e.on_unload&&e.on_unload.call(e.grid||e),w&&($p.eve.detachEvent(w),w=null),!0}function u(e,n){var a=f.elmnts.filter.get_filter()._mixin({action:"get_selection",metadata:_,class_name:h.class_name,order_by:f.elmnts.grid.columnIds[b]||b,direction:v,start:e||((f.elmnts.grid.currentPage||1)-1)*f.elmnts.grid.rowsBufferOutSize,count:n||f.elmnts.grid.rowsBufferOutSize,get_header:void 0==x.get_header}),i=g?f.elmnts.tree.getSelectedId():null;if(t.smart_rendering&&(a.smart_rendering=!0),t.date_from&&!a.date_from&&(a.date_from=t.date_from),t.date_till&&!a.date_till&&(a.date_till=t.date_till),t.initial_value&&(a.initial_value=t.initial_value),t.custom_selection&&(a.custom_selection=t.custom_selection),t.selection)if(a.selection)if(Array.isArray(t.selection))t.selection.forEach(function(e){a.selection.push(e)});else for(var s in t.selection){res.selection||(res.selection=[]);var o={};o[s]=t.selection[s],a.selection.push(o)}else a.selection=t.selection;t.owner&&!a.owner&&(a.owner=t.owner),a.parent=!i&&!t.parent||a.filter?null:i||t.parent,g&&!a.parent&&(a.parent=$p.utils.blank.guid);for(var r in a)if(x[r]!=a[r])return x=a,a}function m(e){var t=f.elmnts.grid.getSortingState();return b=e,v="des"==t[1]?"asc":"des",f.elmnts.grid.reload(),!0}e||(e=t&&t.pwnd?t.pwnd:{}),t||e instanceof dhtmlXCellObject||(t=e,e={}),t||(t={});var f,h=this,_=t.metadata||h.metadata(),g=_.hierarchical&&!(h instanceof ChartOfAccountManager),b=0,v="asc",x={},y=e.on_select||t.on_select,w=$p.eve.attachEvent("frm_close",function(e,t){h&&h.class_name==e&&f&&f.elmnts&&f.elmnts.grid.reload().then(function(){$p.utils.is_empty_guid(t)||f.elmnts.grid.selectRowById(t,!1,!0,!0)})});return g&&t.initial_value&&t.initial_value!=$p.utils.blank.guid&&!t.parent?h.get(t.initial_value,!0).then(function(e){return t.parent=e.parent.ref,t.set_parent=t.parent,n()}):n()},DataManager.prototype.form_list=function(e,t){return this.form_selection(e,t)},$p.iface.wnd_sync=function(){function e(){var e={name:"wnd_sync",wnd:{id:"wnd_sync",top:130,left:200,width:496,height:290,modal:!0,center:!0,caption:"Подготовка данных"}};t.wnd_sync=$p.iface.dat_blank(null,e.wnd);var n=[{type:"block",name:"form_block_1",list:[{type:"label",name:"form_label_1",label:$p.msg.sync_data},{type:"block",name:"form_block_2",list:[{type:"template",name:"img_long",className:"img_long"},{type:"newcolumn"},{type:"template",name:"text_processed"},{type:"template",name:"text_current"},{type:"template",name:"text_bottom"}]}]},{type:"button",name:"form_button_1",value:$p.msg.sync_break}];t.frm_sync=t.wnd_sync.attachForm(n),t.frm_sync.attachEvent("onButtonClick",function(e){t&&(t.do_break=!0)}),t.frm_sync.setItemValue("text_processed","Инициализация"),t.frm_sync.setItemValue("text_bottom","Загружается структура таблиц...")}var t,n=$p.iface.sync={};n.create=function(n){t=n,e()},n.update=function(e){t.frm_sync.setItemValue("text_processed","Обработано элементов: "+t.step*t.step_size+" из "+t.count_all);var n,a="",i=0;for(var s in e){if(i++,i>4)break;a&&(a+="<br />"),n=$p.cat[s].metadata(),a+=(n.list_presentation||n.synonym)+" ("+e[s].length+")"}t.frm_sync.setItemValue("text_current","Текущий запрос: "+t.step+" ("+Math.round(t.step*t.step_size*100/t.count_all)+"%)"),t.frm_sync.setItemValue("text_bottom",a)},n.close=function(){t&&t.wnd_sync&&(t.wnd_sync.close(),delete t.wnd_sync,delete t.frm_sync)}},DataManager.prototype.export=function(e){function t(){$p.wsql.restore_options("data_manager",l),l.wnd.caption="Экспорт "+r.family_name+" '"+(r.metadata().synonym||r.metadata().name)+"'",o=$p.iface.dat_blank(null,l.wnd),o.bottom_toolbar({buttons:[{name:"btn_cancel",text:'<i class="fa fa-times fa-lg"></i> Отмена',title:"Отмена",width:"80px",float:"right"},{name:"btn_ok",b:'<i class="fa fa-floppy-o"></i> Ок',title:"Выполнить экспорт",width:"50px",float:"right"}],onclick:function(e){return"btn_ok"==e?i():o.close(),!1}}),o.button("close").show(),o.button("park").hide(),o.attachEvent("onClose",s);var t=[{type:"fieldset",name:"form_range",label:"Выгрузить",list:[{type:"settings",labelWidth:320,labelAlign:"left",position:"label-right"},{type:"radio",name:"range",label:"Выделенные строки",value:"selected"},{type:"radio",name:"range",label:"Весь справочник",value:"all"}]},{type:"fieldset",name:"form_fieldset_2",label:"Дополнительно выгрузить",list:[{type:"settings",labelWidth:160,position:"label-right"},{type:"checkbox",name:"meta",label:"Описание метаданных",labelAlign:"left",position:"label-right",checked:l.meta},{type:"newcolumn"},{type:"checkbox",name:"relation",label:"Связанные объекты",position:"label-right",checked:l.relation,tooltip:"Связанные объекты по ссылкам (пока не реализовано)"}]},{type:"fieldset",name:"fieldset_format",label:"Формат файла",list:[{type:"settings",labelWidth:60,labelAlign:"left",position:"label-right"},{type:"radio",name:"format",label:"json",value:"json",tooltip:"Выгрузить в формате JSON"},{type:"newcolumn"},{type:"radio",name:"format",label:"xlsx",value:"xlsx",tooltip:"Выгрузить в офисном формате XLSX"},{type:"newcolumn"},{type:"radio",name:"format",label:"atom",value:"atom",tooltip:"Выгрузить в формате XML Atom"}]}];o.elmnts.frm=o.attachForm(t),o.elmnts.frm.setItemValue("range",l.range||"all"),e.items&&1==e.items.length?(e.obj?o.elmnts.frm.setItemLabel("range","selected","Тек. объект: "+e.items[0].presentation):r.get(e.items[0],!0).then(function(e){o.elmnts.frm.setItemLabel("range","selected","Тек. объект: "+e.presentation)}),o.elmnts.frm.setItemValue("range","selected")):e.items&&e.items.length&&o.elmnts.frm.setItemLabel("range","selected","Выделенные строки ("+e.items.length+" элем.)"),r instanceof DocManager&&o.elmnts.frm.setItemLabel("range","all","Все документы из кеша (0 элем.)"),o.elmnts.frm.setItemValue("format",l.format||"json"),o.elmnts.frm.attachEvent("onChange",n),n(),e.pwnd&&e.pwnd.isModal&&e.pwnd.isModal()&&(e.set_pwnd_modal=!0,e.pwnd.setModal(!1)),o.setModal(!0)}function n(){o.elmnts.frm.setItemValue("relation",!1),o.elmnts.frm.disableItem("relation"),"all"==o.elmnts.frm.getItemValue("range")?(o.elmnts.frm.disableItem("format","atom"),"atom"==o.elmnts.frm.getItemValue("format")&&o.elmnts.frm.setItemValue("format","json")):o.elmnts.frm.enableItem("format","atom"),"json"==o.elmnts.frm.getItemValue("format")?o.elmnts.frm.enableItem("meta"):"sql"==o.elmnts.frm.getItemValue("format")?(o.elmnts.frm.setItemValue("meta",!1),o.elmnts.frm.disableItem("meta")):(o.elmnts.frm.setItemValue("meta",!1),o.elmnts.frm.disableItem("meta"))}function a(){return l.format=o.elmnts.frm.getItemValue("format"),l.range=o.elmnts.frm.getItemValue("range"),l.meta=o.elmnts.frm.getItemValue("meta"),l.relation=o.elmnts.frm.getItemValue("relation"),l}function i(){function t(){e.obj?$p.wsql.alasql("SELECT * INTO XLSX('"+r.table_name+".xlsx',{headers:true}) FROM ?",[e.items[0]._obj]):$p.wsql.alasql("SELECT * INTO XLSX('"+r.table_name+".xlsx',{headers:true}) FROM "+r.table_name)}a();var n={meta:{},items:{}},i=n.items[r.class_name]=[];if(l.meta&&(n.meta[r.class_name]=r.metadata()),"json"==l.format)e.obj?i.push(e.items[0]._obj):r.each(function(t){"all"!=l.range&&e.items.indexOf(t.ref)==-1||i.push(t._obj)}),e.items.length&&!i.length?r.get(e.items[0],!0).then(function(e){i.push(e._obj),alasql.utils.saveFile(r.table_name+".json",JSON.stringify(n,null,4))}):alasql.utils.saveFile(r.table_name+".json",JSON.stringify(n,null,4));else if("xlsx"==l.format)window.xlsx?t():$p.load_script("//cdn.jsdelivr.net/js-xlsx/latest/xlsx.core.min.js","script",t);else if("atom"==l.format&&e.items.length){var s=e.obj?Promise.resolve(e.items[0]):r.get(e.items[0],!0);s.then(function(e){alasql.utils.saveFile(r.table_name+".xml",e.to_atom())})}else $p.msg.show_not_implemented()}function s(t){return $p.iface.popup.hide(),o.wnd_options(l.wnd),$p.wsql.save_options("data_manager",a()),o.setModal(!1),e.set_pwnd_modal&&e.pwnd.setModal&&e.pwnd.setModal(!0),!0}e&&"string"==typeof e?e={items:e.split(",")}:e||(e={items:[]});var o,r=this,l={name:"export",wnd:{top:130,left:200,width:480,height:350}};t()},DataManager.prototype.import=function(e,t){function n(e){function n(e,n){var a=_md.mgr_by_class_name(e);if(n.length)if(t){if(t._manager==a)for(var s in n)$p.utils.fix_guid(n[s])==t.ref&&(i=!0,a.load_array([n[s]],!0))}else i=!0,a.load_array(n,!0)}if(o.close(),a.files.length){var s=new FileReader;s.onload=function(e){try{var t=JSON.parse(s.result);if(t.items)for(var a in t.items)n(a,t.items[a]);else["cat","doc","ireg","areg","cch","cacc"].forEach(function(e){if(t[e])for(var a in t[e])n(e+"."+a,t.cat[a])});i||$p.msg.show_msg($p.msg.sync_no_data)}catch(e){$p.msg.show_msg(e.message)}},s.readAsText(a.files[0])}}var a,i;if(!e&&void 0!=typeof window){var s={name:"import",wnd:{width:300,height:100,caption:$p.msg.select_file_import}},o=$p.iface.dat_blank(null,s.wnd);a=document.createElement("input"),a.setAttribute("id","json_file"),a.setAttribute("type","file"),a.setAttribute("accept",".json"),a.setAttribute("value","*.json"),a.onchange=n,o.button("close").show(),o.button("park").hide(),o.attachObject(a),o.centerOnScreen(),o.setModal(!0),setTimeout(function(){a.click()},100)}},$p.eve.__define({set_offline:{value:function(e){var t=$p.job_prm.offline;$p.job_prm.offline=!(!e&&!$p.wsql.get_user_param("offline","boolean")),t!=$p.job_prm.offline&&(t=$p.job_prm.offline)}},on_rotate:{value:function(e){$p.job_prm.device_orient=0==window.orientation||180==window.orientation?"portrait":"landscape","undefined"!=typeof e&&$p.eve.callEvent("onOrientationChange",[$p.job_prm.device_orient])}},steps:{value:{load_meta:0,authorization:1,create_managers:2,process_access:3,load_data_files:4,load_data_db:5,load_data_wsql:6,save_data_wsql:7}},log_in:{value:function(e){var t,n={};return e($p.eve.steps.load_meta),$p.ajax.default_attr(n,$p.job_prm.irest_url()),($p.job_prm.offline?Promise.resolve({responseURL:"",response:""}):$p.ajax.get_ex(n.url,n)).then(function(e){if($p.job_prm.offline||($p.job_prm.irest_enabled=!0),"{"==e.response[0])return JSON.parse(e.response)}).catch(function(){}).then(function(n){return e($p.eve.steps.authorization),t=n,t.root=!0,$p.job_prm.offline||$p.job_prm.irest_enabled?t:$p.ajax.get_ex($p.job_prm.rest_url()+"?$format=json",!0).then(function(){return t})}).catch(function(e){throw $p.iface.auth.onerror&&$p.iface.auth.onerror(e),e}).then(function(t){return e($p.eve.steps.load_data_files),$p.job_prm.offline?t:($p.eve.callEvent("log_in",[$p.ajax.authorized=!0]),"string"==typeof t&&(t=JSON.parse(t)),void($p.msg.check_soap_result(t)||($p.wsql.get_user_param("enable_save_pwd")?$p.wsql.set_user_param("user_pwd",$p.ajax.password):$p.wsql.get_user_param("user_pwd")&&$p.wsql.set_user_param("user_pwd",""),t.now_1c&&t.now_js&&$p.wsql.set_user_param("time_diff",t.now_1c-t.now_js))))}).then(function(){_md.printing_plates(t.printing_plates)})}}}),function(w,eve,msg){var timer_setted=!1,cache;w.addEventListener("online",eve.set_offline),w.addEventListener("offline",function(){eve.set_offline(!0)}),w.addEventListener("load",function(){setTimeout(function(){function navigate(e){e&&(location.origin+location.pathname).indexOf(e)==-1&&location.replace(e)}function init_params(){function e(){var e=dhtmlx.codebase,t=!0,n=!0;e.indexOf("cdn.jsdelivr.net")!=-1&&(e="//cdn.jsdelivr.net/metadata/latest/");for(var a=0;a<document.styleSheets.length;a++)document.styleSheets[a].href&&(document.styleSheets[a].href.indexOf("dhx_web")==-1&&document.styleSheets[a].href.indexOf("dhx_terrace")==-1||(t=!1),document.styleSheets[a].href.indexOf("metadata.css")!=-1&&(n=!1));dhtmlx.skin=$p.wsql.get_user_param("skin")||$p.job_prm.skin||"dhx_web",t&&$p.load_script(e+("dhx_web"==dhtmlx.skin?"dhx_web.css":"dhx_terrace.css"),"link"),n&&$p.load_script(e+"metadata.css","link"),$p.job_prm.additional_css&&$p.job_prm.additional_css.forEach(function(e){(dhx4.isIE||e.indexOf("ie_only")==-1)&&$p.load_script(e,"link")}),dhtmlx.image_path="//oknosoft.github.io/metadata.js/lib/imgs/",dhtmlx.skin_suffix=function(){return dhtmlx.skin.replace("dhx","")+"/"},dhx4.ajax.cache=!0,$p.iface.__define("w",{value:new dhtmlXWindows,enumerable:!1}),$p.iface.w.setSkin(dhtmlx.skin),$p.iface.__define("popup",{value:new dhtmlXPopup,enumerable:!1})}$p.wsql.init_params(),"dhtmlx"in w&&e(),"undefined"==typeof w.orientation?$p.job_prm.device_orient=w.innerWidth>w.innerHeight?"landscape":"portrait":eve.on_rotate(),w.addEventListener("orientationchange",eve.on_rotate,!1),eve.stepper={step:0,count_all:0,step_size:57,files:0},eve.set_offline(!navigator.onLine),setTimeout(function(){$p.wsql.pouch.load_data().catch($p.record_log);var e;(e=document.querySelector("#splash"))&&e.parentNode.removeChild(e),eve.callEvent("iface_init",[$p])},20),(cache=w.applicationCache)&&(cache.addEventListener("noupdate",function(e){},!1),cache.addEventListener("cached",function(e){timer_setted=!0,$p.iface.appcache&&$p.iface.appcache.close()},!1),cache.addEventListener("updateready",function(e){try{cache.swapCache()}catch(e){}$p.iface.do_reload()},!1),cache.addEventListener("error",$p.record_log,!1))}if(!w.JSON||!w.indexedDB)throw eve.redirect=!0,msg.show_msg({type:"alert-error",text:msg.unsupported_browser,title:msg.unsupported_browser_title}),msg.unsupported_browser;$p.__define("job_prm",{value:new JobPrm,writable:!1}),($p.job_prm.use_ip_geo||$p.job_prm.use_google_geo)&&($p.ipinfo=new IPInfo),$p.job_prm.use_google_geo&&(window.google&&window.google.maps?location_callback():$p.on("iface_init",function(){setTimeout(function(){$p.load_script("//maps.google.com/maps/api/js?callback=$p.ipinfo.location_callback","script",function(){})},100)})),$p.job_prm.allow_post_message&&w.addEventListener("message",function(event){if(("*"==$p.job_prm.allow_post_message||$p.job_prm.allow_post_message==event.origin)&&"string"==typeof event.data)try{var res=eval(event.data);if(res&&event.source){if("object"==typeof res)res=JSON.stringify(res);else if("function"==typeof res)return;event.source.postMessage(res,"*")}}catch(e){$p.record_log(e)}}),$p.job_prm.__define("device_type",{get:function(){var e=$p.wsql.get_user_param("device_type");return e||(e=function(e){return e<800?"phone":e<1024?"tablet":"desktop"}(Math.max(screen.width,screen.height)),$p.wsql.set_user_param("device_type",e)),e},set:function(e){$p.wsql.set_user_param("device_type",e)}}),document.body.addEventListener("keydown",function(e){eve.callEvent("keydown",[e])},!1),setTimeout(init_params,10)},10)},!1),w.onbeforeunload=function(){if(!eve.redirect)return msg.onbeforeunload},w.addEventListener("popstat",$p.iface.hash_route),w.addEventListener("hashchange",$p.iface.hash_route)}(window,$p.eve,$p.msg),SpreadsheetDocument.prototype.__define({clear:{value:function(){for(;this._attr.content.firstChild;)this._attr.content.removeChild(this._attr.content.firstChild)}},put:{value:function(e,t){var n;e instanceof HTMLElement?(n=document.createElement(e.tagName),n.innerHTML=e.innerHTML,t||(t=e.attributes)):(n=document.createElement("DIV"),n.innerHTML=e),t&&Object.keys(t).forEach(function(e){"id"!=e&&"id"!=t[e].name&&n.setAttribute(t[e].name||e,t[e].value||t[e])}),this._attr.content.appendChild(n)}},content:{get:function(){return this._attr.content},set:function(e){this.clear(),"string"==typeof e?this._attr.content.innerHTML=e:e instanceof HTMLElement&&(this._attr.content.innerHTML=e.innerHTML)}},title:{get:function(){return this._attr.title},set:function(e){this._attr.title=e}}}),$p.SpreadsheetDocument=SpreadsheetDocument,$p.HandsontableDocument=HandsontableDocument,$p.injected_data._mixin({"form_auth.xml":'<?xml version="1.0" encoding="UTF-8"?>\n<items>\n\t<item type="settings" position="label-left" labelWidth="80" inputWidth="180" noteWidth="180"/>\n\t<item type="fieldset" name="data" inputWidth="auto" label="Авторизация">\n\n <item type="radio" name="type" labelWidth="auto" position="label-right" checked="true" value="guest" label="Гостевой (демо) режим">\n <item type="select" name="guest" label="Роль">\n <option value="Дилер" label="Дилер"/>\n </item>\n </item>\n\n\t\t<item type="radio" name="type" labelWidth="auto" position="label-right" value="auth" label="Есть учетная запись">\n\t\t\t<item type="input" value="" name="login" label="Логин" validate="NotEmpty" />\n\t\t\t<item type="password" value="" name="password" label="Пароль" validate="NotEmpty" />\n\t\t</item>\n\n\t\t<item type="button" value="Войти" name="submit"/>\n\n <item type="template" name="text_options" className="order_dealer_options" inputWidth="170"\n value="<a href=\'#\' onclick=\'$p.iface.open_settings();\' title=\'Страница настроек программы\' > <i class=\'fa fa-cog fa-lg\'></i> Настройки </a> <a href=\'//www.oknosoft.ru/feedback\' target=\'_blank\' style=\'margin-left: 9px;\' title=\'Задать вопрос через форму обратной связи\' > <i class=\'fa fa-question-circle fa-lg\'></i> Вопрос </a>" />\n\n\t</item>\n</items>',"toolbar_add_del.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n <item id="sep0" type="separator"/>\r\n <item type="button" id="btn_add" text="<i class=\'fa fa-plus-circle fa-fw\'></i> Добавить" title="Добавить строку" />\r\n <item type="button" id="btn_delete" text="<i class=\'fa fa-times fa-fw\'></i> Удалить" title="Удалить строку" />\r\n</toolbar>',"toolbar_obj.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n <item id="sep0" type="separator"/>\r\n <item type="button" id="btn_save_close" text="<b>Записать и закрыть</b>" title="Рассчитать, записать и закрыть" />\r\n <item type="button" id="btn_save" text="<i class=\'fa fa-floppy-o fa-fw\'></i>" title="Рассчитать и записать данные"/>\r\n <item type="button" id="btn_post" enabled="false" text="<i class=\'fa fa-check-square-o fa-fw\'></i>" title="Провести документ" />\r\n <item type="button" id="btn_unpost" enabled="false" text="<i class=\'fa fa-square-o fa-fw\'></i>" title="Отмена проведения" />\r\n\r\n <item type="button" id="btn_files" text="<i class=\'fa fa-paperclip fa-fw\'></i>" title="Присоединенные файлы"/>\r\n\r\n <item type="buttonSelect" id="bs_print" text="<i class=\'fa fa-print fa-fw\'></i>" title="Печать" openAll="true">\r\n </item>\r\n\r\n <item type="buttonSelect" id="bs_create_by_virtue" text="<i class=\'fa fa-bolt fa-fw\'></i>" title="Создать на основании" openAll="true" >\r\n <item type="button" id="btn_message" enabled="false" text="Сообщение" />\r\n </item>\r\n\r\n <item type="buttonSelect" id="bs_go_to" text="<i class=\'fa fa-external-link fa-fw\'></i>" title="Перейти" openAll="true" >\r\n <item type="button" id="btn_go_connection" enabled="false" text="Связи" />\r\n </item>\r\n\r\n <item type="buttonSelect" id="bs_more" text="<i class=\'fa fa-th-large fa-fw\'></i>" title="Дополнительно" openAll="true">\r\n\r\n <item type="button" id="btn_import" text="<i class=\'fa fa-upload fa-fw\'></i> Загрузить из файла" />\r\n <item type="button" id="btn_export" text="<i class=\'fa fa-download fa-fw\'></i> Выгрузить в файл" />\r\n </item>\r\n\r\n <item id="sep1" type="separator"/>\r\n <item type="button" id="btn_close" text="<i class=\'fa fa-times fa-fw\'></i>" title="Закрыть форму"/>\r\n <item id="sep2" type="separator"/>\r\n\r\n</toolbar>\r\n',"toolbar_ok_cancel.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n <item id="btn_ok" type="button" img="" imgdis="" text="<b>Ок</b>" />\r\n <item id="btn_cancel" type="button"\timg="" imgdis="" text="Отмена" />\r\n</toolbar>',"toolbar_rep.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n <item id="sep0" type="separator"/>\r\n <item type="button" id="btn_run" text="<i class=\'fa fa-play fa-fw\'></i> Сформировать" title="Сформировать отчет"/>\r\n\r\n <item type="buttonSelect" id="bs_more" text="<i class=\'fa fa-th-large fa-fw\'></i>" title="Дополнительно" openAll="true">\r\n\r\n <item type="button" id="btn_print" text="<i class=\'fa fa-print fa-fw\'></i> Печать" />\r\n\r\n <item id="sep3" type="separator"/>\r\n\r\n <item type="button" id="btn_export" text="<i class=\'fa fa-file-excel-o fa-fw\'></i> Выгрузить в файл" />\r\n\r\n <item id="sep4" type="separator"/>\r\n\r\n <item type="button" id="btn_import" text="<i class=\'fa fa-folder-open-o fa-fw\'></i> Выбрать вариант" />\r\n <item type="button" id="btn_export" text="<i class=\'fa fa-floppy-o fa-fw\'></i> Сохранить вариант" />\r\n\r\n </item>\r\n\r\n <item id="sep1" type="separator"/>\r\n\r\n</toolbar>\r\n',"toolbar_selection.xml":'<?xml version="1.0" encoding=\'utf-8\'?>\r\n<toolbar>\r\n\r\n <item id="sep0" type="separator"/>\r\n\r\n <item id="btn_select" type="button" title="Выбрать элемент списка" text="<b>Выбрать</b>" />\r\n\r\n <item id="sep1" type="separator"/>\r\n <item id="btn_new" type="button"\ttext="<i class=\'fa fa-plus-circle fa-fw\'></i>"\ttitle="Создать" />\r\n <item id="btn_edit" type="button"\ttext="<i class=\'fa fa-pencil fa-fw\'></i>"\ttitle="Изменить" />\r\n <item id="btn_delete" type="button"\ttext="<i class=\'fa fa-times fa-fw\'></i>"\ttitle="Удалить" />\r\n <item id="sep2" type="separator"/>\r\n\r\n <item type="buttonSelect" id="bs_print" text="<i class=\'fa fa-print fa-fw\'></i> Печать" openAll="true" >\r\n </item>\r\n\r\n <item type="buttonSelect" id="bs_more" text="<i class=\'fa fa-th-large fa-fw\'></i>" title="Дополнительно" openAll="true">\r\n <item id="btn_requery" type="button"\ttext="<i class=\'fa fa-refresh fa-fw\'></i> Обновить список" />\r\n </item>\r\n\r\n <item id="sep3" type="separator"/>\r\n\r\n</toolbar>'});var xmlToJSON=function(){this.version="1.3";var e={mergeCDATA:!0,grokAttr:!0,grokText:!0,normalize:!0,xmlns:!0,namespaceKey:"_ns",textKey:"_text",valueKey:"_value",attrKey:"_attr",cdataKey:"_cdata",attrsAsObject:!0,stripAttrPrefix:!0,stripElemPrefix:!0,childrenAsArray:!0},t=new RegExp(/(?!xmlns)^.*:/),n=new RegExp(/^\s+|\s+$/g);return this.grokType=function(e){return/^\s*$/.test(e)?null:/^(?:true|false)$/i.test(e)?"true"===e.toLowerCase():isFinite(e)?parseFloat(e):e},this.parseString=function(e,t){return this.parseXML(this.stringToXML(e),t)},this.parseXML=function(a,i){for(var s in i)e[s]=i[s];var o={},r=0,l="";if(e.xmlns&&a.namespaceURI&&(o[e.namespaceKey]=a.namespaceURI),a.attributes&&a.attributes.length>0){var c={};for(r;r<a.attributes.length;r++){var p=a.attributes.item(r);f={};var d="";d=e.stripAttrPrefix?p.name.replace(t,""):p.name,e.grokAttr?f[e.valueKey]=this.grokType(p.value.replace(n,"")):f[e.valueKey]=p.value.replace(n,""),e.xmlns&&p.namespaceURI&&(f[e.namespaceKey]=p.namespaceURI),e.attrsAsObject?c[d]=f:o[e.attrKey+d]=f}e.attrsAsObject&&(o[e.attrKey]=c)}if(a.hasChildNodes())for(var u,m,f,h=0;h<a.childNodes.length;h++)u=a.childNodes.item(h),4===u.nodeType?e.mergeCDATA?l+=u.nodeValue:o.hasOwnProperty(e.cdataKey)?(o[e.cdataKey].constructor!==Array&&(o[e.cdataKey]=[o[e.cdataKey]]),o[e.cdataKey].push(u.nodeValue)):e.childrenAsArray?(o[e.cdataKey]=[],o[e.cdataKey].push(u.nodeValue)):o[e.cdataKey]=u.nodeValue:3===u.nodeType?l+=u.nodeValue:1===u.nodeType&&(0===r&&(o={}), +m=e.stripElemPrefix?u.nodeName.replace(t,""):u.nodeName,f=xmlToJSON.parseXML(u),o.hasOwnProperty(m)?(o[m].constructor!==Array&&(o[m]=[o[m]]),o[m].push(f)):(e.childrenAsArray?(o[m]=[],o[m].push(f)):o[m]=f,r++));else l||(e.childrenAsArray?(o[e.textKey]=[],o[e.textKey].push(null)):o[e.textKey]=null);if(l)if(e.grokText){var _=this.grokType(l.replace(n,""));null!==_&&void 0!==_&&(o[e.textKey]=_)}else e.normalize?o[e.textKey]=l.replace(n,"").replace(/\s+/g," "):o[e.textKey]=l.replace(n,"");return o},this.xmlToString=function(e){try{var t=e.xml?e.xml:(new XMLSerializer).serializeToString(e);return t}catch(e){return null}},this.stringToXML=function(e){try{var t=null;if(window.DOMParser){var n=new DOMParser;return t=n.parseFromString(e,"text/xml")}return t=new ActiveXObject("Microsoft.XMLDOM"),t.async=!1,t.loadXML(e),t}catch(e){return null}},this}();"undefined"!=typeof module&&null!==module&&module.exports?module.exports=xmlToJSON:"function"==typeof define&&define.amd&&define(function(){return xmlToJSON});/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ +var saveAs=saveAs||function(e){"use strict";if(!("undefined"==typeof e||"undefined"!=typeof navigator&&/MSIE [1-9]\./.test(navigator.userAgent))){var t=e.document,n=function(){return e.URL||e.webkitURL||e},a=t.createElementNS("http://www.w3.org/1999/xhtml","a"),i="download"in a,s=function(e){var t=new MouseEvent("click");e.dispatchEvent(t)},o=/constructor/i.test(e.HTMLElement),r=/CriOS\/[\d]+/.test(navigator.userAgent),l=function(t){(e.setImmediate||e.setTimeout)(function(){throw t},0)},c="application/octet-stream",p=4e4,d=function(e){var t=function(){"string"==typeof e?n().revokeObjectURL(e):e.remove()};setTimeout(t,p)},u=function(e,t,n){t=[].concat(t);for(var a=t.length;a--;){var i=e["on"+t[a]];if("function"==typeof i)try{i.call(e,n||e)}catch(e){l(e)}}},m=function(e){return/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob([String.fromCharCode(65279),e],{type:e.type}):e},f=function(t,l,p){p||(t=m(t));var f,h=this,_=t.type,g=_===c,b=function(){u(h,"writestart progress write writeend".split(" "))},v=function(){if((r||g&&o)&&e.FileReader){var a=new FileReader;return a.onloadend=function(){var t=r?a.result:a.result.replace(/^data:[^;]*;/,"data:attachment/file;"),n=e.open(t,"_blank");n||(e.location.href=t),t=void 0,h.readyState=h.DONE,b()},a.readAsDataURL(t),void(h.readyState=h.INIT)}if(f||(f=n().createObjectURL(t)),g)e.location.href=f;else{var i=e.open(f,"_blank");i||(e.location.href=f)}h.readyState=h.DONE,b(),d(f)};return h.readyState=h.INIT,i?(f=n().createObjectURL(t),void setTimeout(function(){a.href=f,a.download=l,s(a),b(),d(f),h.readyState=h.DONE})):void v()},h=f.prototype,_=function(e,t,n){return new f(e,t||e.name||"download",n)};return"undefined"!=typeof navigator&&navigator.msSaveOrOpenBlob?function(e,t,n){return t=t||e.name||"download",n||(e=m(e)),navigator.msSaveOrOpenBlob(e,t)}:(h.abort=function(){},h.readyState=h.INIT=0,h.WRITING=1,h.DONE=2,h.error=h.onwritestart=h.onprogress=h.onwrite=h.onabort=h.onerror=h.onwriteend=null,_)}}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||this.content);/*! * @version: 2.1.24 * @author: Dan Grossman http://www.dangrossman.info/ * @copyright: Copyright (c) 2012-2016 Dan Grossman. All rights reserved. @@ -21,6 +22,6 @@ var saveAs=saveAs||function(e){"use strict";if(!("undefined"==typeof e||"undefin * Copyright(c) 2014 Jonathan Ong * MIT Licensed */ -return"undefined"!=typeof module&&module.exports?module.exports.saveAs=saveAs:"undefined"!=typeof define&&null!==define&&null!==define.amd&&define([],function(){return saveAs}),"undefined"!=typeof module&&module.exports&&(module.exports=Aes),function(){"use strict";var e=[["","один","два","три","четыре","пять","шесть","семь","восемь","девять","десять","одиннадцать","двенадцать","тринадцать","четырнадцать","пятнадцать","шестнадцать","семнадцать","восемнадцать","девятнадцать"],["","","двадцать","тридцать","сорок","пятьдесят","шестьдесят","семьдесят","восемьдесят","девяносто"],["","сто","двести","триста","четыреста","пятьсот","шестьсот","семьсот","восемьсот","девятьсот"]],t=function(e){return parseFloat(e)},n=function(e,t){if(3!==t.length)return!1;e=Math.abs(e)%100;var n=e%10;return e>10&&e<20?t[2]:n>1&&n<5?t[1]:1===n?t[0]:t[2]},a=function(a,i){var s,o,r="";return 3===a.length&&(s=a.substr(0,1),a=a.substr(1,3),r=""+e[2][s]+" "),a<20?r=r+e[0][t(a)]+" ":(s=a.substr(0,1),o=a.substr(1,2),r=r+e[1][s]+" "+e[0][o]+" "),0===i?r+=n(a,["рубль","рубля","рублей"]):1===i?" "!==r&&(r+=n(a,["тысяча ","тысячи ","тысяч "]),r=r.replace("один ","одна ").replace("два ","две ")):2===i?" "!==r&&(r+=n(a,["миллион ","миллиона ","миллионов "])):3===i&&(r+=n(a,["миллиард ","миллиарда ","миллиардов "])),r},i=function(e){var t=n(e,["копейка","копейки","копеек"]);return 0===e?e="00":e<10&&(e="0"+e)," "+e+" "+t},s=function(e){if(!e)return!1;var n=typeof e;if("number"!==n&&"string"!==n)return!1;if("string"===n&&(e=t(e.replace(",",".")),isNaN(e)))return!1;if(e<=0)return!1;var s,o;e=e.toFixed(2),e.indexOf(".")!==-1&&(s=e.split("."),e=s[0],o=s[1]);for(var r,l="",c=e.length-1,p="",d=0;c>=0;)r=e.substr(c,1),p=r+p,3!==p.length&&0!==c||isNaN(t(p))||(l=a(p,d)+l,p="",d++),c--;return l=l.replace(/\s+/g," "),o&&(l+=i(t(o))),l};Number.prototype.in_words||(Number.prototype.in_words=function(){return s(this)})}(),function(e,t){if("function"==typeof define&&define.amd)define(["moment","jquery"],function(n,a){return e.daterangepicker=t(n,a)});else if("object"==typeof module&&module.exports){var n="undefined"!=typeof window?window.jQuery:void 0;n||(n=require("jquery"),n.fn||(n.fn={})),module.exports=t(require("moment"),n)}else e.daterangepicker=t(e.moment,e.jQuery)}(this,function(e,t){var n=function(n,a,i){if(this.parentEl="body",this.element=t(n),this.startDate=e().startOf("day"),this.endDate=e().endOf("day"),this.minDate=!1,this.maxDate=!1,this.dateLimit=!1,this.autoApply=!1,this.singleDatePicker=!1,this.showDropdowns=!1,this.showWeekNumbers=!1,this.showISOWeekNumbers=!1,this.showCustomRangeLabel=!0,this.timePicker=!1,this.timePicker24Hour=!1,this.timePickerIncrement=1,this.timePickerSeconds=!1,this.linkedCalendars=!0,this.autoUpdateInput=!0,this.alwaysShowCalendars=!1,this.ranges={},this.opens="right",this.element.hasClass("pull-right")&&(this.opens="left"),this.drops="down",this.element.hasClass("dropup")&&(this.drops="up"),this.buttonClasses="btn btn-sm",this.applyClass="btn-success",this.cancelClass="btn-default",this.locale={direction:"ltr",format:"DD.MM.YYYY",separator:" - ",applyLabel:"Применить",cancelLabel:"Отмена",weekLabel:"W",customRangeLabel:"Произвольные даты",daysOfWeek:e.weekdaysMin(),monthNames:e.monthsShort(),firstDay:e.localeData().firstDayOfWeek()},this.callback=function(){},this.isShowing=!1,this.leftCalendar={},this.rightCalendar={},"object"==typeof a&&null!==a||(a={}),a=t.extend(this.element.data(),a),"string"==typeof a.template||a.template instanceof t||(a.template='<div class="daterangepicker dropdown-menu"><div class="calendar left"><div class="daterangepicker_input"><input class="input-mini form-control" type="text" name="daterangepicker_start" value="" /><i class="fa fa-calendar glyphicon glyphicon-calendar"></i><div class="calendar-time"><div></div><i class="fa fa-clock-o glyphicon glyphicon-time"></i></div></div><div class="calendar-table"></div></div><div class="calendar right"><div class="daterangepicker_input"><input class="input-mini form-control" type="text" name="daterangepicker_end" value="" /><i class="fa fa-calendar glyphicon glyphicon-calendar"></i><div class="calendar-time"><div></div><i class="fa fa-clock-o glyphicon glyphicon-time"></i></div></div><div class="calendar-table"></div></div><div class="ranges"><div class="range_inputs"><button class="applyBtn" disabled="disabled" type="button"></button> <button class="cancelBtn" type="button"></button></div></div></div>'),this.parentEl=t(a.parentEl&&t(a.parentEl).length?a.parentEl:this.parentEl),this.container=t(a.template).appendTo(this.parentEl),"object"==typeof a.locale&&("string"==typeof a.locale.direction&&(this.locale.direction=a.locale.direction),"string"==typeof a.locale.format&&(this.locale.format=a.locale.format),"string"==typeof a.locale.separator&&(this.locale.separator=a.locale.separator),"object"==typeof a.locale.daysOfWeek&&(this.locale.daysOfWeek=a.locale.daysOfWeek.slice()),"object"==typeof a.locale.monthNames&&(this.locale.monthNames=a.locale.monthNames.slice()),"number"==typeof a.locale.firstDay&&(this.locale.firstDay=a.locale.firstDay),"string"==typeof a.locale.applyLabel&&(this.locale.applyLabel=a.locale.applyLabel),"string"==typeof a.locale.cancelLabel&&(this.locale.cancelLabel=a.locale.cancelLabel),"string"==typeof a.locale.weekLabel&&(this.locale.weekLabel=a.locale.weekLabel),"string"==typeof a.locale.customRangeLabel&&(this.locale.customRangeLabel=a.locale.customRangeLabel)),this.container.addClass(this.locale.direction),"string"==typeof a.startDate&&(this.startDate=e(a.startDate,this.locale.format)),"string"==typeof a.endDate&&(this.endDate=e(a.endDate,this.locale.format)),"string"==typeof a.minDate&&(this.minDate=e(a.minDate,this.locale.format)),"string"==typeof a.maxDate&&(this.maxDate=e(a.maxDate,this.locale.format)),"object"==typeof a.startDate&&(this.startDate=e(a.startDate)),"object"==typeof a.endDate&&(this.endDate=e(a.endDate)),"object"==typeof a.minDate&&(this.minDate=e(a.minDate)),"object"==typeof a.maxDate&&(this.maxDate=e(a.maxDate)),this.minDate&&this.startDate.isBefore(this.minDate)&&(this.startDate=this.minDate.clone()),this.maxDate&&this.endDate.isAfter(this.maxDate)&&(this.endDate=this.maxDate.clone()),"string"==typeof a.applyClass&&(this.applyClass=a.applyClass),"string"==typeof a.cancelClass&&(this.cancelClass=a.cancelClass),"object"==typeof a.dateLimit&&(this.dateLimit=a.dateLimit),"string"==typeof a.opens&&(this.opens=a.opens),"string"==typeof a.drops&&(this.drops=a.drops),"boolean"==typeof a.showWeekNumbers&&(this.showWeekNumbers=a.showWeekNumbers),"boolean"==typeof a.showISOWeekNumbers&&(this.showISOWeekNumbers=a.showISOWeekNumbers),"string"==typeof a.buttonClasses&&(this.buttonClasses=a.buttonClasses),"object"==typeof a.buttonClasses&&(this.buttonClasses=a.buttonClasses.join(" ")),"boolean"==typeof a.showDropdowns&&(this.showDropdowns=a.showDropdowns),"boolean"==typeof a.showCustomRangeLabel&&(this.showCustomRangeLabel=a.showCustomRangeLabel),"boolean"==typeof a.singleDatePicker&&(this.singleDatePicker=a.singleDatePicker,this.singleDatePicker&&(this.endDate=this.startDate.clone())),"boolean"==typeof a.timePicker&&(this.timePicker=a.timePicker),"boolean"==typeof a.timePickerSeconds&&(this.timePickerSeconds=a.timePickerSeconds),"number"==typeof a.timePickerIncrement&&(this.timePickerIncrement=a.timePickerIncrement),"boolean"==typeof a.timePicker24Hour&&(this.timePicker24Hour=a.timePicker24Hour),"boolean"==typeof a.autoApply&&(this.autoApply=a.autoApply),"boolean"==typeof a.autoUpdateInput&&(this.autoUpdateInput=a.autoUpdateInput),"boolean"==typeof a.linkedCalendars&&(this.linkedCalendars=a.linkedCalendars),"function"==typeof a.isInvalidDate&&(this.isInvalidDate=a.isInvalidDate),"function"==typeof a.isCustomDate&&(this.isCustomDate=a.isCustomDate),"boolean"==typeof a.alwaysShowCalendars&&(this.alwaysShowCalendars=a.alwaysShowCalendars),0!=this.locale.firstDay)for(var s=this.locale.firstDay;s>0;)this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift()),s--;var o,r,l;if("undefined"==typeof a.startDate&&"undefined"==typeof a.endDate&&t(this.element).is("input[type=text]")){var c=t(this.element).val(),p=c.split(this.locale.separator);o=r=null,2==p.length?(o=e(p[0],this.locale.format),r=e(p[1],this.locale.format)):this.singleDatePicker&&""!==c&&(o=e(c,this.locale.format),r=e(c,this.locale.format)),null!==o&&null!==r&&(this.setStartDate(o),this.setEndDate(r))}if("object"==typeof a.ranges){for(l in a.ranges){o="string"==typeof a.ranges[l][0]?e(a.ranges[l][0],this.locale.format):e(a.ranges[l][0]),r="string"==typeof a.ranges[l][1]?e(a.ranges[l][1],this.locale.format):e(a.ranges[l][1]),this.minDate&&o.isBefore(this.minDate)&&(o=this.minDate.clone());var d=this.maxDate;if(this.dateLimit&&d&&o.clone().add(this.dateLimit).isAfter(d)&&(d=o.clone().add(this.dateLimit)),d&&r.isAfter(d)&&(r=d.clone()),!(this.minDate&&r.isBefore(this.minDate,this.timepicker?"minute":"day")||d&&o.isAfter(d,this.timepicker?"minute":"day"))){var u=document.createElement("textarea");u.innerHTML=l;var f=u.value;this.ranges[f]=[o,r]}}var m="<ul>";for(l in this.ranges)m+='<li data-range-key="'+l+'">'+l+"</li>";this.showCustomRangeLabel&&(m+='<li data-range-key="'+this.locale.customRangeLabel+'">'+this.locale.customRangeLabel+"</li>"),m+="</ul>",this.container.find(".ranges").prepend(m)}"function"==typeof i&&(this.callback=i),this.timePicker||(this.startDate=this.startDate.startOf("day"),this.endDate=this.endDate.endOf("day"),this.container.find(".calendar-time").hide()),this.timePicker&&this.autoApply&&(this.autoApply=!1),this.autoApply&&"object"!=typeof a.ranges?this.container.find(".ranges").hide():this.autoApply&&this.container.find(".applyBtn, .cancelBtn").addClass("hide"),this.singleDatePicker&&(this.container.addClass("single"),this.container.find(".calendar.left").addClass("single"),this.container.find(".calendar.left").show(),this.container.find(".calendar.right").hide(),this.container.find(".daterangepicker_input input, .daterangepicker_input > i").hide(),this.timePicker?this.container.find(".ranges ul").hide():this.container.find(".ranges").hide()),("undefined"==typeof a.ranges&&!this.singleDatePicker||this.alwaysShowCalendars)&&this.container.addClass("show-calendar"),this.container.addClass("opens"+this.opens),"undefined"!=typeof a.ranges&&"right"==this.opens&&this.container.find(".ranges").prependTo(this.container.find(".calendar.left").parent()),this.container.find(".applyBtn, .cancelBtn").addClass(this.buttonClasses),this.applyClass.length&&this.container.find(".applyBtn").addClass(this.applyClass),this.cancelClass.length&&this.container.find(".cancelBtn").addClass(this.cancelClass),this.container.find(".applyBtn").html(this.locale.applyLabel),this.container.find(".cancelBtn").html(this.locale.cancelLabel),this.container.find(".calendar").on("click.daterangepicker",".prev",t.proxy(this.clickPrev,this)).on("click.daterangepicker",".next",t.proxy(this.clickNext,this)).on("mousedown.daterangepicker","td.available",t.proxy(this.clickDate,this)).on("mouseenter.daterangepicker","td.available",t.proxy(this.hoverDate,this)).on("mouseleave.daterangepicker","td.available",t.proxy(this.updateFormInputs,this)).on("change.daterangepicker","select.yearselect",t.proxy(this.monthOrYearChanged,this)).on("change.daterangepicker","select.monthselect",t.proxy(this.monthOrYearChanged,this)).on("change.daterangepicker","select.hourselect,select.minuteselect,select.secondselect,select.ampmselect",t.proxy(this.timeChanged,this)).on("click.daterangepicker",".daterangepicker_input input",t.proxy(this.showCalendars,this)).on("focus.daterangepicker",".daterangepicker_input input",t.proxy(this.formInputsFocused,this)).on("blur.daterangepicker",".daterangepicker_input input",t.proxy(this.formInputsBlurred,this)).on("change.daterangepicker",".daterangepicker_input input",t.proxy(this.formInputsChanged,this)),this.container.find(".ranges").on("click.daterangepicker","button.applyBtn",t.proxy(this.clickApply,this)).on("click.daterangepicker","button.cancelBtn",t.proxy(this.clickCancel,this)).on("click.daterangepicker","li",t.proxy(this.clickRange,this)).on("mouseenter.daterangepicker","li",t.proxy(this.hoverRange,this)).on("mouseleave.daterangepicker","li",t.proxy(this.updateFormInputs,this)),this.element.is("input")||this.element.is("button")?this.element.on({"click.daterangepicker":t.proxy(this.show,this),"focus.daterangepicker":t.proxy(this.show,this),"keyup.daterangepicker":t.proxy(this.elementChanged,this),"keydown.daterangepicker":t.proxy(this.keydown,this)}):this.element.on("click.daterangepicker",t.proxy(this.toggle,this)),this.element.is("input")&&!this.singleDatePicker&&this.autoUpdateInput?(this.element.val(this.startDate.format(this.locale.format)+this.locale.separator+this.endDate.format(this.locale.format)),this.element.trigger("change")):this.element.is("input")&&this.autoUpdateInput&&(this.element.val(this.startDate.format(this.locale.format)),this.element.trigger("change"))};return n.prototype={constructor:n,setStartDate:function(t){"string"==typeof t&&(this.startDate=e(t,this.locale.format)),"object"==typeof t&&(this.startDate=e(t)),this.timePicker||(this.startDate=this.startDate.startOf("day")),this.timePicker&&this.timePickerIncrement&&this.startDate.minute(Math.round(this.startDate.minute()/this.timePickerIncrement)*this.timePickerIncrement),this.minDate&&this.startDate.isBefore(this.minDate)&&(this.startDate=this.minDate,this.timePicker&&this.timePickerIncrement&&this.startDate.minute(Math.round(this.startDate.minute()/this.timePickerIncrement)*this.timePickerIncrement)),this.maxDate&&this.startDate.isAfter(this.maxDate)&&(this.startDate=this.maxDate,this.timePicker&&this.timePickerIncrement&&this.startDate.minute(Math.floor(this.startDate.minute()/this.timePickerIncrement)*this.timePickerIncrement)),this.isShowing||this.updateElement(),this.updateMonthsInView()},setEndDate:function(t){"string"==typeof t&&(this.endDate=e(t,this.locale.format)),"object"==typeof t&&(this.endDate=e(t)),this.timePicker||(this.endDate=this.endDate.endOf("day")),this.timePicker&&this.timePickerIncrement&&this.endDate.minute(Math.round(this.endDate.minute()/this.timePickerIncrement)*this.timePickerIncrement),this.endDate.isBefore(this.startDate)&&(this.endDate=this.startDate.clone()),this.maxDate&&this.endDate.isAfter(this.maxDate)&&(this.endDate=this.maxDate),this.dateLimit&&this.startDate.clone().add(this.dateLimit).isBefore(this.endDate)&&(this.endDate=this.startDate.clone().add(this.dateLimit)),this.previousRightTime=this.endDate.clone(),this.isShowing||this.updateElement(),this.updateMonthsInView()},isInvalidDate:function(){return!1},isCustomDate:function(){return!1},updateView:function(){this.timePicker&&(this.renderTimePicker("left"),this.renderTimePicker("right"),this.endDate?this.container.find(".right .calendar-time select").removeAttr("disabled").removeClass("disabled"):this.container.find(".right .calendar-time select").attr("disabled","disabled").addClass("disabled")),this.endDate?(this.container.find('input[name="daterangepicker_end"]').removeClass("active"),this.container.find('input[name="daterangepicker_start"]').addClass("active")):(this.container.find('input[name="daterangepicker_end"]').addClass("active"),this.container.find('input[name="daterangepicker_start"]').removeClass("active")),this.updateMonthsInView(),this.updateCalendars(),this.updateFormInputs()},updateMonthsInView:function(){if(this.endDate){if(!this.singleDatePicker&&this.leftCalendar.month&&this.rightCalendar.month&&(this.startDate.format("YYYY-MM")==this.leftCalendar.month.format("YYYY-MM")||this.startDate.format("YYYY-MM")==this.rightCalendar.month.format("YYYY-MM"))&&(this.endDate.format("YYYY-MM")==this.leftCalendar.month.format("YYYY-MM")||this.endDate.format("YYYY-MM")==this.rightCalendar.month.format("YYYY-MM")))return;this.leftCalendar.month=this.startDate.clone().date(2),this.linkedCalendars||this.endDate.month()==this.startDate.month()&&this.endDate.year()==this.startDate.year()?this.rightCalendar.month=this.startDate.clone().date(2).add(1,"month"):this.rightCalendar.month=this.endDate.clone().date(2)}else this.leftCalendar.month.format("YYYY-MM")!=this.startDate.format("YYYY-MM")&&this.rightCalendar.month.format("YYYY-MM")!=this.startDate.format("YYYY-MM")&&(this.leftCalendar.month=this.startDate.clone().date(2),this.rightCalendar.month=this.startDate.clone().date(2).add(1,"month"));this.maxDate&&this.linkedCalendars&&!this.singleDatePicker&&this.rightCalendar.month>this.maxDate&&(this.rightCalendar.month=this.maxDate.clone().date(2),this.leftCalendar.month=this.maxDate.clone().date(2).subtract(1,"month"))},updateCalendars:function(){if(this.timePicker){var e,t,n;if(this.endDate){if(e=parseInt(this.container.find(".left .hourselect").val(),10),t=parseInt(this.container.find(".left .minuteselect").val(),10),n=this.timePickerSeconds?parseInt(this.container.find(".left .secondselect").val(),10):0,!this.timePicker24Hour){var a=this.container.find(".left .ampmselect").val();"PM"===a&&e<12&&(e+=12),"AM"===a&&12===e&&(e=0)}}else if(e=parseInt(this.container.find(".right .hourselect").val(),10),t=parseInt(this.container.find(".right .minuteselect").val(),10),n=this.timePickerSeconds?parseInt(this.container.find(".right .secondselect").val(),10):0,!this.timePicker24Hour){var a=this.container.find(".right .ampmselect").val();"PM"===a&&e<12&&(e+=12),"AM"===a&&12===e&&(e=0)}this.leftCalendar.month.hour(e).minute(t).second(n),this.rightCalendar.month.hour(e).minute(t).second(n)}this.renderCalendar("left"),this.renderCalendar("right"),this.container.find(".ranges li").removeClass("active"),null!=this.endDate&&this.calculateChosenLabel()},renderCalendar:function(n){var a="left"==n?this.leftCalendar:this.rightCalendar,i=a.month.month(),s=a.month.year(),o=a.month.hour(),r=a.month.minute(),l=a.month.second(),c=e([s,i]).daysInMonth(),p=e([s,i,1]),d=e([s,i,c]),u=e(p).subtract(1,"month").month(),f=e(p).subtract(1,"month").year(),m=e([f,u]).daysInMonth(),h=p.day(),a=[];a.firstDay=p,a.lastDay=d;for(var _=0;_<6;_++)a[_]=[];var g=m-h+this.locale.firstDay+1;g>m&&(g-=7),h==this.locale.firstDay&&(g=m-6);for(var b,v,x=e([f,u,g,12,r,l]),_=0,b=0,v=0;_<42;_++,b++,x=e(x).add(24,"hour"))_>0&&b%7===0&&(b=0,v++),a[v][b]=x.clone().hour(o).minute(r).second(l),x.hour(12),this.minDate&&a[v][b].format("YYYY-MM-DD")==this.minDate.format("YYYY-MM-DD")&&a[v][b].isBefore(this.minDate)&&"left"==n&&(a[v][b]=this.minDate.clone()),this.maxDate&&a[v][b].format("YYYY-MM-DD")==this.maxDate.format("YYYY-MM-DD")&&a[v][b].isAfter(this.maxDate)&&"right"==n&&(a[v][b]=this.maxDate.clone());"left"==n?this.leftCalendar.calendar=a:this.rightCalendar.calendar=a;var y="left"==n?this.minDate:this.startDate,w=this.maxDate,k=("left"==n?this.startDate:this.endDate,"ltr"==this.locale.direction?{left:"chevron-left",right:"chevron-right"}:{left:"chevron-right",right:"chevron-left"}),$='<table class="table-condensed">';$+="<thead>",$+="<tr>",(this.showWeekNumbers||this.showISOWeekNumbers)&&($+="<th></th>"),$+=y&&!y.isBefore(a.firstDay)||this.linkedCalendars&&"left"!=n?"<th></th>":'<th class="prev available"><i class="fa fa-'+k.left+" glyphicon glyphicon-"+k.left+'"></i></th>';var j=this.locale.monthNames[a[1][1].month()]+a[1][1].format(" YYYY");if(this.showDropdowns){for(var D=a[1][1].month(),O=a[1][1].year(),C=w&&w.year()||O+5,E=y&&y.year()||O-50,M=O==E,S=O==C,T='<select class="monthselect">',P=0;P<12;P++)T+=(!M||P>=y.month())&&(!S||P<=w.month())?"<option value='"+P+"'"+(P===D?" selected='selected'":"")+">"+this.locale.monthNames[P]+"</option>":"<option value='"+P+"'"+(P===D?" selected='selected'":"")+" disabled='disabled'>"+this.locale.monthNames[P]+"</option>";T+="</select>";for(var I='<select class="yearselect">',L=E;L<=C;L++)I+='<option value="'+L+'"'+(L===O?' selected="selected"':"")+">"+L+"</option>";I+="</select>",j=T+I}if($+='<th colspan="5" class="month">'+j+"</th>",$+=w&&!w.isAfter(a.lastDay)||this.linkedCalendars&&"right"!=n&&!this.singleDatePicker?"<th></th>":'<th class="next available"><i class="fa fa-'+k.right+" glyphicon glyphicon-"+k.right+'"></i></th>',$+="</tr>",$+="<tr>",(this.showWeekNumbers||this.showISOWeekNumbers)&&($+='<th class="week">'+this.locale.weekLabel+"</th>"),t.each(this.locale.daysOfWeek,function(e,t){$+="<th>"+t+"</th>"}),$+="</tr>",$+="</thead>",$+="<tbody>",null==this.endDate&&this.dateLimit){var A=this.startDate.clone().add(this.dateLimit).endOf("day");w&&!A.isBefore(w)||(w=A)}for(var v=0;v<6;v++){$+="<tr>",this.showWeekNumbers?$+='<td class="week">'+a[v][0].week()+"</td>":this.showISOWeekNumbers&&($+='<td class="week">'+a[v][0].isoWeek()+"</td>");for(var b=0;b<7;b++){var q=[];a[v][b].isSame(new Date,"day")&&q.push("today"),a[v][b].isoWeekday()>5&&q.push("weekend"),a[v][b].month()!=a[1][1].month()&&q.push("off"),this.minDate&&a[v][b].isBefore(this.minDate,"day")&&q.push("off","disabled"),w&&a[v][b].isAfter(w,"day")&&q.push("off","disabled"),this.isInvalidDate(a[v][b])&&q.push("off","disabled"),a[v][b].format("YYYY-MM-DD")==this.startDate.format("YYYY-MM-DD")&&q.push("active","start-date"),null!=this.endDate&&a[v][b].format("YYYY-MM-DD")==this.endDate.format("YYYY-MM-DD")&&q.push("active","end-date"),null!=this.endDate&&a[v][b]>this.startDate&&a[v][b]<this.endDate&&q.push("in-range");var R=this.isCustomDate(a[v][b]);R!==!1&&("string"==typeof R?q.push(R):Array.prototype.push.apply(q,R));for(var N="",Y=!1,_=0;_<q.length;_++)N+=q[_]+" ","disabled"==q[_]&&(Y=!0);Y||(N+="available"),$+='<td class="'+N.replace(/^\s+|\s+$/g,"")+'" data-title="r'+v+"c"+b+'">'+a[v][b].date()+"</td>"}$+="</tr>"}$+="</tbody>",$+="</table>",this.container.find(".calendar."+n+" .calendar-table").html($)},renderTimePicker:function(e){if("right"!=e||this.endDate){var t,n,a,i=this.maxDate;if(!this.dateLimit||this.maxDate&&!this.startDate.clone().add(this.dateLimit).isAfter(this.maxDate)||(i=this.startDate.clone().add(this.dateLimit)),"left"==e)n=this.startDate.clone(),a=this.minDate;else if("right"==e){n=this.endDate.clone(),a=this.startDate;var s=this.container.find(".calendar.right .calendar-time div");if(!this.endDate&&""!=s.html()&&(n.hour(s.find(".hourselect option:selected").val()||n.hour()),n.minute(s.find(".minuteselect option:selected").val()||n.minute()),n.second(s.find(".secondselect option:selected").val()||n.second()),!this.timePicker24Hour)){var o=s.find(".ampmselect option:selected").val();"PM"===o&&n.hour()<12&&n.hour(n.hour()+12),"AM"===o&&12===n.hour()&&n.hour(0)}n.isBefore(this.startDate)&&(n=this.startDate.clone()),i&&n.isAfter(i)&&(n=i.clone())}t='<select class="hourselect">';for(var r=this.timePicker24Hour?0:1,l=this.timePicker24Hour?23:12,c=r;c<=l;c++){var p=c;this.timePicker24Hour||(p=n.hour()>=12?12==c?12:c+12:12==c?0:c);var d=n.clone().hour(p),u=!1;a&&d.minute(59).isBefore(a)&&(u=!0),i&&d.minute(0).isAfter(i)&&(u=!0),t+=p!=n.hour()||u?u?'<option value="'+c+'" disabled="disabled" class="disabled">'+c+"</option>":'<option value="'+c+'">'+c+"</option>":'<option value="'+c+'" selected="selected">'+c+"</option>"}t+="</select> ",t+=': <select class="minuteselect">';for(var c=0;c<60;c+=this.timePickerIncrement){var f=c<10?"0"+c:c,d=n.clone().minute(c),u=!1;a&&d.second(59).isBefore(a)&&(u=!0),i&&d.second(0).isAfter(i)&&(u=!0),t+=n.minute()!=c||u?u?'<option value="'+c+'" disabled="disabled" class="disabled">'+f+"</option>":'<option value="'+c+'">'+f+"</option>":'<option value="'+c+'" selected="selected">'+f+"</option>"}if(t+="</select> ",this.timePickerSeconds){t+=': <select class="secondselect">';for(var c=0;c<60;c++){var f=c<10?"0"+c:c,d=n.clone().second(c),u=!1;a&&d.isBefore(a)&&(u=!0),i&&d.isAfter(i)&&(u=!0),t+=n.second()!=c||u?u?'<option value="'+c+'" disabled="disabled" class="disabled">'+f+"</option>":'<option value="'+c+'">'+f+"</option>":'<option value="'+c+'" selected="selected">'+f+"</option>"}t+="</select> "}if(!this.timePicker24Hour){t+='<select class="ampmselect">';var m="",h="";a&&n.clone().hour(12).minute(0).second(0).isBefore(a)&&(m=' disabled="disabled" class="disabled"'),i&&n.clone().hour(0).minute(0).second(0).isAfter(i)&&(h=' disabled="disabled" class="disabled"'),t+=n.hour()>=12?'<option value="AM"'+m+'>AM</option><option value="PM" selected="selected"'+h+">PM</option>":'<option value="AM" selected="selected"'+m+'>AM</option><option value="PM"'+h+">PM</option>",t+="</select>"}this.container.find(".calendar."+e+" .calendar-time div").html(t)}},updateFormInputs:function(){this.container.find("input[name=daterangepicker_start]").is(":focus")||this.container.find("input[name=daterangepicker_end]").is(":focus")||(this.container.find("input[name=daterangepicker_start]").val(this.startDate.format(this.locale.format)),this.endDate&&this.container.find("input[name=daterangepicker_end]").val(this.endDate.format(this.locale.format)),this.singleDatePicker||this.endDate&&(this.startDate.isBefore(this.endDate)||this.startDate.isSame(this.endDate))?this.container.find("button.applyBtn").removeAttr("disabled"):this.container.find("button.applyBtn").attr("disabled","disabled"))},move:function(){var e,n={top:0,left:0},a=t(window).width();this.parentEl.is("body")||(n={top:this.parentEl.offset().top-this.parentEl.scrollTop(),left:this.parentEl.offset().left-this.parentEl.scrollLeft()},a=this.parentEl[0].clientWidth+this.parentEl.offset().left),e="up"==this.drops?this.element.offset().top-this.container.outerHeight()-n.top:this.element.offset().top+this.element.outerHeight()-n.top,this.container["up"==this.drops?"addClass":"removeClass"]("dropup"),"left"==this.opens?(this.container.css({top:e,right:a-this.element.offset().left-this.element.outerWidth(),left:"auto"}),this.container.offset().left<0&&this.container.css({right:"auto",left:9})):"center"==this.opens?(this.container.css({top:e,left:this.element.offset().left-n.left+this.element.outerWidth()/2-this.container.outerWidth()/2,right:"auto"}),this.container.offset().left<0&&this.container.css({right:"auto",left:9})):(this.container.css({top:e,left:this.element.offset().left-n.left,right:"auto"}),this.container.offset().left+this.container.outerWidth()>t(window).width()&&this.container.css({left:"auto",right:0}))},show:function(e){this.isShowing||(this._outsideClickProxy=t.proxy(function(e){this.outsideClick(e)},this),t(document).on("mousedown.daterangepicker",this._outsideClickProxy).on("touchend.daterangepicker",this._outsideClickProxy).on("click.daterangepicker","[data-toggle=dropdown]",this._outsideClickProxy).on("focusin.daterangepicker",this._outsideClickProxy),t(window).on("resize.daterangepicker",t.proxy(function(e){this.move(e)},this)),this.oldStartDate=this.startDate.clone(),this.oldEndDate=this.endDate.clone(),this.previousRightTime=this.endDate.clone(),this.updateView(),this.container.show(),this.move(),this.element.trigger("show.daterangepicker",this),this.isShowing=!0)},hide:function(e){this.isShowing&&(this.endDate||(this.startDate=this.oldStartDate.clone(),this.endDate=this.oldEndDate.clone()),this.startDate.isSame(this.oldStartDate)&&this.endDate.isSame(this.oldEndDate)||this.callback(this.startDate,this.endDate,this.chosenLabel),this.updateElement(),t(document).off(".daterangepicker"),t(window).off(".daterangepicker"),this.container.hide(),this.element.trigger("hide.daterangepicker",this),this.isShowing=!1)},toggle:function(e){this.isShowing?this.hide():this.show()},outsideClick:function(e){var n=t(e.target);"focusin"==e.type||n.closest(this.element).length||n.closest(this.container).length||n.closest(".calendar-table").length||(this.hide(),this.element.trigger("outsideClick.daterangepicker",this))},showCalendars:function(){this.container.addClass("show-calendar"),this.move(),this.element.trigger("showCalendar.daterangepicker",this)},hideCalendars:function(){this.container.removeClass("show-calendar"),this.element.trigger("hideCalendar.daterangepicker",this)},hoverRange:function(e){if(!this.container.find("input[name=daterangepicker_start]").is(":focus")&&!this.container.find("input[name=daterangepicker_end]").is(":focus")){var t=e.target.getAttribute("data-range-key");if(t==this.locale.customRangeLabel)this.updateView();else{var n=this.ranges[t];this.container.find("input[name=daterangepicker_start]").val(n[0].format(this.locale.format)),this.container.find("input[name=daterangepicker_end]").val(n[1].format(this.locale.format))}}},clickRange:function(e){var t=e.target.getAttribute("data-range-key");if(this.chosenLabel=t,t==this.locale.customRangeLabel)this.showCalendars();else{var n=this.ranges[t];this.startDate=n[0],this.endDate=n[1],this.timePicker||(this.startDate.startOf("day"),this.endDate.endOf("day")),this.alwaysShowCalendars||this.hideCalendars(),this.clickApply()}},clickPrev:function(e){var n=t(e.target).parents(".calendar");n.hasClass("left")?(this.leftCalendar.month.subtract(1,"month"),this.linkedCalendars&&this.rightCalendar.month.subtract(1,"month")):this.rightCalendar.month.subtract(1,"month"),this.updateCalendars()},clickNext:function(e){var n=t(e.target).parents(".calendar");n.hasClass("left")?this.leftCalendar.month.add(1,"month"):(this.rightCalendar.month.add(1,"month"),this.linkedCalendars&&this.leftCalendar.month.add(1,"month")),this.updateCalendars()},hoverDate:function(e){if(t(e.target).hasClass("available")){var n=t(e.target).attr("data-title"),a=n.substr(1,1),i=n.substr(3,1),s=t(e.target).parents(".calendar"),o=s.hasClass("left")?this.leftCalendar.calendar[a][i]:this.rightCalendar.calendar[a][i];this.endDate&&!this.container.find("input[name=daterangepicker_start]").is(":focus")?this.container.find("input[name=daterangepicker_start]").val(o.format(this.locale.format)):this.endDate||this.container.find("input[name=daterangepicker_end]").is(":focus")||this.container.find("input[name=daterangepicker_end]").val(o.format(this.locale.format));var r=this.leftCalendar,l=this.rightCalendar,c=this.startDate;this.endDate||this.container.find(".calendar td").each(function(e,n){if(!t(n).hasClass("week")){var a=t(n).attr("data-title"),i=a.substr(1,1),s=a.substr(3,1),p=t(n).parents(".calendar"),d=p.hasClass("left")?r.calendar[i][s]:l.calendar[i][s];d.isAfter(c)&&d.isBefore(o)||d.isSame(o,"day")?t(n).addClass("in-range"):t(n).removeClass("in-range")}})}},clickDate:function(e){if(t(e.target).hasClass("available")){var n=t(e.target).attr("data-title"),a=n.substr(1,1),i=n.substr(3,1),s=t(e.target).parents(".calendar"),o=s.hasClass("left")?this.leftCalendar.calendar[a][i]:this.rightCalendar.calendar[a][i];if(this.endDate||o.isBefore(this.startDate,"day")){if(this.timePicker){var r=parseInt(this.container.find(".left .hourselect").val(),10);if(!this.timePicker24Hour){var l=this.container.find(".left .ampmselect").val();"PM"===l&&r<12&&(r+=12),"AM"===l&&12===r&&(r=0)}var c=parseInt(this.container.find(".left .minuteselect").val(),10),p=this.timePickerSeconds?parseInt(this.container.find(".left .secondselect").val(),10):0;o=o.clone().hour(r).minute(c).second(p)}this.endDate=null,this.setStartDate(o.clone())}else if(!this.endDate&&o.isBefore(this.startDate))this.setEndDate(this.startDate.clone());else{if(this.timePicker){var r=parseInt(this.container.find(".right .hourselect").val(),10);if(!this.timePicker24Hour){var l=this.container.find(".right .ampmselect").val();"PM"===l&&r<12&&(r+=12),"AM"===l&&12===r&&(r=0)}var c=parseInt(this.container.find(".right .minuteselect").val(),10),p=this.timePickerSeconds?parseInt(this.container.find(".right .secondselect").val(),10):0;o=o.clone().hour(r).minute(c).second(p)}this.setEndDate(o.clone()),this.autoApply&&(this.calculateChosenLabel(),this.clickApply())}this.singleDatePicker&&(this.setEndDate(this.startDate),this.timePicker||this.clickApply()),this.updateView(),e.stopPropagation()}},calculateChosenLabel:function(){var e=!0,t=0;for(var n in this.ranges){if(this.timePicker){if(this.startDate.isSame(this.ranges[n][0])&&this.endDate.isSame(this.ranges[n][1])){e=!1,this.chosenLabel=this.container.find(".ranges li:eq("+t+")").addClass("active").html();break}}else if(this.startDate.format("YYYY-MM-DD")==this.ranges[n][0].format("YYYY-MM-DD")&&this.endDate.format("YYYY-MM-DD")==this.ranges[n][1].format("YYYY-MM-DD")){ +return"undefined"!=typeof module&&module.exports?module.exports.saveAs=saveAs:"undefined"!=typeof define&&null!==define&&null!==define.amd&&define([],function(){return saveAs}),"undefined"!=typeof module&&module.exports&&(module.exports=Aes),function(){"use strict";var e=[["","один","два","три","четыре","пять","шесть","семь","восемь","девять","десять","одиннадцать","двенадцать","тринадцать","четырнадцать","пятнадцать","шестнадцать","семнадцать","восемнадцать","девятнадцать"],["","","двадцать","тридцать","сорок","пятьдесят","шестьдесят","семьдесят","восемьдесят","девяносто"],["","сто","двести","триста","четыреста","пятьсот","шестьсот","семьсот","восемьсот","девятьсот"]],t=function(e){return parseFloat(e)},n=function(e,t){if(3!==t.length)return!1;e=Math.abs(e)%100;var n=e%10;return e>10&&e<20?t[2]:n>1&&n<5?t[1]:1===n?t[0]:t[2]},a=function(a,i){var s,o,r="";return 3===a.length&&(s=a.substr(0,1),a=a.substr(1,3),r=""+e[2][s]+" "),a<20?r=r+e[0][t(a)]+" ":(s=a.substr(0,1),o=a.substr(1,2),r=r+e[1][s]+" "+e[0][o]+" "),0===i?r+=n(a,["рубль","рубля","рублей"]):1===i?" "!==r&&(r+=n(a,["тысяча ","тысячи ","тысяч "]),r=r.replace("один ","одна ").replace("два ","две ")):2===i?" "!==r&&(r+=n(a,["миллион ","миллиона ","миллионов "])):3===i&&(r+=n(a,["миллиард ","миллиарда ","миллиардов "])),r},i=function(e){var t=n(e,["копейка","копейки","копеек"]);return 0===e?e="00":e<10&&(e="0"+e)," "+e+" "+t},s=function(e){if(!e)return!1;var n=typeof e;if("number"!==n&&"string"!==n)return!1;if("string"===n&&(e=t(e.replace(",",".")),isNaN(e)))return!1;if(e<=0)return!1;var s,o;e=e.toFixed(2),e.indexOf(".")!==-1&&(s=e.split("."),e=s[0],o=s[1]);for(var r,l="",c=e.length-1,p="",d=0;c>=0;)r=e.substr(c,1),p=r+p,3!==p.length&&0!==c||isNaN(t(p))||(l=a(p,d)+l,p="",d++),c--;return l=l.replace(/\s+/g," "),o&&(l+=i(t(o))),l};Number.prototype.in_words||(Number.prototype.in_words=function(){return s(this)})}(),function(e,t){if("function"==typeof define&&define.amd)define(["moment","jquery"],function(n,a){return e.daterangepicker=t(n,a)});else if("object"==typeof module&&module.exports){var n="undefined"!=typeof window?window.jQuery:void 0;n||(n=require("jquery"),n.fn||(n.fn={})),module.exports=t(require("moment"),n)}else e.daterangepicker=t(e.moment,e.jQuery)}(this,function(e,t){var n=function(n,a,i){if(this.parentEl="body",this.element=t(n),this.startDate=e().startOf("day"),this.endDate=e().endOf("day"),this.minDate=!1,this.maxDate=!1,this.dateLimit=!1,this.autoApply=!1,this.singleDatePicker=!1,this.showDropdowns=!1,this.showWeekNumbers=!1,this.showISOWeekNumbers=!1,this.showCustomRangeLabel=!0,this.timePicker=!1,this.timePicker24Hour=!1,this.timePickerIncrement=1,this.timePickerSeconds=!1,this.linkedCalendars=!0,this.autoUpdateInput=!0,this.alwaysShowCalendars=!1,this.ranges={},this.opens="right",this.element.hasClass("pull-right")&&(this.opens="left"),this.drops="down",this.element.hasClass("dropup")&&(this.drops="up"),this.buttonClasses="btn btn-sm",this.applyClass="btn-success",this.cancelClass="btn-default",this.locale={direction:"ltr",format:"DD.MM.YYYY",separator:" - ",applyLabel:"Применить",cancelLabel:"Отмена",weekLabel:"W",customRangeLabel:"Произвольные даты",daysOfWeek:e.weekdaysMin(),monthNames:e.monthsShort(),firstDay:e.localeData().firstDayOfWeek()},this.callback=function(){},this.isShowing=!1,this.leftCalendar={},this.rightCalendar={},"object"==typeof a&&null!==a||(a={}),a=t.extend(this.element.data(),a),"string"==typeof a.template||a.template instanceof t||(a.template='<div class="daterangepicker dropdown-menu"><div class="calendar left"><div class="daterangepicker_input"><input class="input-mini form-control" type="text" name="daterangepicker_start" value="" /><i class="fa fa-calendar glyphicon glyphicon-calendar"></i><div class="calendar-time"><div></div><i class="fa fa-clock-o glyphicon glyphicon-time"></i></div></div><div class="calendar-table"></div></div><div class="calendar right"><div class="daterangepicker_input"><input class="input-mini form-control" type="text" name="daterangepicker_end" value="" /><i class="fa fa-calendar glyphicon glyphicon-calendar"></i><div class="calendar-time"><div></div><i class="fa fa-clock-o glyphicon glyphicon-time"></i></div></div><div class="calendar-table"></div></div><div class="ranges"><div class="range_inputs"><button class="applyBtn" disabled="disabled" type="button"></button> <button class="cancelBtn" type="button"></button></div></div></div>'),this.parentEl=t(a.parentEl&&t(a.parentEl).length?a.parentEl:this.parentEl),this.container=t(a.template).appendTo(this.parentEl),"object"==typeof a.locale&&("string"==typeof a.locale.direction&&(this.locale.direction=a.locale.direction),"string"==typeof a.locale.format&&(this.locale.format=a.locale.format),"string"==typeof a.locale.separator&&(this.locale.separator=a.locale.separator),"object"==typeof a.locale.daysOfWeek&&(this.locale.daysOfWeek=a.locale.daysOfWeek.slice()),"object"==typeof a.locale.monthNames&&(this.locale.monthNames=a.locale.monthNames.slice()),"number"==typeof a.locale.firstDay&&(this.locale.firstDay=a.locale.firstDay),"string"==typeof a.locale.applyLabel&&(this.locale.applyLabel=a.locale.applyLabel),"string"==typeof a.locale.cancelLabel&&(this.locale.cancelLabel=a.locale.cancelLabel),"string"==typeof a.locale.weekLabel&&(this.locale.weekLabel=a.locale.weekLabel),"string"==typeof a.locale.customRangeLabel&&(this.locale.customRangeLabel=a.locale.customRangeLabel)),this.container.addClass(this.locale.direction),"string"==typeof a.startDate&&(this.startDate=e(a.startDate,this.locale.format)),"string"==typeof a.endDate&&(this.endDate=e(a.endDate,this.locale.format)),"string"==typeof a.minDate&&(this.minDate=e(a.minDate,this.locale.format)),"string"==typeof a.maxDate&&(this.maxDate=e(a.maxDate,this.locale.format)),"object"==typeof a.startDate&&(this.startDate=e(a.startDate)),"object"==typeof a.endDate&&(this.endDate=e(a.endDate)),"object"==typeof a.minDate&&(this.minDate=e(a.minDate)),"object"==typeof a.maxDate&&(this.maxDate=e(a.maxDate)),this.minDate&&this.startDate.isBefore(this.minDate)&&(this.startDate=this.minDate.clone()),this.maxDate&&this.endDate.isAfter(this.maxDate)&&(this.endDate=this.maxDate.clone()),"string"==typeof a.applyClass&&(this.applyClass=a.applyClass),"string"==typeof a.cancelClass&&(this.cancelClass=a.cancelClass),"object"==typeof a.dateLimit&&(this.dateLimit=a.dateLimit),"string"==typeof a.opens&&(this.opens=a.opens),"string"==typeof a.drops&&(this.drops=a.drops),"boolean"==typeof a.showWeekNumbers&&(this.showWeekNumbers=a.showWeekNumbers),"boolean"==typeof a.showISOWeekNumbers&&(this.showISOWeekNumbers=a.showISOWeekNumbers),"string"==typeof a.buttonClasses&&(this.buttonClasses=a.buttonClasses),"object"==typeof a.buttonClasses&&(this.buttonClasses=a.buttonClasses.join(" ")),"boolean"==typeof a.showDropdowns&&(this.showDropdowns=a.showDropdowns),"boolean"==typeof a.showCustomRangeLabel&&(this.showCustomRangeLabel=a.showCustomRangeLabel),"boolean"==typeof a.singleDatePicker&&(this.singleDatePicker=a.singleDatePicker,this.singleDatePicker&&(this.endDate=this.startDate.clone())),"boolean"==typeof a.timePicker&&(this.timePicker=a.timePicker),"boolean"==typeof a.timePickerSeconds&&(this.timePickerSeconds=a.timePickerSeconds),"number"==typeof a.timePickerIncrement&&(this.timePickerIncrement=a.timePickerIncrement),"boolean"==typeof a.timePicker24Hour&&(this.timePicker24Hour=a.timePicker24Hour),"boolean"==typeof a.autoApply&&(this.autoApply=a.autoApply),"boolean"==typeof a.autoUpdateInput&&(this.autoUpdateInput=a.autoUpdateInput),"boolean"==typeof a.linkedCalendars&&(this.linkedCalendars=a.linkedCalendars),"function"==typeof a.isInvalidDate&&(this.isInvalidDate=a.isInvalidDate),"function"==typeof a.isCustomDate&&(this.isCustomDate=a.isCustomDate),"boolean"==typeof a.alwaysShowCalendars&&(this.alwaysShowCalendars=a.alwaysShowCalendars),0!=this.locale.firstDay)for(var s=this.locale.firstDay;s>0;)this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift()),s--;var o,r,l;if("undefined"==typeof a.startDate&&"undefined"==typeof a.endDate&&t(this.element).is("input[type=text]")){var c=t(this.element).val(),p=c.split(this.locale.separator);o=r=null,2==p.length?(o=e(p[0],this.locale.format),r=e(p[1],this.locale.format)):this.singleDatePicker&&""!==c&&(o=e(c,this.locale.format),r=e(c,this.locale.format)),null!==o&&null!==r&&(this.setStartDate(o),this.setEndDate(r))}if("object"==typeof a.ranges){for(l in a.ranges){o="string"==typeof a.ranges[l][0]?e(a.ranges[l][0],this.locale.format):e(a.ranges[l][0]),r="string"==typeof a.ranges[l][1]?e(a.ranges[l][1],this.locale.format):e(a.ranges[l][1]),this.minDate&&o.isBefore(this.minDate)&&(o=this.minDate.clone());var d=this.maxDate;if(this.dateLimit&&d&&o.clone().add(this.dateLimit).isAfter(d)&&(d=o.clone().add(this.dateLimit)),d&&r.isAfter(d)&&(r=d.clone()),!(this.minDate&&r.isBefore(this.minDate,this.timepicker?"minute":"day")||d&&o.isAfter(d,this.timepicker?"minute":"day"))){var u=document.createElement("textarea");u.innerHTML=l;var m=u.value;this.ranges[m]=[o,r]}}var f="<ul>";for(l in this.ranges)f+='<li data-range-key="'+l+'">'+l+"</li>";this.showCustomRangeLabel&&(f+='<li data-range-key="'+this.locale.customRangeLabel+'">'+this.locale.customRangeLabel+"</li>"),f+="</ul>",this.container.find(".ranges").prepend(f)}"function"==typeof i&&(this.callback=i),this.timePicker||(this.startDate=this.startDate.startOf("day"),this.endDate=this.endDate.endOf("day"),this.container.find(".calendar-time").hide()),this.timePicker&&this.autoApply&&(this.autoApply=!1),this.autoApply&&"object"!=typeof a.ranges?this.container.find(".ranges").hide():this.autoApply&&this.container.find(".applyBtn, .cancelBtn").addClass("hide"),this.singleDatePicker&&(this.container.addClass("single"),this.container.find(".calendar.left").addClass("single"),this.container.find(".calendar.left").show(),this.container.find(".calendar.right").hide(),this.container.find(".daterangepicker_input input, .daterangepicker_input > i").hide(),this.timePicker?this.container.find(".ranges ul").hide():this.container.find(".ranges").hide()),("undefined"==typeof a.ranges&&!this.singleDatePicker||this.alwaysShowCalendars)&&this.container.addClass("show-calendar"),this.container.addClass("opens"+this.opens),"undefined"!=typeof a.ranges&&"right"==this.opens&&this.container.find(".ranges").prependTo(this.container.find(".calendar.left").parent()),this.container.find(".applyBtn, .cancelBtn").addClass(this.buttonClasses),this.applyClass.length&&this.container.find(".applyBtn").addClass(this.applyClass),this.cancelClass.length&&this.container.find(".cancelBtn").addClass(this.cancelClass),this.container.find(".applyBtn").html(this.locale.applyLabel),this.container.find(".cancelBtn").html(this.locale.cancelLabel),this.container.find(".calendar").on("click.daterangepicker",".prev",t.proxy(this.clickPrev,this)).on("click.daterangepicker",".next",t.proxy(this.clickNext,this)).on("mousedown.daterangepicker","td.available",t.proxy(this.clickDate,this)).on("mouseenter.daterangepicker","td.available",t.proxy(this.hoverDate,this)).on("mouseleave.daterangepicker","td.available",t.proxy(this.updateFormInputs,this)).on("change.daterangepicker","select.yearselect",t.proxy(this.monthOrYearChanged,this)).on("change.daterangepicker","select.monthselect",t.proxy(this.monthOrYearChanged,this)).on("change.daterangepicker","select.hourselect,select.minuteselect,select.secondselect,select.ampmselect",t.proxy(this.timeChanged,this)).on("click.daterangepicker",".daterangepicker_input input",t.proxy(this.showCalendars,this)).on("focus.daterangepicker",".daterangepicker_input input",t.proxy(this.formInputsFocused,this)).on("blur.daterangepicker",".daterangepicker_input input",t.proxy(this.formInputsBlurred,this)).on("change.daterangepicker",".daterangepicker_input input",t.proxy(this.formInputsChanged,this)),this.container.find(".ranges").on("click.daterangepicker","button.applyBtn",t.proxy(this.clickApply,this)).on("click.daterangepicker","button.cancelBtn",t.proxy(this.clickCancel,this)).on("click.daterangepicker","li",t.proxy(this.clickRange,this)).on("mouseenter.daterangepicker","li",t.proxy(this.hoverRange,this)).on("mouseleave.daterangepicker","li",t.proxy(this.updateFormInputs,this)),this.element.is("input")||this.element.is("button")?this.element.on({"click.daterangepicker":t.proxy(this.show,this),"focus.daterangepicker":t.proxy(this.show,this),"keyup.daterangepicker":t.proxy(this.elementChanged,this),"keydown.daterangepicker":t.proxy(this.keydown,this)}):this.element.on("click.daterangepicker",t.proxy(this.toggle,this)),this.element.is("input")&&!this.singleDatePicker&&this.autoUpdateInput?(this.element.val(this.startDate.format(this.locale.format)+this.locale.separator+this.endDate.format(this.locale.format)),this.element.trigger("change")):this.element.is("input")&&this.autoUpdateInput&&(this.element.val(this.startDate.format(this.locale.format)),this.element.trigger("change"))};return n.prototype={constructor:n,setStartDate:function(t){"string"==typeof t&&(this.startDate=e(t,this.locale.format)),"object"==typeof t&&(this.startDate=e(t)),this.timePicker||(this.startDate=this.startDate.startOf("day")),this.timePicker&&this.timePickerIncrement&&this.startDate.minute(Math.round(this.startDate.minute()/this.timePickerIncrement)*this.timePickerIncrement),this.minDate&&this.startDate.isBefore(this.minDate)&&(this.startDate=this.minDate,this.timePicker&&this.timePickerIncrement&&this.startDate.minute(Math.round(this.startDate.minute()/this.timePickerIncrement)*this.timePickerIncrement)),this.maxDate&&this.startDate.isAfter(this.maxDate)&&(this.startDate=this.maxDate,this.timePicker&&this.timePickerIncrement&&this.startDate.minute(Math.floor(this.startDate.minute()/this.timePickerIncrement)*this.timePickerIncrement)),this.isShowing||this.updateElement(),this.updateMonthsInView()},setEndDate:function(t){"string"==typeof t&&(this.endDate=e(t,this.locale.format)),"object"==typeof t&&(this.endDate=e(t)),this.timePicker||(this.endDate=this.endDate.endOf("day")),this.timePicker&&this.timePickerIncrement&&this.endDate.minute(Math.round(this.endDate.minute()/this.timePickerIncrement)*this.timePickerIncrement),this.endDate.isBefore(this.startDate)&&(this.endDate=this.startDate.clone()),this.maxDate&&this.endDate.isAfter(this.maxDate)&&(this.endDate=this.maxDate),this.dateLimit&&this.startDate.clone().add(this.dateLimit).isBefore(this.endDate)&&(this.endDate=this.startDate.clone().add(this.dateLimit)),this.previousRightTime=this.endDate.clone(),this.isShowing||this.updateElement(),this.updateMonthsInView()},isInvalidDate:function(){return!1},isCustomDate:function(){return!1},updateView:function(){this.timePicker&&(this.renderTimePicker("left"),this.renderTimePicker("right"),this.endDate?this.container.find(".right .calendar-time select").removeAttr("disabled").removeClass("disabled"):this.container.find(".right .calendar-time select").attr("disabled","disabled").addClass("disabled")),this.endDate?(this.container.find('input[name="daterangepicker_end"]').removeClass("active"),this.container.find('input[name="daterangepicker_start"]').addClass("active")):(this.container.find('input[name="daterangepicker_end"]').addClass("active"),this.container.find('input[name="daterangepicker_start"]').removeClass("active")),this.updateMonthsInView(),this.updateCalendars(),this.updateFormInputs()},updateMonthsInView:function(){if(this.endDate){if(!this.singleDatePicker&&this.leftCalendar.month&&this.rightCalendar.month&&(this.startDate.format("YYYY-MM")==this.leftCalendar.month.format("YYYY-MM")||this.startDate.format("YYYY-MM")==this.rightCalendar.month.format("YYYY-MM"))&&(this.endDate.format("YYYY-MM")==this.leftCalendar.month.format("YYYY-MM")||this.endDate.format("YYYY-MM")==this.rightCalendar.month.format("YYYY-MM")))return;this.leftCalendar.month=this.startDate.clone().date(2),this.linkedCalendars||this.endDate.month()==this.startDate.month()&&this.endDate.year()==this.startDate.year()?this.rightCalendar.month=this.startDate.clone().date(2).add(1,"month"):this.rightCalendar.month=this.endDate.clone().date(2)}else this.leftCalendar.month.format("YYYY-MM")!=this.startDate.format("YYYY-MM")&&this.rightCalendar.month.format("YYYY-MM")!=this.startDate.format("YYYY-MM")&&(this.leftCalendar.month=this.startDate.clone().date(2),this.rightCalendar.month=this.startDate.clone().date(2).add(1,"month"));this.maxDate&&this.linkedCalendars&&!this.singleDatePicker&&this.rightCalendar.month>this.maxDate&&(this.rightCalendar.month=this.maxDate.clone().date(2),this.leftCalendar.month=this.maxDate.clone().date(2).subtract(1,"month"))},updateCalendars:function(){if(this.timePicker){var e,t,n;if(this.endDate){if(e=parseInt(this.container.find(".left .hourselect").val(),10),t=parseInt(this.container.find(".left .minuteselect").val(),10),n=this.timePickerSeconds?parseInt(this.container.find(".left .secondselect").val(),10):0,!this.timePicker24Hour){var a=this.container.find(".left .ampmselect").val();"PM"===a&&e<12&&(e+=12),"AM"===a&&12===e&&(e=0)}}else if(e=parseInt(this.container.find(".right .hourselect").val(),10),t=parseInt(this.container.find(".right .minuteselect").val(),10),n=this.timePickerSeconds?parseInt(this.container.find(".right .secondselect").val(),10):0,!this.timePicker24Hour){var a=this.container.find(".right .ampmselect").val();"PM"===a&&e<12&&(e+=12),"AM"===a&&12===e&&(e=0)}this.leftCalendar.month.hour(e).minute(t).second(n),this.rightCalendar.month.hour(e).minute(t).second(n)}this.renderCalendar("left"),this.renderCalendar("right"),this.container.find(".ranges li").removeClass("active"),null!=this.endDate&&this.calculateChosenLabel()},renderCalendar:function(n){var a="left"==n?this.leftCalendar:this.rightCalendar,i=a.month.month(),s=a.month.year(),o=a.month.hour(),r=a.month.minute(),l=a.month.second(),c=e([s,i]).daysInMonth(),p=e([s,i,1]),d=e([s,i,c]),u=e(p).subtract(1,"month").month(),m=e(p).subtract(1,"month").year(),f=e([m,u]).daysInMonth(),h=p.day(),a=[];a.firstDay=p,a.lastDay=d;for(var _=0;_<6;_++)a[_]=[];var g=f-h+this.locale.firstDay+1;g>f&&(g-=7),h==this.locale.firstDay&&(g=f-6);for(var b,v,x=e([m,u,g,12,r,l]),_=0,b=0,v=0;_<42;_++,b++,x=e(x).add(24,"hour"))_>0&&b%7===0&&(b=0,v++),a[v][b]=x.clone().hour(o).minute(r).second(l),x.hour(12),this.minDate&&a[v][b].format("YYYY-MM-DD")==this.minDate.format("YYYY-MM-DD")&&a[v][b].isBefore(this.minDate)&&"left"==n&&(a[v][b]=this.minDate.clone()),this.maxDate&&a[v][b].format("YYYY-MM-DD")==this.maxDate.format("YYYY-MM-DD")&&a[v][b].isAfter(this.maxDate)&&"right"==n&&(a[v][b]=this.maxDate.clone());"left"==n?this.leftCalendar.calendar=a:this.rightCalendar.calendar=a;var y="left"==n?this.minDate:this.startDate,w=this.maxDate,k=("left"==n?this.startDate:this.endDate,"ltr"==this.locale.direction?{left:"chevron-left",right:"chevron-right"}:{left:"chevron-right",right:"chevron-left"}),$='<table class="table-condensed">';$+="<thead>",$+="<tr>",(this.showWeekNumbers||this.showISOWeekNumbers)&&($+="<th></th>"),$+=y&&!y.isBefore(a.firstDay)||this.linkedCalendars&&"left"!=n?"<th></th>":'<th class="prev available"><i class="fa fa-'+k.left+" glyphicon glyphicon-"+k.left+'"></i></th>';var j=this.locale.monthNames[a[1][1].month()]+a[1][1].format(" YYYY");if(this.showDropdowns){for(var D=a[1][1].month(),O=a[1][1].year(),C=w&&w.year()||O+5,M=y&&y.year()||O-50,E=O==M,S=O==C,T='<select class="monthselect">',P=0;P<12;P++)T+=(!E||P>=y.month())&&(!S||P<=w.month())?"<option value='"+P+"'"+(P===D?" selected='selected'":"")+">"+this.locale.monthNames[P]+"</option>":"<option value='"+P+"'"+(P===D?" selected='selected'":"")+" disabled='disabled'>"+this.locale.monthNames[P]+"</option>";T+="</select>";for(var I='<select class="yearselect">',L=M;L<=C;L++)I+='<option value="'+L+'"'+(L===O?' selected="selected"':"")+">"+L+"</option>";I+="</select>",j=T+I}if($+='<th colspan="5" class="month">'+j+"</th>",$+=w&&!w.isAfter(a.lastDay)||this.linkedCalendars&&"right"!=n&&!this.singleDatePicker?"<th></th>":'<th class="next available"><i class="fa fa-'+k.right+" glyphicon glyphicon-"+k.right+'"></i></th>',$+="</tr>",$+="<tr>",(this.showWeekNumbers||this.showISOWeekNumbers)&&($+='<th class="week">'+this.locale.weekLabel+"</th>"),t.each(this.locale.daysOfWeek,function(e,t){$+="<th>"+t+"</th>"}),$+="</tr>",$+="</thead>",$+="<tbody>",null==this.endDate&&this.dateLimit){var q=this.startDate.clone().add(this.dateLimit).endOf("day");w&&!q.isBefore(w)||(w=q)}for(var v=0;v<6;v++){$+="<tr>",this.showWeekNumbers?$+='<td class="week">'+a[v][0].week()+"</td>":this.showISOWeekNumbers&&($+='<td class="week">'+a[v][0].isoWeek()+"</td>");for(var b=0;b<7;b++){var A=[];a[v][b].isSame(new Date,"day")&&A.push("today"),a[v][b].isoWeekday()>5&&A.push("weekend"),a[v][b].month()!=a[1][1].month()&&A.push("off"),this.minDate&&a[v][b].isBefore(this.minDate,"day")&&A.push("off","disabled"),w&&a[v][b].isAfter(w,"day")&&A.push("off","disabled"),this.isInvalidDate(a[v][b])&&A.push("off","disabled"),a[v][b].format("YYYY-MM-DD")==this.startDate.format("YYYY-MM-DD")&&A.push("active","start-date"),null!=this.endDate&&a[v][b].format("YYYY-MM-DD")==this.endDate.format("YYYY-MM-DD")&&A.push("active","end-date"),null!=this.endDate&&a[v][b]>this.startDate&&a[v][b]<this.endDate&&A.push("in-range");var R=this.isCustomDate(a[v][b]);R!==!1&&("string"==typeof R?A.push(R):Array.prototype.push.apply(A,R));for(var N="",Y=!1,_=0;_<A.length;_++)N+=A[_]+" ","disabled"==A[_]&&(Y=!0);Y||(N+="available"),$+='<td class="'+N.replace(/^\s+|\s+$/g,"")+'" data-title="r'+v+"c"+b+'">'+a[v][b].date()+"</td>"}$+="</tr>"}$+="</tbody>",$+="</table>",this.container.find(".calendar."+n+" .calendar-table").html($)},renderTimePicker:function(e){if("right"!=e||this.endDate){var t,n,a,i=this.maxDate;if(!this.dateLimit||this.maxDate&&!this.startDate.clone().add(this.dateLimit).isAfter(this.maxDate)||(i=this.startDate.clone().add(this.dateLimit)),"left"==e)n=this.startDate.clone(),a=this.minDate;else if("right"==e){n=this.endDate.clone(),a=this.startDate;var s=this.container.find(".calendar.right .calendar-time div");if(!this.endDate&&""!=s.html()&&(n.hour(s.find(".hourselect option:selected").val()||n.hour()),n.minute(s.find(".minuteselect option:selected").val()||n.minute()),n.second(s.find(".secondselect option:selected").val()||n.second()),!this.timePicker24Hour)){var o=s.find(".ampmselect option:selected").val();"PM"===o&&n.hour()<12&&n.hour(n.hour()+12),"AM"===o&&12===n.hour()&&n.hour(0)}n.isBefore(this.startDate)&&(n=this.startDate.clone()),i&&n.isAfter(i)&&(n=i.clone())}t='<select class="hourselect">';for(var r=this.timePicker24Hour?0:1,l=this.timePicker24Hour?23:12,c=r;c<=l;c++){var p=c;this.timePicker24Hour||(p=n.hour()>=12?12==c?12:c+12:12==c?0:c);var d=n.clone().hour(p),u=!1;a&&d.minute(59).isBefore(a)&&(u=!0),i&&d.minute(0).isAfter(i)&&(u=!0),t+=p!=n.hour()||u?u?'<option value="'+c+'" disabled="disabled" class="disabled">'+c+"</option>":'<option value="'+c+'">'+c+"</option>":'<option value="'+c+'" selected="selected">'+c+"</option>"}t+="</select> ",t+=': <select class="minuteselect">';for(var c=0;c<60;c+=this.timePickerIncrement){var m=c<10?"0"+c:c,d=n.clone().minute(c),u=!1;a&&d.second(59).isBefore(a)&&(u=!0),i&&d.second(0).isAfter(i)&&(u=!0),t+=n.minute()!=c||u?u?'<option value="'+c+'" disabled="disabled" class="disabled">'+m+"</option>":'<option value="'+c+'">'+m+"</option>":'<option value="'+c+'" selected="selected">'+m+"</option>"}if(t+="</select> ",this.timePickerSeconds){t+=': <select class="secondselect">';for(var c=0;c<60;c++){var m=c<10?"0"+c:c,d=n.clone().second(c),u=!1;a&&d.isBefore(a)&&(u=!0),i&&d.isAfter(i)&&(u=!0),t+=n.second()!=c||u?u?'<option value="'+c+'" disabled="disabled" class="disabled">'+m+"</option>":'<option value="'+c+'">'+m+"</option>":'<option value="'+c+'" selected="selected">'+m+"</option>"}t+="</select> "}if(!this.timePicker24Hour){t+='<select class="ampmselect">';var f="",h="";a&&n.clone().hour(12).minute(0).second(0).isBefore(a)&&(f=' disabled="disabled" class="disabled"'),i&&n.clone().hour(0).minute(0).second(0).isAfter(i)&&(h=' disabled="disabled" class="disabled"'),t+=n.hour()>=12?'<option value="AM"'+f+'>AM</option><option value="PM" selected="selected"'+h+">PM</option>":'<option value="AM" selected="selected"'+f+'>AM</option><option value="PM"'+h+">PM</option>",t+="</select>"}this.container.find(".calendar."+e+" .calendar-time div").html(t)}},updateFormInputs:function(){this.container.find("input[name=daterangepicker_start]").is(":focus")||this.container.find("input[name=daterangepicker_end]").is(":focus")||(this.container.find("input[name=daterangepicker_start]").val(this.startDate.format(this.locale.format)),this.endDate&&this.container.find("input[name=daterangepicker_end]").val(this.endDate.format(this.locale.format)),this.singleDatePicker||this.endDate&&(this.startDate.isBefore(this.endDate)||this.startDate.isSame(this.endDate))?this.container.find("button.applyBtn").removeAttr("disabled"):this.container.find("button.applyBtn").attr("disabled","disabled"))},move:function(){var e,n={top:0,left:0},a=t(window).width();this.parentEl.is("body")||(n={top:this.parentEl.offset().top-this.parentEl.scrollTop(),left:this.parentEl.offset().left-this.parentEl.scrollLeft()},a=this.parentEl[0].clientWidth+this.parentEl.offset().left),e="up"==this.drops?this.element.offset().top-this.container.outerHeight()-n.top:this.element.offset().top+this.element.outerHeight()-n.top,this.container["up"==this.drops?"addClass":"removeClass"]("dropup"),"left"==this.opens?(this.container.css({top:e,right:a-this.element.offset().left-this.element.outerWidth(),left:"auto"}),this.container.offset().left<0&&this.container.css({right:"auto",left:9})):"center"==this.opens?(this.container.css({top:e,left:this.element.offset().left-n.left+this.element.outerWidth()/2-this.container.outerWidth()/2,right:"auto"}),this.container.offset().left<0&&this.container.css({right:"auto",left:9})):(this.container.css({top:e,left:this.element.offset().left-n.left,right:"auto"}),this.container.offset().left+this.container.outerWidth()>t(window).width()&&this.container.css({left:"auto",right:0}))},show:function(e){this.isShowing||(this._outsideClickProxy=t.proxy(function(e){this.outsideClick(e)},this),t(document).on("mousedown.daterangepicker",this._outsideClickProxy).on("touchend.daterangepicker",this._outsideClickProxy).on("click.daterangepicker","[data-toggle=dropdown]",this._outsideClickProxy).on("focusin.daterangepicker",this._outsideClickProxy),t(window).on("resize.daterangepicker",t.proxy(function(e){this.move(e)},this)),this.oldStartDate=this.startDate.clone(),this.oldEndDate=this.endDate.clone(),this.previousRightTime=this.endDate.clone(),this.updateView(),this.container.show(),this.move(),this.element.trigger("show.daterangepicker",this),this.isShowing=!0)},hide:function(e){this.isShowing&&(this.endDate||(this.startDate=this.oldStartDate.clone(),this.endDate=this.oldEndDate.clone()),this.startDate.isSame(this.oldStartDate)&&this.endDate.isSame(this.oldEndDate)||this.callback(this.startDate,this.endDate,this.chosenLabel),this.updateElement(),t(document).off(".daterangepicker"),t(window).off(".daterangepicker"),this.container.hide(),this.element.trigger("hide.daterangepicker",this),this.isShowing=!1)},toggle:function(e){this.isShowing?this.hide():this.show()},outsideClick:function(e){var n=t(e.target);"focusin"==e.type||n.closest(this.element).length||n.closest(this.container).length||n.closest(".calendar-table").length||(this.hide(),this.element.trigger("outsideClick.daterangepicker",this))},showCalendars:function(){this.container.addClass("show-calendar"),this.move(),this.element.trigger("showCalendar.daterangepicker",this)},hideCalendars:function(){this.container.removeClass("show-calendar"),this.element.trigger("hideCalendar.daterangepicker",this)},hoverRange:function(e){if(!this.container.find("input[name=daterangepicker_start]").is(":focus")&&!this.container.find("input[name=daterangepicker_end]").is(":focus")){var t=e.target.getAttribute("data-range-key");if(t==this.locale.customRangeLabel)this.updateView();else{var n=this.ranges[t];this.container.find("input[name=daterangepicker_start]").val(n[0].format(this.locale.format)),this.container.find("input[name=daterangepicker_end]").val(n[1].format(this.locale.format))}}},clickRange:function(e){var t=e.target.getAttribute("data-range-key");if(this.chosenLabel=t,t==this.locale.customRangeLabel)this.showCalendars();else{var n=this.ranges[t];this.startDate=n[0],this.endDate=n[1],this.timePicker||(this.startDate.startOf("day"),this.endDate.endOf("day")),this.alwaysShowCalendars||this.hideCalendars(),this.clickApply()}},clickPrev:function(e){var n=t(e.target).parents(".calendar");n.hasClass("left")?(this.leftCalendar.month.subtract(1,"month"),this.linkedCalendars&&this.rightCalendar.month.subtract(1,"month")):this.rightCalendar.month.subtract(1,"month"),this.updateCalendars()},clickNext:function(e){var n=t(e.target).parents(".calendar");n.hasClass("left")?this.leftCalendar.month.add(1,"month"):(this.rightCalendar.month.add(1,"month"),this.linkedCalendars&&this.leftCalendar.month.add(1,"month")),this.updateCalendars()},hoverDate:function(e){if(t(e.target).hasClass("available")){var n=t(e.target).attr("data-title"),a=n.substr(1,1),i=n.substr(3,1),s=t(e.target).parents(".calendar"),o=s.hasClass("left")?this.leftCalendar.calendar[a][i]:this.rightCalendar.calendar[a][i];this.endDate&&!this.container.find("input[name=daterangepicker_start]").is(":focus")?this.container.find("input[name=daterangepicker_start]").val(o.format(this.locale.format)):this.endDate||this.container.find("input[name=daterangepicker_end]").is(":focus")||this.container.find("input[name=daterangepicker_end]").val(o.format(this.locale.format));var r=this.leftCalendar,l=this.rightCalendar,c=this.startDate;this.endDate||this.container.find(".calendar td").each(function(e,n){if(!t(n).hasClass("week")){var a=t(n).attr("data-title"),i=a.substr(1,1),s=a.substr(3,1),p=t(n).parents(".calendar"),d=p.hasClass("left")?r.calendar[i][s]:l.calendar[i][s];d.isAfter(c)&&d.isBefore(o)||d.isSame(o,"day")?t(n).addClass("in-range"):t(n).removeClass("in-range")}})}},clickDate:function(e){if(t(e.target).hasClass("available")){var n=t(e.target).attr("data-title"),a=n.substr(1,1),i=n.substr(3,1),s=t(e.target).parents(".calendar"),o=s.hasClass("left")?this.leftCalendar.calendar[a][i]:this.rightCalendar.calendar[a][i];if(this.endDate||o.isBefore(this.startDate,"day")){if(this.timePicker){var r=parseInt(this.container.find(".left .hourselect").val(),10);if(!this.timePicker24Hour){var l=this.container.find(".left .ampmselect").val();"PM"===l&&r<12&&(r+=12),"AM"===l&&12===r&&(r=0)}var c=parseInt(this.container.find(".left .minuteselect").val(),10),p=this.timePickerSeconds?parseInt(this.container.find(".left .secondselect").val(),10):0;o=o.clone().hour(r).minute(c).second(p)}this.endDate=null,this.setStartDate(o.clone())}else if(!this.endDate&&o.isBefore(this.startDate))this.setEndDate(this.startDate.clone());else{if(this.timePicker){var r=parseInt(this.container.find(".right .hourselect").val(),10);if(!this.timePicker24Hour){var l=this.container.find(".right .ampmselect").val();"PM"===l&&r<12&&(r+=12),"AM"===l&&12===r&&(r=0)}var c=parseInt(this.container.find(".right .minuteselect").val(),10),p=this.timePickerSeconds?parseInt(this.container.find(".right .secondselect").val(),10):0;o=o.clone().hour(r).minute(c).second(p)}this.setEndDate(o.clone()),this.autoApply&&(this.calculateChosenLabel(),this.clickApply())}this.singleDatePicker&&(this.setEndDate(this.startDate),this.timePicker||this.clickApply()),this.updateView(),e.stopPropagation()}},calculateChosenLabel:function(){var e=!0,t=0;for(var n in this.ranges){if(this.timePicker){if(this.startDate.isSame(this.ranges[n][0])&&this.endDate.isSame(this.ranges[n][1])){e=!1,this.chosenLabel=this.container.find(".ranges li:eq("+t+")").addClass("active").html();break}}else if(this.startDate.format("YYYY-MM-DD")==this.ranges[n][0].format("YYYY-MM-DD")&&this.endDate.format("YYYY-MM-DD")==this.ranges[n][1].format("YYYY-MM-DD")){ e=!1,this.chosenLabel=this.container.find(".ranges li:eq("+t+")").addClass("active").html();break}t++}e&&this.showCustomRangeLabel&&(this.chosenLabel=this.container.find(".ranges li:last").addClass("active").html(),this.showCalendars())},clickApply:function(e){this.hide(),this.element.trigger("apply.daterangepicker",this)},clickCancel:function(e){this.startDate=this.oldStartDate,this.endDate=this.oldEndDate,this.hide(),this.element.trigger("cancel.daterangepicker",this)},monthOrYearChanged:function(e){var n=t(e.target).closest(".calendar").hasClass("left"),a=n?"left":"right",i=this.container.find(".calendar."+a),s=parseInt(i.find(".monthselect").val(),10),o=i.find(".yearselect").val();n||(o<this.startDate.year()||o==this.startDate.year()&&s<this.startDate.month())&&(s=this.startDate.month(),o=this.startDate.year()),this.minDate&&(o<this.minDate.year()||o==this.minDate.year()&&s<this.minDate.month())&&(s=this.minDate.month(),o=this.minDate.year()),this.maxDate&&(o>this.maxDate.year()||o==this.maxDate.year()&&s>this.maxDate.month())&&(s=this.maxDate.month(),o=this.maxDate.year()),n?(this.leftCalendar.month.month(s).year(o),this.linkedCalendars&&(this.rightCalendar.month=this.leftCalendar.month.clone().add(1,"month"))):(this.rightCalendar.month.month(s).year(o),this.linkedCalendars&&(this.leftCalendar.month=this.rightCalendar.month.clone().subtract(1,"month"))),this.updateCalendars()},timeChanged:function(e){var n=t(e.target).closest(".calendar"),a=n.hasClass("left"),i=parseInt(n.find(".hourselect").val(),10),s=parseInt(n.find(".minuteselect").val(),10),o=this.timePickerSeconds?parseInt(n.find(".secondselect").val(),10):0;if(!this.timePicker24Hour){var r=n.find(".ampmselect").val();"PM"===r&&i<12&&(i+=12),"AM"===r&&12===i&&(i=0)}if(a){var l=this.startDate.clone();l.hour(i),l.minute(s),l.second(o),this.setStartDate(l),this.singleDatePicker?this.endDate=this.startDate.clone():this.endDate&&this.endDate.format("YYYY-MM-DD")==l.format("YYYY-MM-DD")&&this.endDate.isBefore(l)&&this.setEndDate(l.clone())}else if(this.endDate){var c=this.endDate.clone();c.hour(i),c.minute(s),c.second(o),this.setEndDate(c)}this.updateCalendars(),this.updateFormInputs(),this.renderTimePicker("left"),this.renderTimePicker("right")},formInputsChanged:function(n){var a=t(n.target).closest(".calendar").hasClass("right"),i=e(this.container.find('input[name="daterangepicker_start"]').val(),this.locale.format),s=e(this.container.find('input[name="daterangepicker_end"]').val(),this.locale.format);i.isValid()&&s.isValid()&&(a&&s.isBefore(i)&&(i=s.clone()),this.setStartDate(i),this.setEndDate(s),a?this.container.find('input[name="daterangepicker_start"]').val(this.startDate.format(this.locale.format)):this.container.find('input[name="daterangepicker_end"]').val(this.endDate.format(this.locale.format))),this.updateView()},formInputsFocused:function(e){this.container.find('input[name="daterangepicker_start"], input[name="daterangepicker_end"]').removeClass("active"),t(e.target).addClass("active");var n=t(e.target).closest(".calendar").hasClass("right");n&&(this.endDate=null,this.setStartDate(this.startDate.clone()),this.updateView())},formInputsBlurred:function(t){if(!this.endDate){var n=this.container.find('input[name="daterangepicker_end"]').val(),a=e(n,this.locale.format);a.isValid()&&(this.setEndDate(a),this.updateView())}},elementChanged:function(){if(this.element.is("input")&&this.element.val().length&&!(this.element.val().length<this.locale.format.length)){var t=this.element.val().split(this.locale.separator),n=null,a=null;2===t.length&&(n=e(t[0],this.locale.format),a=e(t[1],this.locale.format)),(this.singleDatePicker||null===n||null===a)&&(n=e(this.element.val(),this.locale.format),a=n),n.isValid()&&a.isValid()&&(this.setStartDate(n),this.setEndDate(a),this.updateView())}},keydown:function(e){9!==e.keyCode&&13!==e.keyCode||this.hide()},updateElement:function(){this.element.is("input")&&!this.singleDatePicker&&this.autoUpdateInput?(this.element.val(this.startDate.format(this.locale.format)+this.locale.separator+this.endDate.format(this.locale.format)),this.element.trigger("change")):this.element.is("input")&&this.autoUpdateInput&&(this.element.val(this.startDate.format(this.locale.format)),this.element.trigger("change"))},remove:function(){this.container.remove(),this.element.off(".daterangepicker"),this.element.removeData()}},t.fn.daterangepicker=function(e,a){return this.each(function(){var i=t(this);i.data("daterangepicker")&&i.data("daterangepicker").remove(),i.data("daterangepicker",new n(i,e,a))}),this},n}),$p.utils.__define({mime_db:{value:{"application/andrew-inset":{extensions:["ez"]},"application/applixware":{extensions:["aw"]},"application/atom+xml":{compressible:!0,extensions:["atom"]},"application/atomcat+xml":{extensions:["atomcat"]},"application/atomsvc+xml":{extensions:["atomsvc"]},"application/bdoc":{compressible:!1,extensions:["bdoc"]},"application/ccxml+xml":{extensions:["ccxml"]},"application/cdmi-capability":{extensions:["cdmia"]},"application/cdmi-container":{extensions:["cdmic"]},"application/cdmi-domain":{extensions:["cdmid"]},"application/cdmi-object":{extensions:["cdmio"]},"application/cdmi-queue":{extensions:["cdmiq"]},"application/cu-seeme":{extensions:["cu"]},"application/dash+xml":{extensions:["mpd"]},"application/davmount+xml":{extensions:["davmount"]},"application/docbook+xml":{extensions:["dbk"]},"application/dssc+der":{extensions:["dssc"]},"application/dssc+xml":{extensions:["xdssc"]},"application/ecmascript":{compressible:!0,extensions:["ecma"]},"application/emma+xml":{extensions:["emma"]},"application/epub+zip":{extensions:["epub"]},"application/exi":{extensions:["exi"]},"application/font-tdpfr":{extensions:["pfr"]},"application/font-woff":{compressible:!1,extensions:["woff"]},"application/font-woff2":{compressible:!1,extensions:["woff2"]},"application/gml+xml":{extensions:["gml"]},"application/gpx+xml":{extensions:["gpx"]},"application/gxf":{extensions:["gxf"]},"application/hyperstudio":{extensions:["stk"]},"application/inkml+xml":{extensions:["ink","inkml"]},"application/ipfix":{extensions:["ipfix"]},"application/java-archive":{compressible:!1,extensions:["jar","war","ear"]},"application/java-serialized-object":{compressible:!1,extensions:["ser"]},"application/java-vm":{compressible:!1,extensions:["class"]},"application/javascript":{charset:"UTF-8",compressible:!0,extensions:["js"]},"application/json":{charset:"UTF-8",compressible:!0,extensions:["json","map"]},"application/json-patch+json":{compressible:!0},"application/json5":{extensions:["json5"]},"application/jsonml+json":{compressible:!0,extensions:["jsonml"]},"application/ld+json":{compressible:!0,extensions:["jsonld"]},"application/lost+xml":{extensions:["lostxml"]},"application/mac-binhex40":{extensions:["hqx"]},"application/mac-compactpro":{extensions:["cpt"]},"application/mads+xml":{extensions:["mads"]},"application/manifest+json":{charset:"UTF-8",compressible:!0,extensions:["webmanifest"]},"application/marc":{extensions:["mrc"]},"application/marcxml+xml":{extensions:["mrcx"]},"application/mathematica":{extensions:["ma","nb","mb"]},"application/mathml+xml":{extensions:["mathml"]},"application/mbox":{extensions:["mbox"]},"application/mediaservercontrol+xml":{extensions:["mscml"]},"application/metalink+xml":{extensions:["metalink"]},"application/metalink4+xml":{extensions:["meta4"]},"application/mets+xml":{extensions:["mets"]},"application/mods+xml":{extensions:["mods"]},"application/mp21":{extensions:["m21","mp21"]},"application/mp4":{extensions:["mp4s","m4p"]},"application/msword":{compressible:!1,extensions:["doc","dot"]},"application/mxf":{extensions:["mxf"]},"application/octet-stream":{compressible:!1,extensions:["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"]},"application/oda":{extensions:["oda"]},"application/oebps-package+xml":{extensions:["opf"]},"application/ogg":{compressible:!1,extensions:["ogx"]},"application/omdoc+xml":{extensions:["omdoc"]},"application/onenote":{extensions:["onetoc","onetoc2","onetmp","onepkg"]},"application/oxps":{extensions:["oxps"]},"application/patch-ops-error+xml":{extensions:["xer"]},"application/pdf":{compressible:!1,extensions:["pdf"]},"application/pgp-encrypted":{compressible:!1,extensions:["pgp"]},"application/pgp-signature":{extensions:["asc","sig"]},"application/pics-rules":{extensions:["prf"]},"application/pkcs10":{extensions:["p10"]},"application/pkcs7-mime":{extensions:["p7m","p7c"]},"application/pkcs7-signature":{extensions:["p7s"]},"application/pkcs8":{extensions:["p8"]},"application/pkix-attr-cert":{extensions:["ac"]},"application/pkix-cert":{extensions:["cer"]},"application/pkix-crl":{extensions:["crl"]},"application/pkix-pkipath":{extensions:["pkipath"]},"application/pkixcmp":{extensions:["pki"]},"application/pls+xml":{extensions:["pls"]},"application/postscript":{compressible:!0,extensions:["ai","eps","ps"]},"application/prs.cww":{extensions:["cww"]},"application/pskc+xml":{extensions:["pskcxml"]},"application/rdf+xml":{compressible:!0,extensions:["rdf"]},"application/reginfo+xml":{extensions:["rif"]},"application/relax-ng-compact-syntax":{extensions:["rnc"]},"application/resource-lists+xml":{extensions:["rl"]},"application/resource-lists-diff+xml":{extensions:["rld"]},"application/rls-services+xml":{extensions:["rs"]},"application/rpki-ghostbusters":{extensions:["gbr"]},"application/rpki-manifest":{extensions:["mft"]},"application/rpki-roa":{extensions:["roa"]},"application/rsd+xml":{extensions:["rsd"]},"application/rss+xml":{compressible:!0,extensions:["rss"]},"application/rtf":{compressible:!0,extensions:["rtf"]},"application/sbml+xml":{extensions:["sbml"]},"application/scvp-cv-request":{extensions:["scq"]},"application/scvp-cv-response":{extensions:["scs"]},"application/scvp-vp-request":{extensions:["spq"]},"application/scvp-vp-response":{extensions:["spp"]},"application/sdp":{extensions:["sdp"]},"application/set-payment-initiation":{extensions:["setpay"]},"application/set-registration-initiation":{extensions:["setreg"]},"application/shf+xml":{extensions:["shf"]},"application/smil+xml":{extensions:["smi","smil"]},"application/sparql-query":{extensions:["rq"]},"application/sparql-results+xml":{extensions:["srx"]},"application/srgs":{extensions:["gram"]},"application/srgs+xml":{extensions:["grxml"]},"application/sru+xml":{extensions:["sru"]},"application/ssdl+xml":{extensions:["ssdl"]},"application/ssml+xml":{extensions:["ssml"]},"application/tei+xml":{extensions:["tei","teicorpus"]},"application/thraud+xml":{extensions:["tfi"]},"application/timestamped-data":{extensions:["tsd"]},"application/vnd.3gpp.pic-bw-large":{extensions:["plb"]},"application/vnd.3gpp.pic-bw-small":{extensions:["psb"]},"application/vnd.3gpp.pic-bw-var":{extensions:["pvb"]},"application/vnd.3gpp2.tcap":{extensions:["tcap"]},"application/vnd.3m.post-it-notes":{extensions:["pwn"]},"application/vnd.accpac.simply.aso":{extensions:["aso"]},"application/vnd.accpac.simply.imp":{extensions:["imp"]},"application/vnd.acucobol":{extensions:["acu"]},"application/vnd.acucorp":{extensions:["atc","acutc"]},"application/vnd.adobe.air-application-installer-package+zip":{extensions:["air"]},"application/vnd.adobe.formscentral.fcdt":{extensions:["fcdt"]},"application/vnd.adobe.fxp":{extensions:["fxp","fxpl"]},"application/vnd.adobe.xdp+xml":{extensions:["xdp"]},"application/vnd.adobe.xfdf":{extensions:["xfdf"]},"application/vnd.ahead.space":{extensions:["ahead"]},"application/vnd.airzip.filesecure.azf":{extensions:["azf"]},"application/vnd.airzip.filesecure.azs":{extensions:["azs"]},"application/vnd.amazon.ebook":{extensions:["azw"]},"application/vnd.americandynamics.acc":{extensions:["acc"]},"application/vnd.amiga.ami":{extensions:["ami"]},"application/vnd.android.package-archive":{compressible:!1,extensions:["apk"]},"application/vnd.anser-web-certificate-issue-initiation":{extensions:["cii"]},"application/vnd.anser-web-funds-transfer-initiation":{extensions:["fti"]},"application/vnd.antix.game-component":{extensions:["atx"]},"application/vnd.apple.installer+xml":{extensions:["mpkg"]},"application/vnd.apple.mpegurl":{extensions:["m3u8"]},"application/vnd.apple.pkpass":{compressible:!1,extensions:["pkpass"]},"application/vnd.aristanetworks.swi":{extensions:["swi"]},"application/vnd.astraea-software.iota":{extensions:["iota"]},"application/vnd.audiograph":{extensions:["aep"]},"application/vnd.blueice.multipass":{extensions:["mpm"]},"application/vnd.bmi":{extensions:["bmi"]},"application/vnd.businessobjects":{extensions:["rep"]},"application/vnd.chemdraw+xml":{extensions:["cdxml"]},"application/vnd.chipnuts.karaoke-mmd":{extensions:["mmd"]},"application/vnd.cinderella":{extensions:["cdy"]},"application/vnd.claymore":{extensions:["cla"]},"application/vnd.cloanto.rp9":{extensions:["rp9"]},"application/vnd.clonk.c4group":{extensions:["c4g","c4d","c4f","c4p","c4u"]},"application/vnd.cluetrust.cartomobile-config":{extensions:["c11amc"]},"application/vnd.cluetrust.cartomobile-config-pkg":{extensions:["c11amz"]},"application/vnd.commonspace":{extensions:["csp"]},"application/vnd.contact.cmsg":{extensions:["cdbcmsg"]},"application/vnd.cosmocaller":{extensions:["cmc"]},"application/vnd.crick.clicker":{extensions:["clkx"]},"application/vnd.crick.clicker.keyboard":{extensions:["clkk"]},"application/vnd.crick.clicker.palette":{extensions:["clkp"]},"application/vnd.crick.clicker.template":{extensions:["clkt"]},"application/vnd.crick.clicker.wordbank":{extensions:["clkw"]},"application/vnd.criticaltools.wbs+xml":{extensions:["wbs"]},"application/vnd.ctc-posml":{extensions:["pml"]},"application/vnd.cups-ppd":{extensions:["ppd"]},"application/vnd.curl.car":{extensions:["car"]},"application/vnd.curl.pcurl":{extensions:["pcurl"]},"application/vnd.dart":{compressible:!0,extensions:["dart"]},"application/vnd.data-vision.rdz":{extensions:["rdz"]},"application/vnd.dece.data":{extensions:["uvf","uvvf","uvd","uvvd"]},"application/vnd.dece.ttml+xml":{extensions:["uvt","uvvt"]},"application/vnd.dece.unspecified":{extensions:["uvx","uvvx"]},"application/vnd.dece.zip":{extensions:["uvz","uvvz"]},"application/vnd.denovo.fcselayout-link":{extensions:["fe_launch"]},"application/vnd.dna":{extensions:["dna"]},"application/vnd.dolby.mlp":{extensions:["mlp"]},"application/vnd.dpgraph":{extensions:["dpg"]},"application/vnd.dreamfactory":{extensions:["dfac"]},"application/vnd.ds-keypoint":{extensions:["kpxx"]},"application/vnd.dvb.ait":{extensions:["ait"]},"application/vnd.dvb.service":{extensions:["svc"]},"application/vnd.dynageo":{extensions:["geo"]},"application/vnd.ecowin.chart":{extensions:["mag"]},"application/vnd.enliven":{extensions:["nml"]},"application/vnd.epson.esf":{extensions:["esf"]},"application/vnd.epson.msf":{extensions:["msf"]},"application/vnd.epson.quickanime":{extensions:["qam"]},"application/vnd.epson.salt":{extensions:["slt"]},"application/vnd.epson.ssf":{extensions:["ssf"]},"application/vnd.eszigno3+xml":{extensions:["es3","et3"]},"application/vnd.ezpix-album":{extensions:["ez2"]},"application/vnd.ezpix-package":{extensions:["ez3"]},"application/vnd.fdf":{extensions:["fdf"]},"application/vnd.fdsn.mseed":{extensions:["mseed"]},"application/vnd.fdsn.seed":{extensions:["seed","dataless"]},"application/vnd.flographit":{extensions:["gph"]},"application/vnd.fluxtime.clip":{extensions:["ftc"]},"application/vnd.framemaker":{extensions:["fm","frame","maker","book"]},"application/vnd.frogans.fnc":{extensions:["fnc"]},"application/vnd.frogans.ltf":{extensions:["ltf"]},"application/vnd.fsc.weblaunch":{extensions:["fsc"]},"application/vnd.fujitsu.oasys":{extensions:["oas"]},"application/vnd.fujitsu.oasys2":{extensions:["oa2"]},"application/vnd.fujitsu.oasys3":{extensions:["oa3"]},"application/vnd.fujitsu.oasysgp":{extensions:["fg5"]},"application/vnd.fujitsu.oasysprs":{extensions:["bh2"]},"application/vnd.fujixerox.ddd":{extensions:["ddd"]},"application/vnd.fujixerox.docuworks":{extensions:["xdw"]},"application/vnd.fujixerox.docuworks.binder":{extensions:["xbd"]},"application/vnd.fuzzysheet":{extensions:["fzs"]},"application/vnd.genomatix.tuxedo":{extensions:["txd"]},"application/vnd.geogebra.file":{extensions:["ggb"]},"application/vnd.geogebra.tool":{extensions:["ggt"]},"application/vnd.geometry-explorer":{extensions:["gex","gre"]},"application/vnd.geonext":{extensions:["gxt"]},"application/vnd.geoplan":{extensions:["g2w"]},"application/vnd.geospace":{extensions:["g3w"]},"application/vnd.gmx":{extensions:["gmx"]},"application/vnd.google-apps.document":{compressible:!1,extensions:["gdoc"]},"application/vnd.google-apps.presentation":{compressible:!1,extensions:["gslides"]},"application/vnd.google-apps.spreadsheet":{compressible:!1,extensions:["gsheet"]},"application/vnd.google-earth.kml+xml":{compressible:!0,extensions:["kml"]},"application/vnd.google-earth.kmz":{compressible:!1,extensions:["kmz"]},"application/vnd.grafeq":{extensions:["gqf","gqs"]},"application/vnd.groove-account":{extensions:["gac"]},"application/vnd.groove-help":{extensions:["ghf"]},"application/vnd.groove-identity-message":{extensions:["gim"]},"application/vnd.groove-injector":{extensions:["grv"]},"application/vnd.groove-tool-message":{extensions:["gtm"]},"application/vnd.groove-tool-template":{extensions:["tpl"]},"application/vnd.groove-vcard":{extensions:["vcg"]},"application/vnd.hal+xml":{extensions:["hal"]},"application/vnd.handheld-entertainment+xml":{extensions:["zmm"]},"application/vnd.hbci":{extensions:["hbci"]},"application/vnd.hhe.lesson-player":{extensions:["les"]},"application/vnd.hp-hpgl":{extensions:["hpgl"]},"application/vnd.hp-hpid":{extensions:["hpid"]},"application/vnd.hp-hps":{extensions:["hps"]},"application/vnd.hp-jlyt":{extensions:["jlt"]},"application/vnd.hp-pcl":{extensions:["pcl"]},"application/vnd.hp-pclxl":{extensions:["pclxl"]},"application/vnd.hydrostatix.sof-data":{extensions:["sfd-hdstx"]},"application/vnd.ibm.minipay":{extensions:["mpy"]},"application/vnd.ibm.modcap":{extensions:["afp","listafp","list3820"]},"application/vnd.ibm.rights-management":{extensions:["irm"]},"application/vnd.ibm.secure-container":{extensions:["sc"]},"application/vnd.iccprofile":{extensions:["icc","icm"]},"application/vnd.igloader":{extensions:["igl"]},"application/vnd.immervision-ivp":{extensions:["ivp"]},"application/vnd.immervision-ivu":{extensions:["ivu"]},"application/vnd.insors.igm":{extensions:["igm"]},"application/vnd.intercon.formnet":{extensions:["xpw","xpx"]},"application/vnd.intergeo":{extensions:["i2g"]},"application/vnd.intu.qbo":{extensions:["qbo"]},"application/vnd.intu.qfx":{extensions:["qfx"]},"application/vnd.ipunplugged.rcprofile":{extensions:["rcprofile"]},"application/vnd.irepository.package+xml":{extensions:["irp"]},"application/vnd.is-xpr":{extensions:["xpr"]},"application/vnd.isac.fcs":{extensions:["fcs"]},"application/vnd.jam":{extensions:["jam"]},"application/vnd.jcp.javame.midlet-rms":{extensions:["rms"]},"application/vnd.jisp":{extensions:["jisp"]},"application/vnd.joost.joda-archive":{extensions:["joda"]},"application/vnd.kahootz":{extensions:["ktz","ktr"]},"application/vnd.kde.karbon":{extensions:["karbon"]},"application/vnd.kde.kchart":{extensions:["chrt"]},"application/vnd.kde.kformula":{extensions:["kfo"]},"application/vnd.kde.kivio":{extensions:["flw"]},"application/vnd.kde.kontour":{extensions:["kon"]},"application/vnd.kde.kpresenter":{extensions:["kpr","kpt"]},"application/vnd.kde.kspread":{extensions:["ksp"]},"application/vnd.kde.kword":{extensions:["kwd","kwt"]},"application/vnd.kenameaapp":{extensions:["htke"]},"application/vnd.kidspiration":{extensions:["kia"]},"application/vnd.kinar":{extensions:["kne","knp"]},"application/vnd.koan":{extensions:["skp","skd","skt","skm"]},"application/vnd.kodak-descriptor":{extensions:["sse"]},"application/vnd.las.las+xml":{extensions:["lasxml"]},"application/vnd.llamagraphics.life-balance.desktop":{extensions:["lbd"]},"application/vnd.llamagraphics.life-balance.exchange+xml":{extensions:["lbe"]},"application/vnd.lotus-1-2-3":{extensions:["123"]},"application/vnd.lotus-approach":{extensions:["apr"]},"application/vnd.lotus-freelance":{extensions:["pre"]},"application/vnd.lotus-notes":{extensions:["nsf"]},"application/vnd.lotus-organizer":{extensions:["org"]},"application/vnd.lotus-screencam":{extensions:["scm"]},"application/vnd.lotus-wordpro":{extensions:["lwp"]},"application/vnd.macports.portpkg":{extensions:["portpkg"]},"application/vnd.mcd":{extensions:["mcd"]},"application/vnd.medcalcdata":{extensions:["mc1"]},"application/vnd.mediastation.cdkey":{extensions:["cdkey"]},"application/vnd.mfer":{extensions:["mwf"]},"application/vnd.mfmp":{extensions:["mfm"]},"application/vnd.micrografx.flo":{extensions:["flo"]},"application/vnd.micrografx.igx":{extensions:["igx"]},"application/vnd.mif":{extensions:["mif"]},"application/vnd.mobius.daf":{extensions:["daf"]},"application/vnd.mobius.dis":{extensions:["dis"]},"application/vnd.mobius.mbk":{extensions:["mbk"]},"application/vnd.mobius.mqy":{extensions:["mqy"]},"application/vnd.mobius.msl":{extensions:["msl"]},"application/vnd.mobius.plc":{extensions:["plc"]},"application/vnd.mobius.txf":{extensions:["txf"]},"application/vnd.mophun.application":{extensions:["mpn"]},"application/vnd.mophun.certificate":{extensions:["mpc"]},"application/vnd.mozilla.xul+xml":{compressible:!0,extensions:["xul"]},"application/vnd.ms-cab-compressed":{extensions:["cab"]},"application/vnd.ms-excel":{compressible:!1,extensions:["xls","xlm","xla","xlc","xlt","xlw"]},"application/vnd.ms-excel.addin.macroenabled.12":{extensions:["xlam"]},"application/vnd.ms-excel.sheet.binary.macroenabled.12":{extensions:["xlsb"]},"application/vnd.ms-excel.sheet.macroenabled.12":{extensions:["xlsm"]},"application/vnd.ms-excel.template.macroenabled.12":{extensions:["xltm"]},"application/vnd.ms-fontobject":{compressible:!0,extensions:["eot"]},"application/vnd.ms-htmlhelp":{extensions:["chm"]},"application/vnd.ms-ims":{extensions:["ims"]},"application/vnd.ms-lrm":{extensions:["lrm"]},"application/vnd.ms-officetheme":{extensions:["thmx"]},"application/vnd.ms-opentype":{compressible:!0},"application/vnd.ms-pki.seccat":{extensions:["cat"]},"application/vnd.ms-pki.stl":{extensions:["stl"]},"application/vnd.ms-powerpoint":{compressible:!1,extensions:["ppt","pps","pot"]},"application/vnd.ms-powerpoint.addin.macroenabled.12":{extensions:["ppam"]},"application/vnd.ms-powerpoint.presentation.macroenabled.12":{extensions:["pptm"]},"application/vnd.ms-powerpoint.slide.macroenabled.12":{extensions:["sldm"]},"application/vnd.ms-powerpoint.slideshow.macroenabled.12":{extensions:["ppsm"]},"application/vnd.ms-powerpoint.template.macroenabled.12":{extensions:["potm"]},"application/vnd.ms-project":{extensions:["mpp","mpt"]},"application/vnd.ms-word.document.macroenabled.12":{extensions:["docm"]},"application/vnd.ms-word.template.macroenabled.12":{extensions:["dotm"]},"application/vnd.ms-works":{extensions:["wps","wks","wcm","wdb"]},"application/vnd.ms-wpl":{extensions:["wpl"]},"application/vnd.ms-xpsdocument":{compressible:!1,extensions:["xps"]},"application/vnd.mseq":{extensions:["mseq"]},"application/vnd.musician":{extensions:["mus"]},"application/vnd.muvee.style":{extensions:["msty"]},"application/vnd.mynfc":{extensions:["taglet"]},"application/vnd.neurolanguage.nlu":{extensions:["nlu"]},"application/vnd.nitf":{extensions:["ntf","nitf"]},"application/vnd.noblenet-directory":{extensions:["nnd"]},"application/vnd.noblenet-sealer":{extensions:["nns"]},"application/vnd.noblenet-web":{extensions:["nnw"]},"application/vnd.nokia.n-gage.data":{extensions:["ngdat"]},"application/vnd.nokia.n-gage.symbian.install":{extensions:["n-gage"]},"application/vnd.nokia.radio-preset":{extensions:["rpst"]},"application/vnd.nokia.radio-presets":{extensions:["rpss"]},"application/vnd.novadigm.edm":{extensions:["edm"]},"application/vnd.novadigm.edx":{extensions:["edx"]},"application/vnd.novadigm.ext":{extensions:["ext"]},"application/vnd.oasis.opendocument.chart":{extensions:["odc"]},"application/vnd.oasis.opendocument.chart-template":{extensions:["otc"]},"application/vnd.oasis.opendocument.database":{extensions:["odb"]},"application/vnd.oasis.opendocument.formula":{extensions:["odf"]},"application/vnd.oasis.opendocument.formula-template":{extensions:["odft"]},"application/vnd.oasis.opendocument.graphics":{compressible:!1,extensions:["odg"]},"application/vnd.oasis.opendocument.graphics-template":{extensions:["otg"]},"application/vnd.oasis.opendocument.image":{extensions:["odi"]},"application/vnd.oasis.opendocument.image-template":{extensions:["oti"]},"application/vnd.oasis.opendocument.presentation":{compressible:!1,extensions:["odp"]},"application/vnd.oasis.opendocument.presentation-template":{extensions:["otp"]},"application/vnd.oasis.opendocument.spreadsheet":{compressible:!1,extensions:["ods"]},"application/vnd.oasis.opendocument.spreadsheet-template":{extensions:["ots"]},"application/vnd.oasis.opendocument.text":{compressible:!1,extensions:["odt"]},"application/vnd.oasis.opendocument.text-master":{extensions:["odm"]},"application/vnd.oasis.opendocument.text-template":{extensions:["ott"]},"application/vnd.oasis.opendocument.text-web":{extensions:["oth"]},"application/vnd.olpc-sugar":{extensions:["xo"]},"application/vnd.oma.dd2+xml":{extensions:["dd2"]},"application/vnd.openofficeorg.extension":{extensions:["oxt"]},"application/vnd.openxmlformats-officedocument.presentationml.presentation":{compressible:!1,extensions:["pptx"]},"application/vnd.openxmlformats-officedocument.presentationml.slide":{extensions:["sldx"]},"application/vnd.openxmlformats-officedocument.presentationml.slideshow":{extensions:["ppsx"]},"application/vnd.openxmlformats-officedocument.presentationml.template":{extensions:["potx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":{compressible:!1,extensions:["xlsx"]},"application/vnd.openxmlformats-officedocument.spreadsheetml.template":{extensions:["xltx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.document":{compressible:!1,extensions:["docx"]},"application/vnd.openxmlformats-officedocument.wordprocessingml.template":{extensions:["dotx"]},"application/vnd.osgeo.mapguide.package":{extensions:["mgp"]},"application/vnd.osgi.dp":{extensions:["dp"]},"application/vnd.osgi.subsystem":{extensions:["esa"]},"application/vnd.palm":{extensions:["pdb","pqa","oprc"]},"application/vnd.pawaafile":{extensions:["paw"]},"application/vnd.pg.format":{extensions:["str"]},"application/vnd.pg.osasli":{extensions:["ei6"]},"application/vnd.picsel":{extensions:["efif"]},"application/vnd.pmi.widget":{extensions:["wg"]},"application/vnd.pocketlearn":{extensions:["plf"]},"application/vnd.powerbuilder6":{extensions:["pbd"]},"application/vnd.previewsystems.box":{extensions:["box"]},"application/vnd.proteus.magazine":{extensions:["mgz"]},"application/vnd.publishare-delta-tree":{extensions:["qps"]},"application/vnd.pvi.ptid1":{extensions:["ptid"]},"application/vnd.quark.quarkxpress":{extensions:["qxd","qxt","qwd","qwt","qxl","qxb"]},"application/vnd.realvnc.bed":{extensions:["bed"]},"application/vnd.recordare.musicxml":{extensions:["mxl"]},"application/vnd.recordare.musicxml+xml":{extensions:["musicxml"]},"application/vnd.rig.cryptonote":{extensions:["cryptonote"]},"application/vnd.rim.cod":{extensions:["cod"]},"application/vnd.rn-realmedia":{extensions:["rm"]},"application/vnd.rn-realmedia-vbr":{extensions:["rmvb"]},"application/vnd.route66.link66+xml":{extensions:["link66"]},"application/vnd.sailingtracker.track":{extensions:["st"]},"application/vnd.seemail":{extensions:["see"]},"application/vnd.sema":{extensions:["sema"]},"application/vnd.semd":{extensions:["semd"]},"application/vnd.semf":{extensions:["semf"]},"application/vnd.shana.informed.formdata":{extensions:["ifm"]},"application/vnd.shana.informed.formtemplate":{extensions:["itp"]},"application/vnd.shana.informed.interchange":{extensions:["iif"]},"application/vnd.shana.informed.package":{extensions:["ipk"]},"application/vnd.simtech-mindmapper":{extensions:["twd","twds"]},"application/vnd.smaf":{extensions:["mmf"]},"application/vnd.smart.teacher":{extensions:["teacher"]},"application/vnd.solent.sdkm+xml":{extensions:["sdkm","sdkd"]},"application/vnd.spotfire.dxp":{extensions:["dxp"]},"application/vnd.spotfire.sfs":{extensions:["sfs"]},"application/vnd.stardivision.calc":{extensions:["sdc"]},"application/vnd.stardivision.draw":{extensions:["sda"]},"application/vnd.stardivision.impress":{extensions:["sdd"]},"application/vnd.stardivision.math":{extensions:["smf"]},"application/vnd.stardivision.writer":{extensions:["sdw","vor"]},"application/vnd.stardivision.writer-global":{extensions:["sgl"]},"application/vnd.stepmania.package":{extensions:["smzip"]},"application/vnd.stepmania.stepchart":{extensions:["sm"]},"application/vnd.sun.xml.calc":{extensions:["sxc"]},"application/vnd.sun.xml.calc.template":{extensions:["stc"]},"application/vnd.sun.xml.draw":{extensions:["sxd"]},"application/vnd.sun.xml.draw.template":{extensions:["std"]},"application/vnd.sun.xml.impress":{extensions:["sxi"]},"application/vnd.sun.xml.impress.template":{extensions:["sti"]},"application/vnd.sun.xml.math":{extensions:["sxm"]},"application/vnd.sun.xml.writer":{extensions:["sxw"]},"application/vnd.sun.xml.writer.global":{extensions:["sxg"]},"application/vnd.sun.xml.writer.template":{extensions:["stw"]},"application/vnd.sus-calendar":{extensions:["sus","susp"]},"application/vnd.svd":{extensions:["svd"]},"application/vnd.symbian.install":{extensions:["sis","sisx"]},"application/vnd.syncml+xml":{extensions:["xsm"]},"application/vnd.syncml.dm+wbxml":{extensions:["bdm"]},"application/vnd.syncml.dm+xml":{extensions:["xdm"]},"application/vnd.tao.intent-module-archive":{extensions:["tao"]},"application/vnd.tcpdump.pcap":{extensions:["pcap","cap","dmp"]},"application/vnd.tmobile-livetv":{extensions:["tmo"]},"application/vnd.trid.tpt":{extensions:["tpt"]},"application/vnd.triscape.mxs":{extensions:["mxs"]},"application/vnd.trueapp":{extensions:["tra"]},"application/vnd.ufdl":{extensions:["ufd","ufdl"]},"application/vnd.uiq.theme":{extensions:["utz"]},"application/vnd.umajin":{extensions:["umj"]},"application/vnd.unity":{extensions:["unityweb"]},"application/vnd.uoml+xml":{extensions:["uoml"]},"application/vnd.vcx":{extensions:["vcx"]},"application/vnd.visio":{extensions:["vsd","vst","vss","vsw"]},"application/vnd.visionary":{extensions:["vis"]},"application/vnd.vsf":{extensions:["vsf"]},"application/vnd.wap.wbxml":{extensions:["wbxml"]},"application/vnd.wap.wmlc":{extensions:["wmlc"]},"application/vnd.wap.wmlscriptc":{extensions:["wmlsc"]},"application/vnd.webturbo":{extensions:["wtb"]},"application/vnd.wolfram.player":{extensions:["nbp"]},"application/vnd.wordperfect":{extensions:["wpd"]},"application/vnd.wqd":{extensions:["wqd"]},"application/vnd.wt.stf":{extensions:["stf"]},"application/vnd.xara":{extensions:["xar"]},"application/vnd.xfdl":{extensions:["xfdl"]},"application/vnd.yamaha.hv-dic":{extensions:["hvd"]},"application/vnd.yamaha.hv-script":{extensions:["hvs"]},"application/vnd.yamaha.hv-voice":{extensions:["hvp"]},"application/vnd.yamaha.openscoreformat":{extensions:["osf"]},"application/vnd.yamaha.openscoreformat.osfpvg+xml":{extensions:["osfpvg"]},"application/vnd.yamaha.smaf-audio":{extensions:["saf"]},"application/vnd.yamaha.smaf-phrase":{extensions:["spf"]},"application/vnd.yellowriver-custom-menu":{extensions:["cmp"]},"application/vnd.zul":{extensions:["zir","zirz"]},"application/vnd.zzazz.deck+xml":{extensions:["zaz"]},"application/voicexml+xml":{extensions:["vxml"]},"application/widget":{extensions:["wgt"]},"application/winhlp":{extensions:["hlp"]},"application/wsdl+xml":{extensions:["wsdl"]},"application/wspolicy+xml":{extensions:["wspolicy"]},"application/x-7z-compressed":{compressible:!1,extensions:["7z"]},"application/x-abiword":{extensions:["abw"]},"application/x-ace-compressed":{ extensions:["ace"]},"application/x-apple-diskimage":{extensions:["dmg"]},"application/x-authorware-bin":{extensions:["aab","x32","u32","vox"]},"application/x-authorware-map":{extensions:["aam"]},"application/x-authorware-seg":{extensions:["aas"]},"application/x-bcpio":{extensions:["bcpio"]},"application/x-bdoc":{compressible:!1,extensions:["bdoc"]},"application/x-bittorrent":{extensions:["torrent"]},"application/x-blorb":{extensions:["blb","blorb"]},"application/x-bzip":{compressible:!1,extensions:["bz"]},"application/x-bzip2":{compressible:!1,extensions:["bz2","boz"]},"application/x-cbr":{extensions:["cbr","cba","cbt","cbz","cb7"]},"application/x-cdlink":{extensions:["vcd"]},"application/x-cfs-compressed":{extensions:["cfs"]},"application/x-chat":{extensions:["chat"]},"application/x-chess-pgn":{extensions:["pgn"]},"application/x-chrome-extension":{extensions:["crx"]},"application/x-cocoa":{source:"nginx",extensions:["cco"]},"application/x-conference":{extensions:["nsc"]},"application/x-cpio":{extensions:["cpio"]},"application/x-csh":{extensions:["csh"]},"application/x-debian-package":{extensions:["deb","udeb"]},"application/x-dgc-compressed":{extensions:["dgc"]},"application/x-director":{extensions:["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"]},"application/x-doom":{extensions:["wad"]},"application/x-dtbncx+xml":{extensions:["ncx"]},"application/x-dtbook+xml":{extensions:["dtb"]},"application/x-dtbresource+xml":{extensions:["res"]},"application/x-dvi":{compressible:!1,extensions:["dvi"]},"application/x-envoy":{extensions:["evy"]},"application/x-eva":{extensions:["eva"]},"application/x-font-bdf":{extensions:["bdf"]},"application/x-font-ghostscript":{extensions:["gsf"]},"application/x-font-linux-psf":{extensions:["psf"]},"application/x-font-otf":{compressible:!0,extensions:["otf"]},"application/x-font-pcf":{extensions:["pcf"]},"application/x-font-snf":{extensions:["snf"]},"application/x-font-ttf":{compressible:!0,extensions:["ttf","ttc"]},"application/x-font-type1":{extensions:["pfa","pfb","pfm","afm"]},"application/x-freearc":{extensions:["arc"]},"application/x-futuresplash":{extensions:["spl"]},"application/x-gca-compressed":{extensions:["gca"]},"application/x-glulx":{extensions:["ulx"]},"application/x-gnumeric":{extensions:["gnumeric"]},"application/x-gramps-xml":{extensions:["gramps"]},"application/x-gtar":{extensions:["gtar"]},"application/x-hdf":{extensions:["hdf"]},"application/x-httpd-php":{compressible:!0,extensions:["php"]},"application/x-install-instructions":{extensions:["install"]},"application/x-iso9660-image":{extensions:["iso"]},"application/x-java-archive-diff":{source:"nginx",extensions:["jardiff"]},"application/x-java-jnlp-file":{compressible:!1,extensions:["jnlp"]},"application/x-latex":{compressible:!1,extensions:["latex"]},"application/x-lua-bytecode":{extensions:["luac"]},"application/x-lzh-compressed":{extensions:["lzh","lha"]},"application/x-makeself":{source:"nginx",extensions:["run"]},"application/x-mie":{extensions:["mie"]},"application/x-mobipocket-ebook":{extensions:["prc","mobi"]},"application/x-ms-application":{extensions:["application"]},"application/x-ms-shortcut":{extensions:["lnk"]},"application/x-ms-wmd":{extensions:["wmd"]},"application/x-ms-wmz":{extensions:["wmz"]},"application/x-ms-xbap":{extensions:["xbap"]},"application/x-msaccess":{extensions:["mdb"]},"application/x-msbinder":{extensions:["obd"]},"application/x-mscardfile":{extensions:["crd"]},"application/x-msclip":{extensions:["clp"]},"application/x-msdos-program":{extensions:["exe"]},"application/x-msdownload":{extensions:["exe","dll","com","bat","msi"]},"application/x-msmediaview":{extensions:["mvb","m13","m14"]},"application/x-msmetafile":{extensions:["wmf","wmz","emf","emz"]},"application/x-msmoney":{extensions:["mny"]},"application/x-mspublisher":{extensions:["pub"]},"application/x-msschedule":{extensions:["scd"]},"application/x-msterminal":{extensions:["trm"]},"application/x-mswrite":{extensions:["wri"]},"application/x-netcdf":{extensions:["nc","cdf"]},"application/x-ns-proxy-autoconfig":{compressible:!0,extensions:["pac"]},"application/x-nzb":{extensions:["nzb"]},"application/x-perl":{source:"nginx",extensions:["pl","pm"]},"application/x-pilot":{source:"nginx",extensions:["prc","pdb"]},"application/x-pkcs12":{compressible:!1,extensions:["p12","pfx"]},"application/x-pkcs7-certificates":{extensions:["p7b","spc"]},"application/x-pkcs7-certreqresp":{extensions:["p7r"]},"application/x-rar-compressed":{compressible:!1,extensions:["rar"]},"application/x-redhat-package-manager":{source:"nginx",extensions:["rpm"]},"application/x-research-info-systems":{extensions:["ris"]},"application/x-sea":{source:"nginx",extensions:["sea"]},"application/x-sh":{compressible:!0,extensions:["sh"]},"application/x-shar":{extensions:["shar"]},"application/x-shockwave-flash":{compressible:!1,extensions:["swf"]},"application/x-silverlight-app":{extensions:["xap"]},"application/x-sql":{extensions:["sql"]},"application/x-stuffit":{compressible:!1,extensions:["sit"]},"application/x-stuffitx":{extensions:["sitx"]},"application/x-subrip":{extensions:["srt"]},"application/x-sv4cpio":{extensions:["sv4cpio"]},"application/x-sv4crc":{extensions:["sv4crc"]},"application/x-t3vm-image":{extensions:["t3"]},"application/x-tads":{extensions:["gam"]},"application/x-tar":{compressible:!0,extensions:["tar"]},"application/x-tcl":{extensions:["tcl","tk"]},"application/x-tex":{extensions:["tex"]},"application/x-tex-tfm":{extensions:["tfm"]},"application/x-texinfo":{extensions:["texinfo","texi"]},"application/x-tgif":{extensions:["obj"]},"application/x-ustar":{extensions:["ustar"]},"application/x-wais-source":{extensions:["src"]},"application/x-web-app-manifest+json":{compressible:!0,extensions:["webapp"]},"application/x-x509-ca-cert":{extensions:["der","crt","pem"]},"application/x-xfig":{extensions:["fig"]},"application/x-xliff+xml":{extensions:["xlf"]},"application/x-xpinstall":{compressible:!1,extensions:["xpi"]},"application/x-xz":{extensions:["xz"]},"application/x-zmachine":{extensions:["z1","z2","z3","z4","z5","z6","z7","z8"]},"application/xaml+xml":{extensions:["xaml"]},"application/xcap-diff+xml":{extensions:["xdf"]},"application/xenc+xml":{extensions:["xenc"]},"application/xhtml+xml":{compressible:!0,extensions:["xhtml","xht"]},"application/xml":{compressible:!0,extensions:["xml","xsl","xsd","rng"]},"application/xml-dtd":{compressible:!0,extensions:["dtd"]},"application/xop+xml":{compressible:!0,extensions:["xop"]},"application/xproc+xml":{extensions:["xpl"]},"application/xslt+xml":{extensions:["xslt"]},"application/xspf+xml":{extensions:["xspf"]},"application/xv+xml":{extensions:["mxml","xhvml","xvml","xvm"]},"application/yang":{extensions:["yang"]},"application/yin+xml":{extensions:["yin"]},"application/zip":{compressible:!1,extensions:["zip"]},"audio/3gpp":{compressible:!1,extensions:["3gpp"]},"audio/adpcm":{extensions:["adp"]},"audio/basic":{compressible:!1,extensions:["au","snd"]},"audio/midi":{extensions:["mid","midi","kar","rmi"]},"audio/mp4":{compressible:!1,extensions:["m4a","mp4a"]},"audio/mpeg":{compressible:!1,extensions:["mpga","mp2","mp2a","mp3","m2a","m3a"]},"audio/ogg":{compressible:!1,extensions:["oga","ogg","spx"]},"audio/s3m":{extensions:["s3m"]},"audio/silk":{extensions:["sil"]},"audio/vnd.dece.audio":{extensions:["uva","uvva"]},"audio/vnd.digital-winds":{extensions:["eol"]},"audio/vnd.dra":{extensions:["dra"]},"audio/vnd.dts":{extensions:["dts"]},"audio/vnd.dts.hd":{extensions:["dtshd"]},"audio/vnd.lucent.voice":{extensions:["lvp"]},"audio/vnd.ms-playready.media.pya":{extensions:["pya"]},"audio/vnd.nuera.ecelp4800":{extensions:["ecelp4800"]},"audio/vnd.nuera.ecelp7470":{extensions:["ecelp7470"]},"audio/vnd.nuera.ecelp9600":{extensions:["ecelp9600"]},"audio/vnd.rip":{extensions:["rip"]},"audio/wav":{compressible:!1,extensions:["wav"]},"audio/wave":{compressible:!1,extensions:["wav"]},"audio/webm":{compressible:!1,extensions:["weba"]},"audio/x-aac":{compressible:!1,extensions:["aac"]},"audio/x-aiff":{extensions:["aif","aiff","aifc"]},"audio/x-caf":{compressible:!1,extensions:["caf"]},"audio/x-flac":{extensions:["flac"]},"audio/x-m4a":{source:"nginx",extensions:["m4a"]},"audio/x-matroska":{extensions:["mka"]},"audio/x-mpegurl":{extensions:["m3u"]},"audio/x-ms-wax":{extensions:["wax"]},"audio/x-ms-wma":{extensions:["wma"]},"audio/x-pn-realaudio":{extensions:["ram","ra"]},"audio/x-pn-realaudio-plugin":{extensions:["rmp"]},"audio/x-realaudio":{source:"nginx",extensions:["ra"]},"audio/x-wav":{extensions:["wav"]},"audio/xm":{extensions:["xm"]},"chemical/x-cdx":{extensions:["cdx"]},"chemical/x-cif":{extensions:["cif"]},"chemical/x-cmdf":{extensions:["cmdf"]},"chemical/x-cml":{extensions:["cml"]},"chemical/x-csml":{extensions:["csml"]},"chemical/x-xyz":{extensions:["xyz"]},"font/opentype":{compressible:!0,extensions:["otf"]},"image/bmp":{compressible:!0,extensions:["bmp"]},"image/cgm":{extensions:["cgm"]},"image/g3fax":{extensions:["g3"]},"image/gif":{compressible:!1,extensions:["gif"]},"image/ief":{extensions:["ief"]},"image/jpeg":{compressible:!1,extensions:["jpeg","jpg","jpe"]},"image/ktx":{extensions:["ktx"]},"image/png":{compressible:!1,extensions:["png"]},"image/prs.btif":{extensions:["btif"]},"image/sgi":{extensions:["sgi"]},"image/svg+xml":{compressible:!0,extensions:["svg","svgz"]},"image/tiff":{compressible:!1,extensions:["tiff","tif"]},"image/vnd.adobe.photoshop":{compressible:!0,extensions:["psd"]},"image/vnd.dece.graphic":{extensions:["uvi","uvvi","uvg","uvvg"]},"image/vnd.djvu":{extensions:["djvu","djv"]},"image/vnd.dvb.subtitle":{extensions:["sub"]},"image/vnd.dwg":{extensions:["dwg"]},"image/vnd.dxf":{extensions:["dxf"]},"image/vnd.fastbidsheet":{extensions:["fbs"]},"image/vnd.fpx":{extensions:["fpx"]},"image/vnd.fst":{extensions:["fst"]},"image/vnd.fujixerox.edmics-mmr":{extensions:["mmr"]},"image/vnd.fujixerox.edmics-rlc":{extensions:["rlc"]},"image/vnd.ms-modi":{extensions:["mdi"]},"image/vnd.ms-photo":{extensions:["wdp"]},"image/vnd.net-fpx":{extensions:["npx"]},"image/vnd.wap.wbmp":{extensions:["wbmp"]},"image/vnd.xiff":{extensions:["xif"]},"image/webp":{extensions:["webp"]},"image/x-3ds":{extensions:["3ds"]},"image/x-cmu-raster":{extensions:["ras"]},"image/x-cmx":{extensions:["cmx"]},"image/x-freehand":{extensions:["fh","fhc","fh4","fh5","fh7"]},"image/x-icon":{compressible:!0,extensions:["ico"]},"image/x-jng":{source:"nginx",extensions:["jng"]},"image/x-mrsid-image":{extensions:["sid"]},"image/x-ms-bmp":{source:"nginx",compressible:!0,extensions:["bmp"]},"image/x-pcx":{extensions:["pcx"]},"image/x-pict":{extensions:["pic","pct"]},"image/x-portable-anymap":{extensions:["pnm"]},"image/x-portable-bitmap":{extensions:["pbm"]},"image/x-portable-graymap":{extensions:["pgm"]},"image/x-portable-pixmap":{extensions:["ppm"]},"image/x-rgb":{extensions:["rgb"]},"image/x-tga":{extensions:["tga"]},"image/x-xbitmap":{extensions:["xbm"]},"image/x-xpixmap":{extensions:["xpm"]},"image/x-xwindowdump":{extensions:["xwd"]},"message/rfc822":{compressible:!0,extensions:["eml","mime"]},"model/iges":{compressible:!1,extensions:["igs","iges"]},"model/mesh":{compressible:!1,extensions:["msh","mesh","silo"]},"model/vnd.collada+xml":{extensions:["dae"]},"model/vnd.dwf":{extensions:["dwf"]},"model/vnd.gdl":{extensions:["gdl"]},"model/vnd.gtw":{extensions:["gtw"]},"model/vnd.mts":{extensions:["mts"]},"model/vnd.vtu":{extensions:["vtu"]},"model/vrml":{compressible:!1,extensions:["wrl","vrml"]},"model/x3d+binary":{compressible:!1,extensions:["x3db","x3dbz"]},"model/x3d+vrml":{compressible:!1,extensions:["x3dv","x3dvz"]},"model/x3d+xml":{compressible:!0,extensions:["x3d","x3dz"]},"text/cache-manifest":{compressible:!0,extensions:["appcache","manifest"]},"text/calendar":{extensions:["ics","ifb"]},"text/coffeescript":{extensions:["coffee","litcoffee"]},"text/css":{compressible:!0,extensions:["css"]},"text/csv":{compressible:!0,extensions:["csv"]},"text/hjson":{extensions:["hjson"]},"text/html":{compressible:!0,extensions:["html","htm","shtml"]},"text/jade":{extensions:["jade"]},"text/jsx":{compressible:!0,extensions:["jsx"]},"text/less":{extensions:["less"]},"text/mathml":{source:"nginx",extensions:["mml"]},"text/n3":{compressible:!0,extensions:["n3"]},"text/plain":{compressible:!0,extensions:["txt","text","conf","def","list","log","in","ini"]},"text/prs.lines.tag":{extensions:["dsc"]},"text/richtext":{compressible:!0,extensions:["rtx"]},"text/rtf":{compressible:!0,extensions:["rtf"]},"text/sgml":{extensions:["sgml","sgm"]},"text/slim":{extensions:["slim","slm"]},"text/stylus":{extensions:["stylus","styl"]},"text/tab-separated-values":{compressible:!0,extensions:["tsv"]},"text/troff":{extensions:["t","tr","roff","man","me","ms"]},"text/turtle":{extensions:["ttl"]},"text/uri-list":{compressible:!0,extensions:["uri","uris","urls"]},"text/vcard":{compressible:!0,extensions:["vcard"]},"text/vnd.curl":{extensions:["curl"]},"text/vnd.curl.dcurl":{extensions:["dcurl"]},"text/vnd.curl.mcurl":{extensions:["mcurl"]},"text/vnd.curl.scurl":{extensions:["scurl"]},"text/vnd.dvb.subtitle":{extensions:["sub"]},"text/vnd.fly":{extensions:["fly"]},"text/vnd.fmi.flexstor":{extensions:["flx"]},"text/vnd.graphviz":{extensions:["gv"]},"text/vnd.in3d.3dml":{extensions:["3dml"]},"text/vnd.in3d.spot":{extensions:["spot"]},"text/vnd.sun.j2me.app-descriptor":{extensions:["jad"]},"text/vnd.wap.wml":{extensions:["wml"]},"text/vnd.wap.wmlscript":{extensions:["wmls"]},"text/vtt":{charset:"UTF-8",compressible:!0,extensions:["vtt"]},"text/x-asm":{extensions:["s","asm"]},"text/x-c":{extensions:["c","cc","cxx","cpp","h","hh","dic"]},"text/x-component":{source:"nginx",extensions:["htc"]},"text/x-fortran":{extensions:["f","for","f77","f90"]},"text/x-handlebars-template":{extensions:["hbs"]},"text/x-java-source":{extensions:["java"]},"text/x-lua":{extensions:["lua"]},"text/x-markdown":{compressible:!0,extensions:["markdown","md","mkd"]},"text/x-nfo":{extensions:["nfo"]},"text/x-opml":{extensions:["opml"]},"text/x-pascal":{extensions:["p","pas"]},"text/x-processing":{compressible:!0,extensions:["pde"]},"text/x-sass":{extensions:["sass"]},"text/x-scss":{extensions:["scss"]},"text/x-setext":{extensions:["etx"]},"text/x-sfv":{extensions:["sfv"]},"text/x-suse-ymp":{compressible:!0,extensions:["ymp"]},"text/x-uuencode":{extensions:["uu"]},"text/x-vcalendar":{extensions:["vcs"]},"text/x-vcard":{extensions:["vcf"]},"text/xml":{source:"iana",compressible:!0,extensions:["xml"]},"text/yaml":{extensions:["yaml","yml"]},"video/3gpp":{extensions:["3gp","3gpp"]},"video/3gpp2":{extensions:["3g2"]},"video/h261":{extensions:["h261"]},"video/h263":{extensions:["h263"]},"video/h264":{extensions:["h264"]},"video/jpeg":{extensions:["jpgv"]},"video/jpm":{extensions:["jpm","jpgm"]},"video/mj2":{extensions:["mj2","mjp2"]},"video/mp2t":{extensions:["ts"]},"video/mp4":{compressible:!1,extensions:["mp4","mp4v","mpg4"]},"video/mpeg":{compressible:!1,extensions:["mpeg","mpg","mpe","m1v","m2v"]},"video/ogg":{compressible:!1,extensions:["ogv"]},"video/quicktime":{compressible:!1,extensions:["qt","mov"]},"video/vnd.dece.hd":{extensions:["uvh","uvvh"]},"video/vnd.dece.mobile":{extensions:["uvm","uvvm"]},"video/vnd.dece.pd":{extensions:["uvp","uvvp"]},"video/vnd.dece.sd":{extensions:["uvs","uvvs"]},"video/vnd.dece.video":{extensions:["uvv","uvvv"]},"video/vnd.dvb.file":{extensions:["dvb"]},"video/vnd.fvt":{extensions:["fvt"]},"video/vnd.mpegurl":{extensions:["mxu","m4u"]},"video/vnd.ms-playready.media.pyv":{extensions:["pyv"]},"video/vnd.uvvu.mp4":{extensions:["uvu","uvvu"]},"video/vnd.vivo":{extensions:["viv"]},"video/webm":{compressible:!1,extensions:["webm"]},"video/x-f4v":{extensions:["f4v"]},"video/x-fli":{extensions:["fli"]},"video/x-flv":{compressible:!1,extensions:["flv"]},"video/x-m4v":{extensions:["m4v"]},"video/x-matroska":{compressible:!1,extensions:["mkv","mk3d","mks"]},"video/x-mng":{extensions:["mng"]},"video/x-ms-asf":{extensions:["asf","asx"]},"video/x-ms-vob":{extensions:["vob"]},"video/x-ms-wm":{extensions:["wm"]},"video/x-ms-wmv":{compressible:!1,extensions:["wmv"]},"video/x-ms-wmx":{extensions:["wmx"]},"video/x-ms-wvx":{extensions:["wvx"]},"video/x-msvideo":{extensions:["avi"]},"video/x-sgi-movie":{extensions:["movie"]},"video/x-smv":{extensions:["smv"]},"x-conference/x-cooltalk":{extensions:["ice"]}}},mime_lookup:{value:function(e){if(!e)return"application/octet-stream";e=e.toLowerCase();for(var t in this.mime_db)if(this.mime_db[t].extensions&&this.mime_db[t].extensions.indexOf(e)!=-1)return t;return"application/octet-stream"}}}),$p}); \ No newline at end of file diff --git a/package.json b/package.json index c8625bd6c..67ec462af 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "metadata-js", "description": "Library for building offline-first browser-based business applications", - "version": "0.11.223", + "version": "0.12.225", "author": "Evgeniy Malyarov <info@oknosoft.ru> (http://www.oknosoft.ru)", "directories": { "example": "examples", diff --git a/packages/metadata-core/src/common.js b/packages/metadata-core/src/common.js index 0df1852c4..af844e9ed 100644 --- a/packages/metadata-core/src/common.js +++ b/packages/metadata-core/src/common.js @@ -112,8 +112,8 @@ export default class MetaEngine{ * @param err */ record_log(err) { - if(this.ireg && this.ireg.$log){ - this.ireg.$log.record(err) + if(this.ireg && this.ireg.log){ + this.ireg.log.record(err) } console.log(err) } diff --git a/packages/metadata-core/src/meta.js b/packages/metadata-core/src/meta.js index ccbe7c0ba..cd90435a4 100644 --- a/packages/metadata-core/src/meta.js +++ b/packages/metadata-core/src/meta.js @@ -41,7 +41,7 @@ class Meta extends MetaEventEmitter{ super(); - var _m; + let _m = Object.assign({}, meta_sys); /** * ### Инициализирует метаданные @@ -52,31 +52,7 @@ class Meta extends MetaEventEmitter{ * @param [meta_db] {Object|String} */ this.init = function (meta_db) { - - var confirm_count = 0; - - _m = meta_db; - meta_db = null; - - - // следим за изменениями базы meta и предлагаем перезагрузку при обновлении версии - // TODO: назначить обработчик - // $p.adapters.pouch.local.sync.meta.on("change", function (change) { - // if(!_m) - // do_init(); - // - // else{ - // // если изменились метаданные, запланировать перезагрузку - // do_reload(); - // setTimeout(function () { - // $p.eve.redirect = true; - // location.reload(true); - // }, 1000); - // } - // }); - - return _m; - + return utils._patch(_m, meta_db); }; /** diff --git a/packages/metadata-core/src/meta_sys.js b/packages/metadata-core/src/meta_sys.js new file mode 100644 index 000000000..aaa1ceb27 --- /dev/null +++ b/packages/metadata-core/src/meta_sys.js @@ -0,0 +1,420 @@ +/** + * Метаданные системных перечислений, регистров и справочников + * + * @module metadata + * @submodule sys_types + * + * Created 28.11.2016 + */ + +const meta_sys = { + _id: "meta_sys", + enm: { + accumulation_record_type: [ + { + order: 0, + name: "debit", + synonym: "Приход" + }, + { + order: 1, + name: "credit", + synonym: "Расход" + } + ], + comparison_types: [ + { + order: 0, + name: "gt", + synonym: "Больше" + }, + { + order: 1, + name: "gte", + synonym: "Больше или равно" + }, + { + order: 2, + name: "lt", + synonym: "Меньше" + }, + { + order: 3, + name: "lte", + synonym: "Меньше или равно " + }, + { + order: 4, + name: "eq", + synonym: "Равно" + }, + { + order: 5, + name: "ne", + synonym: "Не равно" + }, + { + "order": 6, + "name": "in", + "synonym": "В списке" + }, + { + order: 7, + name: "nin", + synonym: "Не в списке" + }, + { + order: 8, + name: "lke", + synonym: "Подобно " + }, + { + order: 9, + name: "nlk", + synonym: "Не подобно" + } + ] + }, + cat: { + meta_objs: {}, + meta_fields: {}, + scheme_settings: { + name: "scheme_settings", + splitted: true, + synonym: "Настройки отчетов и списков", + illustration: "", + obj_presentation: "", + list_presentation: "", + input_by_string: [ + "name" + ], + hierarchical: false, + has_owners: false, + group_hierarchy: true, + main_presentation_name: true, + code_length: 0, + fields: { + obj: { + "synonym": "Объект", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 250 + } + }, + user: { + "synonym": "Пользователь", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 50 + } + }, + predefined_name: { + "synonym": "", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 256 + } + } + }, + tabular_sections: { + available_fields: { + "name": "available_fields", + "synonym": "Доступные поля", + "tooltip": "Состав, порядок и ширина колонок", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "Для плоского списка, родитель пустой", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "use": { + "synonym": "Использование", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "boolean" + ] + } + }, + "field": { + "synonym": "Поле", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "width": { + "synonym": "Ширина", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "number" + ], + "digits": 6, + "fraction_figits": 0 + } + }, + "caption": { + "synonym": "Заголовок", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + sort_fields: { + "name": "sort_fields", + "synonym": "Поля сортировки", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "field": { + "synonym": "Поле", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + grouping_fields: { + "name": "grouping_fields", + "synonym": "Поля группировки", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "field": { + "synonym": "Поле", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + selection: { + "name": "selection", + "synonym": "Отбор", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "use": { + "synonym": "Использование", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "boolean" + ] + } + }, + "left_value": { + "synonym": "Левое значение", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "comparison_type": { + "synonym": "Вид сравнения", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "right_value": { + "synonym": "Правое значение", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + scheme: { + "name": "scheme", + "synonym": "Структура", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 10 + } + }, + "kind": { + "synonym": "Вид раздела отчета", + "multiline_mode": false, + "tooltip": "список, таблица, группировка строк, группировка колонок", + "type": { + "types": [ + "string" + ], + "str_len": 10 + } + } + } + } + }, + cachable: "doc" + } + }, + doc: {}, + ireg: { + "log": { + name: "log", + note: "", + synonym: "Журнал событий", + dimensions: { + date: { + synonym: "Дата", + multiline_mode: false, + tooltip: "Время события", + type: { + types: [ + "number" + ], + digits: 15, + fraction_figits: 0 + } + }, + sequence: { + synonym: "Порядок", + multiline_mode: false, + tooltip: "Порядок следования", + type: { + types: [ + "number" + ], + digits: 6, + fraction_figits: 0 + } + } + }, + resources: { + "class": { + synonym: "Класс", + multiline_mode: false, + tooltip: "Класс события", + type: { + types: [ + "string" + ], + str_len: 100 + } + }, + note: { + synonym: "Комментарий", + multiline_mode: true, + tooltip: "Текст события", + type: { + types: [ + "string" + ], + str_len: 0 + } + }, + obj: { + synonym: "Объект", + multiline_mode: true, + tooltip: "Объект, к которому относится событие", + type: { + types: [ + "string" + ], + str_len: 0 + } + } + } + } + }, + areg: {}, + dp: {}, + rep: {}, + cch: {}, + cacc: {} +} \ No newline at end of file diff --git a/packages/metadata-core/src/mngrs.js b/packages/metadata-core/src/mngrs.js index d4bce6e32..e7cb43f23 100644 --- a/packages/metadata-core/src/mngrs.js +++ b/packages/metadata-core/src/mngrs.js @@ -2451,76 +2451,7 @@ function mngrs($p) { class LogManager extends InfoRegManager{ constructor() { - super("ireg.$log"); - } - - metadata(){ - return { - name: "$log", - note: "", - synonym: "Журнал событий", - dimensions: { - date: { - synonym: "Дата", - multiline_mode: false, - tooltip: "Время события", - type: { - types: [ - "number" - ], - digits: 15, - fraction_figits: 0 - } - }, - sequence: { - synonym: "Порядок", - multiline_mode: false, - tooltip: "Порядок следования", - type: { - types: [ - "number" - ], - digits: 6, - fraction_figits: 0 - } - } - }, - resources: { - "class": { - synonym: "Класс", - multiline_mode: false, - tooltip: "Класс события", - type: { - types: [ - "string" - ], - str_len: 100 - } - }, - note: { - synonym: "Комментарий", - multiline_mode: true, - tooltip: "Текст события", - type: { - types: [ - "string" - ], - str_len: 0 - } - }, - obj: { - synonym: "Объект", - multiline_mode: true, - tooltip: "Объект, к которому относится событие", - type: { - types: [ - "string" - ], - str_len: 0 - } - } - } - } + super("ireg.log"); } /** @@ -2550,7 +2481,7 @@ function mngrs($p) { // уникальность ключа if(!this.smax) - this.smax = alasql.compile("select MAX(`sequence`) as `sequence` from `ireg_$log` where `date` = ?"); + this.smax = alasql.compile("select MAX(`sequence`) as `sequence` from `ireg_log` where `date` = ?"); var res = this.smax([msg.date]); if(!res.length || res[0].sequence === undefined) msg.sequence = 0; @@ -2561,7 +2492,7 @@ function mngrs($p) { if(!msg.class) msg.class = "note"; - wsql.alasql("insert into `ireg_$log` (`ref`, `date`, `sequence`, `class`, `note`, `obj`) values (?,?,?,?,?,?)", + wsql.alasql("insert into `ireg_log` (`ref`, `date`, `sequence`, `class`, `note`, `obj`) values (?,?,?,?,?,?)", [msg.date + "¶" + msg.sequence, msg.date, msg.sequence, msg.class, msg.note, msg.obj ? JSON.stringify(msg.obj) : ""]); } @@ -2611,7 +2542,7 @@ function mngrs($p) { return undefined; var parts = ref.split("¶"); - wsql.alasql("select * from `ireg_$log` where date=" + parts[0] + " and sequence=" + parts[1]) + wsql.alasql("select * from `ireg_log` where date=" + parts[0] + " and sequence=" + parts[1]) .forEach(row => new RegisterRow(row, this)); } @@ -2621,7 +2552,7 @@ function mngrs($p) { get_sql_struct(attr){ if(attr && attr.action == "get_selection"){ - var sql = "select * from `ireg_$log`"; + var sql = "select * from `ireg_log`"; if(attr.date_from){ if (attr.date_till) sql += " where `date` >= ? and `date` <= ?"; @@ -2680,9 +2611,6 @@ function mngrs($p) { */ class MetaObjManager extends CatManager{ - metadata(){ - return {} - } } /** @@ -2690,18 +2618,14 @@ function mngrs($p) { * Используется при настройке отчетов и динамических списков */ class MetaFieldManager extends CatManager{ - metadata(){ - return {} - } + } /** * ### Менеджер настроек отчетов и динсписков */ class SchemeSettingsManager extends CatManager{ - metadata(){ - return {} - } + } @@ -2808,18 +2732,18 @@ function mngrs($p) { }); // создаём системные менеджеры (журнал регистрации, метаданные и настройки компоновки) - Object.defineProperty($p.ireg, '$log', { - value: new LogManager('ireg.$log') + Object.defineProperty($p.ireg, 'log', { + value: new LogManager('ireg.log') }) Object.defineProperties($p.cat, { - $meta: { - value: new MetaObjManager('cat.$meta') + meta_objs: { + value: new MetaObjManager('cat.meta_objs') }, - $fld: { - value: new MetaFieldManager('cat.$fld') + meta_fields: { + value: new MetaFieldManager('cat.meta_fields') }, - $scheme: { - value: new SchemeSettingsManager('cat.$scheme') + scheme_settings: { + value: new SchemeSettingsManager('cat.scheme_settings') } }) diff --git a/packages/metadata-core/src/sys_types.js b/packages/metadata-core/src/sys_types.js deleted file mode 100644 index fd7e180c7..000000000 --- a/packages/metadata-core/src/sys_types.js +++ /dev/null @@ -1,273 +0,0 @@ -/** - * Метаданные системных перечислений, регистров и справочников - * - * @module metadata - * @submodule sys_types - * - * Created 28.11.2016 - */ - -const $scheme = { - name: "$scheme", - splitted: true, - synonym: "Настройки отчетов и списков", - illustration: "", - obj_presentation: "", - list_presentation: "", - input_by_string: [ - "name" - ], - hierarchical: false, - has_owners: false, - group_hierarchy: true, - main_presentation_name: true, - code_length: 0, - fields: { - obj: { - "synonym": "Объект", - "multiline_mode": false, - "tooltip": "", - "type": { - "types": [ - "string" - ], - "str_len": 250 - } - }, - user: { - "synonym": "Пользователь", - "multiline_mode": false, - "tooltip": "", - "type": { - "types": [ - "string" - ], - "str_len": 50 - } - }, - predefined_name: { - "synonym": "", - "multiline_mode": false, - "tooltip": "", - "type": { - "types": [ - "string" - ], - "str_len": 256 - } - } - }, - tabular_sections: { - available_fields: { - "name": "available_fields", - "synonym": "Доступные поля", - "tooltip": "Состав, порядок и ширина колонок", - "fields": { - "parent": { - "synonym": "Родитель", - "multiline_mode": false, - "tooltip": "Для плоского списка, родитель пустой", - "type": { - "types": [ - "string" - ], - "str_len": 100 - } - }, - "use": { - "synonym": "Использование", - "multiline_mode": false, - "tooltip": "", - "type": { - "types": [ - "boolean" - ] - } - }, - "field": { - "synonym": "Поле", - "multiline_mode": false, - "tooltip": "", - "type": { - "types": [ - "string" - ], - "str_len": 100 - } - }, - "width": { - "synonym": "Ширина", - "multiline_mode": false, - "tooltip": "", - "type": { - "types": [ - "number" - ], - "digits": 6, - "fraction_figits": 0 - } - }, - "caption": { - "synonym": "Заголовок", - "multiline_mode": false, - "tooltip": "", - "type": { - "types": [ - "string" - ], - "str_len": 100 - } - } - } - }, - sort_fields: { - "name": "sort_fields", - "synonym": "Поля сортировки", - "tooltip": "", - "fields": { - "parent": { - "synonym": "Родитель", - "multiline_mode": false, - "tooltip": "", - "type": { - "types": [ - "string" - ], - "str_len": 100 - } - }, - "field": { - "synonym": "Поле", - "multiline_mode": false, - "tooltip": "", - "type": { - "types": [ - "string" - ], - "str_len": 100 - } - } - } - }, - grouping_fields: { - "name": "grouping_fields", - "synonym": "Поля группировки", - "tooltip": "", - "fields": { - "parent": { - "synonym": "Родитель", - "multiline_mode": false, - "tooltip": "", - "type": { - "types": [ - "string" - ], - "str_len": 100 - } - }, - "field": { - "synonym": "Поле", - "multiline_mode": false, - "tooltip": "", - "type": { - "types": [ - "string" - ], - "str_len": 100 - } - } - } - }, - selection: { - "name": "selection", - "synonym": "Отбор", - "tooltip": "", - "fields": { - "parent": { - "synonym": "Родитель", - "multiline_mode": false, - "tooltip": "", - "type": { - "types": [ - "string" - ], - "str_len": 100 - } - }, - "use": { - "synonym": "Использование", - "multiline_mode": false, - "tooltip": "", - "type": { - "types": [ - "boolean" - ] - } - }, - "left_value": { - "synonym": "Левое значение", - "multiline_mode": false, - "tooltip": "", - "type": { - "types": [ - "string" - ], - "str_len": 100 - } - }, - "comparison_type": { - "synonym": "Вид сравнения", - "multiline_mode": false, - "tooltip": "", - "type": { - "types": [ - "string" - ], - "str_len": 100 - } - }, - "right_value": { - "synonym": "Правое значение", - "multiline_mode": false, - "tooltip": "", - "type": { - "types": [ - "string" - ], - "str_len": 100 - } - } - } - }, - scheme: { - "name": "scheme", - "synonym": "Структура", - "tooltip": "", - "fields": { - "parent": { - "synonym": "Родитель", - "multiline_mode": false, - "tooltip": "", - "type": { - "types": [ - "string" - ], - "str_len": 10 - } - }, - "kind": { - "synonym": "Вид раздела отчета", - "multiline_mode": false, - "tooltip": "список, таблица, группировка строк, группировка колонок", - "type": { - "types": [ - "string" - ], - "str_len": 10 - } - } - } - } - }, - cachable: "doc" -} \ No newline at end of file diff --git a/src/common.js b/src/common.js index 88a816a81..da7b467a5 100644 --- a/src/common.js +++ b/src/common.js @@ -640,8 +640,8 @@ function MetaEngine() { */ record_log: { value: function (err) { - if($p.ireg && $p.ireg.$log) - $p.ireg.$log.record(err); + if($p.ireg && $p.ireg.log) + $p.ireg.log.record(err); console.log(err); } }, @@ -941,6 +941,18 @@ function MetaEngine() { value: LogManager }, + MetaObjManager: { + value: MetaObjManager + }, + + MetaFieldManager: { + value: MetaFieldManager + }, + + SchemeSettingsManager: { + value: SchemeSettingsManager + }, + AccumRegManager: { value: AccumRegManager }, @@ -1010,6 +1022,7 @@ function MetaEngine() { } }); + } /** @@ -1353,16 +1366,16 @@ function Ajax() { if(typeof auth == "object" && auth.username && auth.hasOwnProperty("password")){ username = auth.username; password = auth.password; - + }else{ if($p.ajax.username && $p.ajax.authorized){ username = $p.ajax.username; password = $p.aes.Ctr.decrypt($p.ajax.password); - + }else{ username = $p.wsql.get_user_param("user_name"); password = $p.aes.Ctr.decrypt($p.wsql.get_user_param("user_pwd")); - + if(!username && $p.job_prm && $p.job_prm.guest_name){ username = $p.job_prm.guest_name; password = $p.aes.Ctr.decrypt($p.job_prm.guest_pwd); diff --git a/src/common.ui.js b/src/common.ui.js index 2b4312e3f..9d7d2f616 100644 --- a/src/common.ui.js +++ b/src/common.ui.js @@ -723,7 +723,7 @@ $p.__define({ get_acl: { value: function(class_name) { var acn = class_name.split("."); - return this._acl && this._acl[acn[0]] ? this._acl[acn[0]][acn[1]] : "e"; + return this._acl && this._acl[acn[0]] && this._acl[acn[0]][acn[1]] ? this._acl[acn[0]][acn[1]] : "e"; } } diff --git a/src/meta_meta.js b/src/meta_meta.js index 1d12e2dd3..5d8f4c633 100644 --- a/src/meta_meta.js +++ b/src/meta_meta.js @@ -22,11 +22,419 @@ */ function Meta() { - var _m; + var _m = { + enm: { + accumulation_record_type: [ + { + order: 0, + name: "debit", + synonym: "Приход" + }, + { + order: 1, + name: "credit", + synonym: "Расход" + } + ], + comparison_types: [ + { + order: 0, + name: "gt", + synonym: "Больше" + }, + { + order: 1, + name: "gte", + synonym: "Больше или равно" + }, + { + order: 2, + name: "lt", + synonym: "Меньше" + }, + { + order: 3, + name: "lte", + synonym: "Меньше или равно " + }, + { + order: 4, + name: "eq", + synonym: "Равно" + }, + { + order: 5, + name: "ne", + synonym: "Не равно" + }, + { + "order": 6, + "name": "in", + "synonym": "В списке" + }, + { + order: 7, + name: "nin", + synonym: "Не в списке" + }, + { + order: 8, + name: "lke", + synonym: "Подобно " + }, + { + order: 9, + name: "nlk", + synonym: "Не подобно" + } + ] + }, + cat: { + meta_objs: {}, + meta_fields: {}, + scheme_settings: { + name: "scheme_settings", + splitted: true, + synonym: "Настройки отчетов и списков", + illustration: "", + obj_presentation: "", + list_presentation: "", + input_by_string: [ + "name" + ], + hierarchical: false, + has_owners: false, + group_hierarchy: true, + main_presentation_name: true, + code_length: 0, + fields: { + obj: { + "synonym": "Объект", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 250 + } + }, + user: { + "synonym": "Пользователь", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 50 + } + }, + predefined_name: { + "synonym": "", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 256 + } + } + }, + tabular_sections: { + available_fields: { + "name": "available_fields", + "synonym": "Доступные поля", + "tooltip": "Состав, порядок и ширина колонок", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "Для плоского списка, родитель пустой", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "use": { + "synonym": "Использование", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "boolean" + ] + } + }, + "field": { + "synonym": "Поле", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "width": { + "synonym": "Ширина", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "number" + ], + "digits": 6, + "fraction_figits": 0 + } + }, + "caption": { + "synonym": "Заголовок", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + sort_fields: { + "name": "sort_fields", + "synonym": "Поля сортировки", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "field": { + "synonym": "Поле", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + grouping_fields: { + "name": "grouping_fields", + "synonym": "Поля группировки", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "field": { + "synonym": "Поле", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + selection: { + "name": "selection", + "synonym": "Отбор", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "use": { + "synonym": "Использование", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "boolean" + ] + } + }, + "left_value": { + "synonym": "Левое значение", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "comparison_type": { + "synonym": "Вид сравнения", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + }, + "right_value": { + "synonym": "Правое значение", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 100 + } + } + } + }, + scheme: { + "name": "scheme", + "synonym": "Структура", + "tooltip": "", + "fields": { + "parent": { + "synonym": "Родитель", + "multiline_mode": false, + "tooltip": "", + "type": { + "types": [ + "string" + ], + "str_len": 10 + } + }, + "kind": { + "synonym": "Вид раздела отчета", + "multiline_mode": false, + "tooltip": "список, таблица, группировка строк, группировка колонок", + "type": { + "types": [ + "string" + ], + "str_len": 10 + } + } + } + } + }, + cachable: "doc" + } + }, + doc: {}, + ireg: { + "log": { + name: "log", + note: "", + synonym: "Журнал событий", + dimensions: { + date: { + synonym: "Дата", + multiline_mode: false, + tooltip: "Время события", + type: { + types: [ + "number" + ], + digits: 15, + fraction_figits: 0 + } + }, + sequence: { + synonym: "Порядок", + multiline_mode: false, + tooltip: "Порядок следования", + type: { + types: [ + "number" + ], + digits: 6, + fraction_figits: 0 + } + } + }, + resources: { + "class": { + synonym: "Класс", + multiline_mode: false, + tooltip: "Класс события", + type: { + types: [ + "string" + ], + str_len: 100 + } + }, + note: { + synonym: "Комментарий", + multiline_mode: true, + tooltip: "Текст события", + type: { + types: [ + "string" + ], + str_len: 0 + } + }, + obj: { + synonym: "Объект", + multiline_mode: true, + tooltip: "Объект, к которому относится событие", + type: { + types: [ + "string" + ], + str_len: 0 + } + } + } + } + }, + areg: {}, + dp: {}, + rep: {}, + cch: {}, + cacc: {} + }; _md = this; - // загружает метаданные из pouchdb function meta_from_pouch(meta_db){ @@ -36,7 +444,7 @@ function Meta() { }) .then(function (doc) { - _m = doc; + $p._patch(_m, doc); doc = null; return meta_db.get('meta_patch'); @@ -73,7 +481,7 @@ function Meta() { function do_init(){ if(meta_db && !is_local && !is_remote){ - _m = meta_db; + $p._patch(_m, meta_db); meta_db = null; _md.create_managers(); @@ -104,7 +512,7 @@ function Meta() { if(!_m) do_init(); - else{ + else if($p.iface && $p.iface.do_reload){ // если изменились метаданные, запланировать перезагрузку setTimeout(function () { diff --git a/src/meta_mngrs.js b/src/meta_mngrs.js index 69025ac29..4dbd720d1 100644 --- a/src/meta_mngrs.js +++ b/src/meta_mngrs.js @@ -54,7 +54,7 @@ function DataManager(class_name){ * ### После чтения объекта с сервера * Имеет смысл для объектов с типом кеширования ("doc", "doc_remote", "meta", "e1cib"). * т.к. структура _DataObj_ может отличаться от прототипа в базе-источнике, в обработчике можно дозаполнить или пересчитать реквизиты прочитанного объекта - * + * * @event after_load * @for DataManager */ @@ -422,7 +422,7 @@ DataManager.prototype.sync_grid = function(attr, grid){ if(typeof attr.custom_selection == "function"){ return attr.custom_selection(attr); - + }else if(mgr.cachable == "ram"){ // запрос к alasql @@ -486,7 +486,7 @@ DataManager.prototype.sync_grid = function(attr, grid){ }); } - + // TODO: переделать обработку catch() return request() .then(to_grid) @@ -779,8 +779,8 @@ DataManager.prototype.print = function(ref, model, wnd){ // если _printing_plates содержит ссылку на обрабочтик печати, используем его if(this._printing_plates[model] instanceof DataObj) - model = this._printing_plates[model]; - + model = this._printing_plates[model]; + // если существует локальный обработчик, используем его if(model instanceof DataObj && model.execute){ @@ -793,7 +793,7 @@ DataManager.prototype.print = function(ref, model, wnd){ .then(tune_wnd_print); }else{ - + // иначе - печатаем средствами 1С или иного сервера var rattr = {}; $p.ajax.default_attr(rattr, $p.job_prm.irest_url()); @@ -853,9 +853,9 @@ DataManager.prototype.printing_plates = function(){ * @param class_name {string} - имя типа менеджера объекта */ function RefDataManager(class_name) { - + RefDataManager.superclass.constructor.call(this, class_name); - + } RefDataManager._extend(DataManager); @@ -1090,7 +1090,7 @@ RefDataManager.prototype.__define({ return this.get(); } }, - + /** * Возаращает массив запросов для создания таблиц объекта и его табличных частей * @method get_sql_struct @@ -1885,10 +1885,10 @@ function RegisterManager(class_name){ attr = {}; else if(typeof attr == "string") attr = {ref: attr}; - + if(attr.ref && return_row) return force_promise ? Promise.resolve(this.by_ref[attr.ref]) : this.by_ref[attr.ref]; - + attr.action = "select"; var arr = $p.wsql.alasql(this.get_sql_struct(attr), attr._values), @@ -1906,7 +1906,7 @@ function RegisterManager(class_name){ res.push(this.by_ref[this.get_ref(arr[i])]); } } - + return force_promise ? Promise.resolve(res) : res; }; @@ -2404,199 +2404,6 @@ InfoRegManager.prototype.slice_last = function(filter){ }; -/** - * ### Журнал событий - * Хранит и накапливает события сеанса<br /> - * Является наследником регистра сведений - * @extends InfoRegManager - * @class LogManager - * @static - */ -function LogManager(){ - - LogManager.superclass.constructor.call(this, "ireg.$log"); - - var smax; - - this.__define({ - - /** - * Добавляет запись в журнал - * @param msg {String|Object|Error} - текст + класс события - * @param [msg.obj] {Object} - дополнительный json объект - */ - record: { - value: function(msg){ - - if(msg instanceof Error){ - if(console) - console.log(msg); - msg = { - class: "error", - note: msg.toString() - } - }else if(typeof msg == "object" && !msg.class && !msg.obj){ - msg = { - class: "obj", - obj: msg, - note: msg.note - }; - }else if(typeof msg != "object") - msg = {note: msg}; - - msg.date = Date.now() + $p.wsql.time_diff; - - // уникальность ключа - if(!smax) - smax = alasql.compile("select MAX(`sequence`) as `sequence` from `ireg_$log` where `date` = ?"); - var res = smax([msg.date]); - if(!res.length || res[0].sequence === undefined) - msg.sequence = 0; - else - msg.sequence = parseInt(res[0].sequence) + 1; - - // класс сообщения - if(!msg.class) - msg.class = "note"; - - $p.wsql.alasql("insert into `ireg_$log` (`ref`, `date`, `sequence`, `class`, `note`, `obj`) values (?,?,?,?,?,?)", - [msg.date + "¶" + msg.sequence, msg.date, msg.sequence, msg.class, msg.note, msg.obj ? JSON.stringify(msg.obj) : ""]); - - } - }, - - /** - * Сбрасывает события на сервер - * @method backup - * @param [dfrom] {Date} - * @param [dtill] {Date} - */ - backup: { - value: function(dfrom, dtill){ - - } - }, - - /** - * Восстанавливает события из архива на сервере - * @method restore - * @param [dfrom] {Date} - * @param [dtill] {Date} - */ - restore: { - value: function(dfrom, dtill){ - - } - }, - - /** - * Стирает события в указанном диапазоне дат - * @method clear - * @param [dfrom] {Date} - * @param [dtill] {Date} - */ - clear: { - value: function(dfrom, dtill){ - - } - }, - - show: { - value: function (pwnd) { - - } - }, - - get: { - value: function (ref, force_promise, do_not_create) { - - if(typeof ref == "object") - ref = ref.ref || ""; - - if(!this.by_ref[ref]){ - - if(force_promise === false) - return undefined; - - var parts = ref.split("¶"); - $p.wsql.alasql("select * from `ireg_$log` where date=" + parts[0] + " and sequence=" + parts[1]).forEach(function (row) { - new RegisterRow(row, this); - }.bind(this)); - } - - return force_promise ? Promise.resolve(this.by_ref[ref]) : this.by_ref[ref]; - } - }, - - get_sql_struct: { - value: function(attr){ - - if(attr && attr.action == "get_selection"){ - var sql = "select * from `ireg_$log`"; - if(attr.date_from){ - if (attr.date_till) - sql += " where `date` >= ? and `date` <= ?"; - else - sql += " where `date` >= ?"; - }else if (attr.date_till) - sql += " where `date` <= ?"; - - return sql; - - }else - return LogManager.superclass.get_sql_struct.call(this, attr); - } - }, - - caption_flds: { - value: function (attr) { - - var str_def = "<column id=\"%1\" width=\"%2\" type=\"%3\" align=\"%4\" sort=\"%5\">%6</column>", - acols = [], s = ""; - - - acols.push(new Col_struct("date", "200", "ro", "left", "server", "Дата")); - acols.push(new Col_struct("class", "100", "ro", "left", "server", "Класс")); - acols.push(new Col_struct("note", "*", "ro", "left", "server", "Событие")); - - if(attr.get_header){ - s = "<head>"; - for(var col in acols){ - s += str_def.replace("%1", acols[col].id).replace("%2", acols[col].width).replace("%3", acols[col].type) - .replace("%4", acols[col].align).replace("%5", acols[col].sort).replace("%6", acols[col].caption); - } - s += "</head>"; - } - - return {head: s, acols: acols}; - } - }, - - data_to_grid: { - value: function (data, attr) { - var xml = "<?xml version='1.0' encoding='UTF-8'?><rows total_count='%1' pos='%2' set_parent='%3'>" - .replace("%1", data.length).replace("%2", attr.start) - .replace("%3", attr.set_parent || "" ), - caption = this.caption_flds(attr); - - // при первом обращении к методу добавляем описание колонок - xml += caption.head; - - data.forEach(function(r){ - xml += "<row id=\"" + r.ref + "\"><cell>" + - $p.moment(r.date - $p.wsql.time_diff).format("DD.MM.YYYY HH:mm:ss") + "." + r.sequence + "</cell>" + - "<cell>" + (r.class || "") + "</cell><cell>" + (r.note || "") + "</cell></row>"; - }); - - return xml + "</rows>"; - } - } - }); - -} -LogManager._extend(InfoRegManager); - - /** * ### Абстрактный менеджер регистра накопления @@ -2616,7 +2423,6 @@ AccumRegManager._extend(RegisterManager); - /** * ### Абстрактный менеджер справочника * Экземпляры объектов этого класса создаются при выполнении конструктора {{#crossLink "Meta"}}{{/crossLink}} @@ -2809,3 +2615,231 @@ function BusinessProcessManager(class_name){ } BusinessProcessManager._extend(CatManager); + +/** + * ### Журнал событий + * Хранит и накапливает события сеанса<br /> + * Является наследником регистра сведений + * @extends InfoRegManager + * @class LogManager + * @static + */ +function LogManager(){ + + LogManager.superclass.constructor.call(this, "ireg.log"); + + var smax; + + this.__define({ + + /** + * Добавляет запись в журнал + * @param msg {String|Object|Error} - текст + класс события + * @param [msg.obj] {Object} - дополнительный json объект + */ + record: { + value: function(msg){ + + if(msg instanceof Error){ + if(console) + console.log(msg); + msg = { + class: "error", + note: msg.toString() + } + }else if(typeof msg == "object" && !msg.class && !msg.obj){ + msg = { + class: "obj", + obj: msg, + note: msg.note + }; + }else if(typeof msg != "object") + msg = {note: msg}; + + msg.date = Date.now() + $p.wsql.time_diff; + + // уникальность ключа + if(!smax) + smax = alasql.compile("select MAX(`sequence`) as `sequence` from `ireg_log` where `date` = ?"); + var res = smax([msg.date]); + if(!res.length || res[0].sequence === undefined) + msg.sequence = 0; + else + msg.sequence = parseInt(res[0].sequence) + 1; + + // класс сообщения + if(!msg.class) + msg.class = "note"; + + $p.wsql.alasql("insert into `ireg_log` (`ref`, `date`, `sequence`, `class`, `note`, `obj`) values (?,?,?,?,?,?)", + [msg.date + "¶" + msg.sequence, msg.date, msg.sequence, msg.class, msg.note, msg.obj ? JSON.stringify(msg.obj) : ""]); + + } + }, + + /** + * Сбрасывает события на сервер + * @method backup + * @param [dfrom] {Date} + * @param [dtill] {Date} + */ + backup: { + value: function(dfrom, dtill){ + + } + }, + + /** + * Восстанавливает события из архива на сервере + * @method restore + * @param [dfrom] {Date} + * @param [dtill] {Date} + */ + restore: { + value: function(dfrom, dtill){ + + } + }, + + /** + * Стирает события в указанном диапазоне дат + * @method clear + * @param [dfrom] {Date} + * @param [dtill] {Date} + */ + clear: { + value: function(dfrom, dtill){ + + } + }, + + show: { + value: function (pwnd) { + + } + }, + + get: { + value: function (ref, force_promise, do_not_create) { + + if(typeof ref == "object") + ref = ref.ref || ""; + + if(!this.by_ref[ref]){ + + if(force_promise === false) + return undefined; + + var parts = ref.split("¶"); + $p.wsql.alasql("select * from `ireg_log` where date=" + parts[0] + " and sequence=" + parts[1]).forEach(function (row) { + new RegisterRow(row, this); + }.bind(this)); + } + + return force_promise ? Promise.resolve(this.by_ref[ref]) : this.by_ref[ref]; + } + }, + + get_sql_struct: { + value: function(attr){ + + if(attr && attr.action == "get_selection"){ + var sql = "select * from `ireg_log`"; + if(attr.date_from){ + if (attr.date_till) + sql += " where `date` >= ? and `date` <= ?"; + else + sql += " where `date` >= ?"; + }else if (attr.date_till) + sql += " where `date` <= ?"; + + return sql; + + }else + return LogManager.superclass.get_sql_struct.call(this, attr); + } + }, + + caption_flds: { + value: function (attr) { + + var str_def = "<column id=\"%1\" width=\"%2\" type=\"%3\" align=\"%4\" sort=\"%5\">%6</column>", + acols = [], s = ""; + + + acols.push(new Col_struct("date", "200", "ro", "left", "server", "Дата")); + acols.push(new Col_struct("class", "100", "ro", "left", "server", "Класс")); + acols.push(new Col_struct("note", "*", "ro", "left", "server", "Событие")); + + if(attr.get_header){ + s = "<head>"; + for(var col in acols){ + s += str_def.replace("%1", acols[col].id).replace("%2", acols[col].width).replace("%3", acols[col].type) + .replace("%4", acols[col].align).replace("%5", acols[col].sort).replace("%6", acols[col].caption); + } + s += "</head>"; + } + + return {head: s, acols: acols}; + } + }, + + data_to_grid: { + value: function (data, attr) { + var xml = "<?xml version='1.0' encoding='UTF-8'?><rows total_count='%1' pos='%2' set_parent='%3'>" + .replace("%1", data.length).replace("%2", attr.start) + .replace("%3", attr.set_parent || "" ), + caption = this.caption_flds(attr); + + // при первом обращении к методу добавляем описание колонок + xml += caption.head; + + data.forEach(function(r){ + xml += "<row id=\"" + r.ref + "\"><cell>" + + $p.moment(r.date - $p.wsql.time_diff).format("DD.MM.YYYY HH:mm:ss") + "." + r.sequence + "</cell>" + + "<cell>" + (r.class || "") + "</cell><cell>" + (r.note || "") + "</cell></row>"; + }); + + return xml + "</rows>"; + } + } + + }); + +} +LogManager._extend(InfoRegManager); + + +/** + * ### Менеджер объектов метаданных + * Используется для формирования списков типов документов, справочников и т.д. + * Например, при работе в интерфейсе с составными типами + */ +function MetaObjManager() { + + MetaObjManager.superclass.constructor.call(this, "cat.meta_objs"); +} +MetaObjManager._extend(CatManager); + + +/** + * ### Менеджер доступных полей + * Используется при настройке отчетов и динамических списков + */ +function MetaFieldManager() { + + MetaFieldManager.superclass.constructor.call(this, "cat.meta_fields"); +} +MetaFieldManager._extend(CatManager); + + +/** + * ### Менеджер настроек отчетов и динсписков + */ +function SchemeSettingsManager() { + + SchemeSettingsManager.superclass.constructor.call(this, "cat.scheme_settings"); +} +SchemeSettingsManager._extend(CatManager); + + diff --git a/src/server/README.md b/src/server/README.md index 3cd254b45..0424708f7 100644 --- a/src/server/README.md +++ b/src/server/README.md @@ -1,4 +1,4 @@ -# Устареаший модуль +# Устаревший модуль ~~Сервер библиотеки интеграции Расположен между 1С и веб-приложением, содержит собственную базу данных и решает следующие задачи: Хранение списка объектов метаданных веб-приложения Хранение списка синонимов для сопоставления имён свойств и объектов метаданных diff --git a/src/server/build_meta.js b/src/server/build_meta.js index 92beafecf..841c67a16 100644 --- a/src/server/build_meta.js +++ b/src/server/build_meta.js @@ -72,7 +72,13 @@ $p.md.init($p.wsql.pouch.local._meta) function create_modules(_m){ var name, - text = "$p.md.create_managers=function(){\n", + sys_nsmes = ["log","meta_objs","meta_fields","scheme_settings"], + text = "$p.md.create_managers=function(){\n" + + "// создаём системные менеджеры (журнал регистрации, метаданные и настройки компоновки)\n" + + "$p.ireg.log = new $p.LogManager();\n" + + "$p.cat.meta_objs = new $p.MetaObjManager();\n" + + "$p.cat.meta_fields = new $p.MetaFieldManager();\n" + + "$p.cat.scheme_settings = new $p.SchemeSettingsManager();\n", categoties = { cch: {mgr: "ChartOfCharacteristicManager", obj: "CatObj"}, cacc: {mgr: "ChartOfAccountManager", obj: "CatObj"}, @@ -95,10 +101,9 @@ function create_modules(_m){ for(var category in categoties){ for(name in _m[category]){ text+= obj_constructor_text(_m, category, name, categoties[category].obj); - if(name == "$log") - text+= "$p." + category + "." + name + " = new $p.LogManager('ireg.$log');\n"; - else + if(sys_nsmes.indexOf(name) == -1){ text+= "$p." + category + "." + name + " = new $p." + categoties[category].mgr + "('" + category + "." + name + "');\n"; + } } } diff --git a/src/utils/prebuild.js b/src/utils/prebuild.js index 4ab6b20ad..51ccd12f6 100644 --- a/src/utils/prebuild.js +++ b/src/utils/prebuild.js @@ -49,7 +49,13 @@ module.exports = function (package_data) { function create_modules(_m){ var name, - text = "$p.md.create_managers=function(){\n", + sys_nsmes = ["log","meta_objs","meta_fields","scheme_settings"], + text = "$p.md.create_managers=function(){\n" + + "// создаём системные менеджеры (журнал регистрации, метаданные и настройки компоновки)\n" + + "$p.ireg.log = new $p.LogManager();\n" + + "$p.cat.meta_objs = new $p.MetaObjManager();\n" + + "$p.cat.meta_fields = new $p.MetaFieldManager();\n" + + "$p.cat.scheme_settings = new $p.SchemeSettingsManager();\n", categoties = { cch: {mgr: "ChartOfCharacteristicManager", obj: "CatObj"}, cacc: {mgr: "ChartOfAccountManager", obj: "CatObj"}, @@ -71,10 +77,9 @@ module.exports = function (package_data) { for(var category in categoties){ for(name in _m[category]){ text+= obj_constructor_text(_m, category, name, categoties[category].obj); - if(name == "$log") - text+= "$p." + category + "." + name + " = new $p.LogManager('ireg.$log');\n"; - else + if(sys_nsmes.indexOf(name) == -1){ text+= "$p." + category + "." + name + " = new $p." + categoties[category].mgr + "('" + category + "." + name + "');\n"; + } } }