var commands = commands || {}; commands.CommandBag = (function () { "use strict"; function CommandBag() { } EventHandler.injectInto(CommandBag.prototype); Object.defineProperties(CommandBag.prototype, { commands: { get: function () { if (!this.hasOwnProperty("_commands")) { Object.defineProperty(this, "_commands", { value: {} }); } return this._commands; }, enumerable: true }, items: { get: function () { return _.toArray(this.commands).select(function (x) { return x.value; }).distinct(); }, enumerable: true }, on: { value: function () { var args = _.array(arguments); if (args.length === 3 && typeof (args[1]) === "string") { return EventHandler.prototype.on.call(this, args[0], function (e, arg) { return arg.cmd.name === args[1]; }, args[2]); } return EventHandler.prototype.on.apply(this, args); } }, find: { value: function (name) { return this.commands[name]; } }, add: { value: function (cmd) { var cb = this; var cmds = _.array(cmd); var replaced = []; cmds.forEach(function (cmd) { if (!cmd.hasOwnProperty("disabled")) { Object.defineProperty(cmd, "disabled", { value: false, writable: true }); } if (!cmd.hasOwnProperty("toggleable")) { Object.defineProperty(cmd, "toggleable", { get: function () { return cmd.hasOwnProperty("active"); } }); } if (cmd.name in cb.commands) { replaced.push(cb.commands[cmd.name]); } cb.commands[cmd.name] = cmd; }); return cb._onAdd({ added: cmds, replaced: replaced, commands: cb.commands }); } }, remove: { value: function (o) { var name = o.name || o; if (name in this.commands) { var cmd = this.commands[name]; delete this.commands[name]; return this._onRemove({ removed: cmd, commands: this.commands }); } return Promise.resolve(); } }, _execute: { value: function (cmd) { var cb = this; var promise; if (typeof (cmd.callback) !== "function") { promise = Promise.resolve(true); } else { promise = Promise.resolve(cmd.callback.call(cmd.scope || cb, { cmd: cmd, context: cb })); } return promise .then(function (commandResult) { return cb._onExecute({ cmd: cmd, context: cb, result: commandResult }); }); } }, execute: { value: function (o) { var cmd = typeof (o) === "string" ? this.find(o) : o; //console.log("EXECUTE", { o: o, cmd: cmd, bag: this }); if (cmd) { if (cmd.toggleable) { if (cmd.active) { return this.deactivate(cmd); } else { return this.activate(cmd); } } else { return this._execute(cmd); } } return Promise.resolve(false); } }, activate: { //o: name | cmd value: function (o) { var cmd = typeof (o) === "string" ? this.find(o) : o; if (cmd && cmd.toggleable) { cmd.active = true; return this._execute(cmd); } return Promise.resolve(false); } }, deactivate: { //o: name | cmd value: function (o) { var cmd = typeof (o) === "string" ? this.find(o) : o; if (cmd && cmd.toggleable) { cmd.active = false; return this._execute(cmd); } return Promise.resolve(false); } }, setDisabled: { value: function (o, disabled) { if (disabled) { this.disable(o); } else { this.enable(o); } } }, disable: { value: function (o) { var cb = this; var disabled = []; //console.log("DISABLING", { o: o, commands: cb.commands }); _.array(o).forEach(function (input) { var cmd = cb.find(input.name || input); //console.log("DISABLING", { cmd: cmd, input: input }); cmd.disabled = true; disabled.push(cmd); }); return cb._onChange({ disabled: disabled, commands: cb.commands }); } }, disableAll: { value: function () { this.items.forEach(function (cmd) { cmd.disabled = true; }); return this._onChange({ disabled: this.items, commands: this.commands }); } }, enable: { value: function (o) { var cb = this; var enabled = []; _.array(o).forEach(function (input) { var cmd = cb.find(input.name || input); cmd.disabled = false; enabled.push(cmd); }); return cb._onChange({ enabled: enabled, commands: cb.commands }); } }, enableAll: { value: function () { this.items.forEach(function (cmd) { cmd.disabled = false; }); return this._onChange({ enabled: this.items, commands: this.commands }); } }, //mode: { // value: function(mode) { // var cb = this; // } //}, _onAdd: { value: function (arg) { return this.trigger("add", arg); } }, _onRemove: { value: function (arg) { return this.trigger("remove", arg); } }, _onChange: { value: function (arg) { return this.trigger("change", arg); } }, _onExecute: { //arg: { cmd: cmd, result: cmdResult } value: function (arg) { var cb = this; return cb.trigger("execute", arg) .then(function (results) { return cb._onAfterExecute({ cmd: arg.cmd, context: cb, commandResult: arg.result, eventResults: results }); }); } }, _onAfterExecute: { //arg: { cmd: cmd, commandResult: cmdResult, eventResults: results } value: function (arg) { return this.trigger(new Event("after-execute"), arg); } } }); return CommandBag; })("commands"); var commands = commands || {}; commands.CommandDirective = (function () { function CommandDirective($compile) { return { restrict: "EA", scope: { cmd: "=" }, link: function ($scope, $el) { $scope.update = function () { if ($scope.compiled) { $scope.compiled.remove(); } var content = typeof ($scope.cmd.content) === "function" ? $scope.cmd.content($scope.cmd) : $scope.cmd.content; $scope.compiled = $compile($(content).clone())($scope); $el.append($scope.compiled); } $scope.$watch("cmd", $scope.update); } } }; CommandDirective.$inject = ["$compile"]; return CommandDirective; })("commands"); var commands = commands || {}; commands.CommandManager = (function () { "use strict"; function CommandManager(commandBag) { var cm = this; //console.log("COMMAND_MANAGER", { me: this }); Object.defineProperties(cm, { _commandBag: { value: commandBag } }); commandBag.on("add", function () { cm._updateTree(); }); } EventHandler.injectInto(CommandManager.prototype); Object.defineProperties(CommandManager.prototype, { keys: { get: function () { if (!("_keys" in this)) { Object.defineProperty(this, "_keys", { value: new TreeList({ fkSelector: function (child, parent) { return child.parentName && child.parentName === parent.name; } }) }); } return this._keys; }, enumerable: true }, _missing: { //ToDo: use this property to mainain order of commands in tree get: function () { return this.keys.where(function (x) { return !x.ready; }).select(function (x) { return x.name; }); }, enumerable: true }, tree: { get: function () { if (!("_tree" in this)) { Object.defineProperty(this, "_tree", { value: new TreeList({ fkSelector: function (child, parent) { return child.parentName && child.parentName === parent.name; } }) }); } return this._tree; }, enumerable: true }, find: { value: function (name) { return this._commandBag.find(name); //return this.tree.first(function (x) { return x.name === name; }); } }, buildTree: { /* [ { "GreetingPlaceholder": [ "Hello", "GreetMeLater" ] }, "ActivateMe", "RemoveFirstCommand" ] */ value: function (keyArray) { var cm = this; //ToDo: maintain requested order of commands (loaded async!) function addKeys(items, parentKey) { items.forEach(function (item, index) { var key = (typeof (item) === "string") ? item : Object.keys(item).first(); cm.keys.add({ name: key, position: index, parentName: parentKey, ready: false }); if (typeof (item) !== "string" && key in item) { var cmd = cm.find(key); if (cmd && !("active" in cmd)) { cmd.active = false; } addKeys(item[key], key); } }); } //console.log("CM.BUILDING_TREE", { keys: keyArray }); cm.keys.clear(); addKeys(keyArray); cm.tree.clear(); return cm._updateTree(); } }, _updateTree: { value: function () { var cm = this; var added = []; cm.keys.values .where(function (x) { return !x.ready; }) .forEach(function (x) { var cmd = cm._commandBag.find(x.name); if (cmd) { var arg = {/*position: x.position*/ }; if (x.parentName) { arg.parents = cm.tree.getNodes().first(function (p) { return p.value.name === x.parentName; }); } added.push(cmd); cm.tree.add(cmd, arg); x.ready = true; } }); return cm._change({ added: added, tree: cm.tree }); } }, _change: { //arg: { added: [added], tree: tree } value: function (arg) { var cm = this; //console.log("CM.CHANGE", { arg: arg }); return cm.trigger(new Event("change"), arg); } } }); return CommandManager; })("commands"); var commands = commands || {}; commands.CommandsController = (function () { "use strict"; function CommandsController(commandBag, commandManager, $timeout) { var vm = this; Object.defineProperties(vm, { _commandBag: { value: commandBag }, _tree: { value: commandManager.tree } }); function updateView() { //console.log("CMD.UPDATE_VIEW", { cm: cm, ctrl: vm }); return $timeout(); } vm.$onInit = function () { commandManager.on("change", updateView); commandBag.on("change", updateView); }; vm.$onDestroy = function () { commandManager.off("change", updateView); commandBag.off("change", updateView); }; } CommandsController.$inject = ["commandBag", "commandManager", "$timeout"]; Object.defineProperties(CommandsController.prototype, { tree: { get: function () { return this._tree; }, enumerable: true }, items: { get: function () { return this.tree.values; }, enumerable: true }, execute: { value: function (cmd) { return this._commandBag.execute(cmd); } }, isVisible: { value: function (cmd) { if (!("visible" in cmd)) { return true; } if (typeof (cmd.visible) === "function") { return cmd.visible.apply(cmd); } return cmd.visible; } }, isDisabled: { value: function (cmd) { if ("disabled" in cmd) { if (typeof (cmd.disabled) === "function") { return cmd.disabled.apply(cmd); } return cmd.disabled; } if ("enabled" in cmd) { if (typeof (cmd.enabled) === "function") { return !cmd.enabled.apply(cmd); } return !cmd.enabled; } return false; } } }); return CommandsController; })("commands"); var commands = commands || {}; (function (root) { function ContextMenuDirectiveFactory() { } ContextMenuDirectiveFactory.create = function (ctrl, defaultTemplateUrl) { function ContextMenuDirective($timeout) { return { restrict: "EA", controller: ctrl, controllerAs: "ctrl", scope: { parentContainer: "@" }, templateUrl: function ($el, $attr) { return $el.contextMenu || $attr.src || defaultTemplateUrl; }, link: function ($scope, $el, $attr, $ctrl) { //console.log("CONTEXTMENU_INIT", { arg: arguments, scope: $scope, ctrl: $ctrl }); var hidingPromise; var parent = $($scope.parentContainer || "body") .append( $el.addClass("context-menu") .on("mouseover", function () { if (hidingPromise) { $timeout.cancel(hidingPromise); } }) .on("mouseout", function () { hidingPromise = $timeout(function () { $scope.hide(); }, 500); }) ) .css({ position: "relative" }); $(document) .on("contextmenu", parent, function (e) { e.preventDefault(); $el.css({ left: e.clientX + "px", top: e.clientY + "px" }).show(); }); $scope.hide = function () { $el.hide(); } $scope.hide(); } } } ContextMenuDirective.$inject = ["$timeout"]; return ContextMenuDirective; }; root.ContextMenuDirectiveFactory = ContextMenuDirectiveFactory; })(commands); var commands = commands || {}; (function (root) { function ToolbarDirectiveFactory() { } ToolbarDirectiveFactory.create = function (ctrl) { return function ToolbarDirective() { return { restrict: "EA", controller: ctrl || "toolbarController", controllerAs: "ctrl", scope: {}, transclude: true, link: function ($scope, $el, $attr, $ctrl, $transclude) { $transclude($scope, function (clone) { $el .addClass("toolbar") .append(clone); }); } } } }; root.ToolbarDirectiveFactory = ToolbarDirectiveFactory; })(commands); var commands = commands || {}; commands.module = (function (moduleName) { "use strict"; return angular.module("geoit.commands", []) //.service("commandBag", commands.CommandBag) .provider("commandBag", function () { var cmds = []; this.add = function (cmd) { cmds.addRange(_.array(cmd)); }; this.$get = function () { var cb = new commands.CommandBag(); cb.add(cmds); return cb; }; }) .directive("command", commands.CommandDirective) .run(["config", function (config) { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); }]) .config(["commandBagProvider", function (cbProvider) { cbProvider.add({ name: "separator", content: '
' }); }]); })("commands"); var projects = projects || {}; projects.projectHeaderComponent = (function () { function projectHeaderViewModel(projectManager) { Object.defineProperties(this, { _projectManager: { value: projectManager } }); } Object.defineProperties(projectHeaderViewModel.prototype, { item: { get: function () { return this._projectManager.activeItem; }, enumerable: true } }); function projectHeaderComponent(templateUrl) { return { bindings: { hideCode: "<" }, controller: projectHeaderViewModel, templateUrl: ["config", function (config) { return config.baseUrl + "/" + templateUrl + "?v=" + config.version; }] } } return projectHeaderComponent; })(); var projects = projects || {}; projects.projectListComponent = (function () { "use strict"; function projectListViewModel($translate) { Object.defineProperties(this, { _translate: { value: $translate }, loading: { writable: true }, canCreate: { writable: true }, canEdit: { writable: true }, items: { writable: true }, activeItem: { writable: true }, loadedItems: { writable: true }, onActiveItemChange: { writable: true }, onLoadItem: { writable: true }, onUnloadItem: { writable: true }, onShow: { writable: true }, onZoom: { writable: true } }); } Object.defineProperties(projectListViewModel.prototype, { toggleActiveItem: { value: function (e, item) { var isActive = this.isActive(item); return this.onActiveItemChange({ event: e, item: isActive ? null : item }); } }, toggleLoaded: { value: function (e, item) { var isLoaded = this.isLoaded(item); if (!isLoaded) { return this.onLoadItem({ event: e, item: item }); } else { return this.onUnloadItem({ event: e, item: item }); } } }, handleShow: { value: function (e, item, display) { return this.onShow({ event: e, item: item, display: display }); } }, handleZoom: { value: function (e, item) { return this.onZoom({ event: e, item: item }); } }, isActive: { value: function (item) { return (this.activeItem || {}).id === item.id; } }, isLoaded: { value: function (item) { var isLoaded = (this.loadedItems || []).any(function (x) { return x.id === item.id; }); return isLoaded; } } }); function projectListComponent(templateUrl) { return { controller: ["$translate", projectListViewModel], bindings: { loading: "<", canCreate: "<", canEdit: "<", items: "<", activeItem: "<", loadedItems: "<", onActiveItemChange: "&", onLoadItem: "&", onUnloadItem: "&", onShow: "&", onZoom: "&" }, templateUrl: ["config", function (config) { return config.baseUrl + "/" + templateUrl + "?v=" + config.version; }], transclude: { loading: "?loading" } }; } return projectListComponent; })(); var projects = projects || {}; projects.ProjectController = (function (moduleName) { "use strict"; var _translate; function ProjectController(manager, $timeout, $translate) { var ctrl = this; _translate = $translate; Object.defineProperties(ctrl, { //_display: { value: "list", writable: true }, loading: { value: false, writable: true }, _item: { writable: true }, _manager: { value: manager }, _timeout: { value: $timeout }, stateManager: { value: StateManagerFactory.createEntityStateManager(_.newGuid(), { controller: ctrl, entityType: 'Project', module: moduleName }), enumerable: true } }); } Object.defineProperties(ProjectController.prototype, { filter: { get: function () { return this._manager.filter; }, set: function (value) { this._manager.filter = value; }, enumerable: true }, activeItem: { get: function () { return this._manager.activeItem; }, enumerable: true }, errors: { get: function () { return this._manager.errors; }, enumerable: true }, display: { get: function () { //return this._display; return this._manager.display; }, set: function (value) { //this._display = value; //if (value !== "form") { // this._manager.setFormItem(null); // this._timeout(); //} var o = { oldValue: this._display, newValue: value }; this._manager.setDisplay(value); if (o.oldValue !== o.newValue) { this.onChangeDisplay(o); } }, enumerable: true }, onChangeDisplay: { value: function (o) { } }, item: { get: function () { return this._item; }, set: function (value) { //console.log("PC.SET_ITEM", { item: value }); this._item = value; this._manager.setFormItem(this.display === "form" ? value : null); }, enumerable: true }, items: { get: function () { return this._manager.items; }, enumerable: true }, itemsCount: { get: function () { return this._manager.itemsCount; }, enumerable: true }, loadedItems: { get: function () { return this._manager.loadedItems; }, enumerable: true }, // init init: { value: function () { //return this.list(); } }, // filter onChangeFilter: { value: function (/*filter, prop*/) { } }, confirmFilter: { value: function () { var ctrl = this; return this.list() .then(ctrl._timeout); } }, resetFilter: { value: function () { var ctrl = this; this.filter = {}; return this.list() .then(ctrl._timeout); } }, // item(s) showItem: { value: function (item, display) { var ctrl = this; var promise; if (item == null || item.id <= 0) { promise = ctrl.select(null) .then(function () { return ctrl._manager.getNewItem(); }); } else { promise = ctrl._manager.details(item.id); } return promise .then(function (details) { ctrl.setItem(details, display); return ctrl._timeout(); }); } }, onChangeItem: { value: function (item, prop, value) { var ctrl = this; var oldValue = item[prop]; item[prop] = value; //console.log("PC.CHANGE_ITEM", { item: item, prop: prop, oldValue: oldValue, value: value, ctrl: ctrl }); return Promise.resolve() .then(function () { if (prop === "title") { } if (prop === "code") { return ctrl._manager.validateCode($.extend(true, {}, item, { code: value }), ctrl.errors) .then(function (errors) { return { isValid: !errors.length, rollback: false }; }); } if (prop === "startDate" || prop === "endDate") { return ctrl._manager.validateStartAndEndDate($.extend(true, {}, item, { code: value }), ctrl.errors) .then(function (errors) { return { isValid: !errors.length, rollback: false }; }); } return { isValid: true, rollback: false }; }) .then(function (result) { if (result.rollback) { item[prop] = oldValue; return false; } return ctrl._manager.onChangeItem(item, prop, value, oldValue); }) .then(function (response) { return ctrl._timeout() .then(response); }); } }, list: { value: function () { return this._manager.list(); } }, save: { // projectUsers is optional value: function (/*projectUsers*/) { var ctrl = this; var item = ctrl.item; //console.log("PC.SAVE", { item: item }); return ctrl._manager.save(item); } }, remove: { value: function () { var ctrl = this; var item = ctrl.item; return _translate("global.ConfirmDeleteProject") .then(function (translation) { return confirm(translation); }) .then(function (confirmed) { if (!confirmed) { return false; } var state = ctrl.stateManager.addState("loading"); return ctrl._manager.remove(item) .then(function (removed) { ctrl.item = null; ctrl.display = "list"; return ctrl._timeout() .then(function () { return removed; }); }) .then(state.completed) .catch(function (error) { state.error(error); throw error; }); }); } }, reset: { value: function (display) { var ctrl = this; return ctrl.showItem(ctrl.item, display || ((ctrl.item != null && ctrl.item.id > 0) ? "form" : "list")); } }, // (de)activate item select: { value: function (item) { var ctrl = this; var state = ctrl.stateManager.addState("loading"); //ctrl.setLoading(true); var projectToUnload; return Promise.resolve() .then(function () { if (ctrl.activeItem != null && item != null && ctrl.activeItem.id !== item.id) { projectToUnload = ctrl.activeItem; } }) .then(function () { if (item == null || item.id <= 0) { return item; } return ctrl._manager.details(item.id); }) .then(function (details) { return ctrl._manager.setActiveItem(details); //.then(function () { // ctrl.setLoading(false); // return details; //}); }) .then(function (details) { if (projectToUnload != null) { return ctrl.unloadItem(projectToUnload) .then(function () { return details; }); } return details; }) .then(state.completed) .catch(function (error) { state.error(error); throw error; }); } }, // (un)loading items loadItem: { value: function (item) { var ctrl = this; //console.log("PC.LOAD", { item: item, ctrl: this }); var state = ctrl.stateManager.addState("loading"); //ctrl.setLoading(true); return this._manager.loadItem(item) //.then(function (arg) { // ctrl.setLoading(false); // return arg; //}) .then(state.completed) .catch(function (error) { state.error(error); throw error; }); } }, unloadItem: { value: function (item) { var ctrl = this; //console.log("PC.UNLOAD", { item: item, ctrl: this }); var state = ctrl.stateManager.addState("loading"); //ctrl.setLoading(true); return this._manager.unloadItem(item) //.then(function (arg) { // ctrl.setLoading(false); // return arg; // }) .then(state.completed) .catch(function (error) { state.error(error); throw error; }); } }, setItem: { value: function (item, display) { var ctrl = this; ctrl.display = display; ctrl.item = item; ctrl.errors.clear(); }, configurable: true }, // busy //setLoading: { // value: function (value, ms) { // var ctrl = this; // return ctrl._timeout(function () { // ctrl.loading = value; // }, ms || 25); // } //}, zoom: { value: function (items) { if (typeof (items) === "undefined") { items = this.display !== "list" ? this.item : this.loadedItems; } return this._manager.focus(items, { minScale: 500 }); } }, }); return ProjectController; })("projects"); var projects = projects || {}; projects.ProjectManager = (function () { "use strict"; function ProjectManager(service) { common.EntityManager.call(this, service); Object.defineProperties(this, { _active: { value: null, writable: true }, _formItem: { value: null, writable: true }, _display: { value: "list", writable: true }, _loaded: { value: [] }, canChangeActiveItem: { value: true, writable: true, enumerable: true }, errors: { value: [], enumerable: true } }); } ProjectManager.prototype = Object.create(common.EntityManager.prototype, { constructor: { value: ProjectManager }, loadedItems: { get: function () { return this._loaded; }, set: function (value) { this.setLoadedItems(value); }, enumerable: true }, activeItem: { get: function () { return this._active; }, set: function (value) { this.setActiveItem(value); }, enumerable: true }, activeId: { get: function () { var item = this.activeItem; return item ? item.id : null; } }, formItem: { get: function () { return this._formItem; }, set: function (value) { this.setFormItem(this.display === "form" ? value : null); }, enumerable: true }, display: { get: function () { return this._display; }, set: function (value) { this.setDisplay(value); } }, //init init: { value: function (o) { o = o || {}; return common.EntityManager.prototype.init.call(this, o); } }, remove: { value: function (item) { var mgr = this; return Promise.resolve() .then(function () { // unload item if (mgr.isLoaded(item)) { return mgr.unloadItem(item); } return null; }) .then(function () { // deactivate item if (mgr.isActive(item)) { return mgr.setActiveItem(null); } return null; }) .then(function () { return common.EntityManager.prototype.remove.call(mgr, item) .then(function (removed) { return removed; }); }); } }, // (un)loading items loadItem: { value: function (item) { //console.log('ProjectManager.loadItem', item, this); return this.loadItems(_.array(item)); } }, loadItems: { value: function (items) { var t0 = performance.now(); return this.setLoadedItems(this.loadedItems.concat(_.array(items)).distinctBy(function (x) { return x.id; })) .then(function (result) { var t1 = performance.now(); //console.log("PERFORMANCE", Math.round(t1 - t0), "ProjectManager[loadItems]"); return result; }); } }, unloadItem: { value: function (item) { //console.log('ProjectManager.unloadItem', item, this); return this.unloadItems([item]); } }, unloadItems: { value: function (items) { var mgr = this; items = _.array(items); var t0 = performance.now(); var itemsToRemove = this.loadedItems.where(function (x) { return items.any(function (o) { return mgr._equalsItem(x, o); }); }); return this.setLoadedItems(this.loadedItems.except(itemsToRemove)) .then(function (result) { var t1 = performance.now(); //console.log("PERFORMANCE", Math.round(t1 - t0), "ProjectManager[unloadItems]"); return result; }); } }, // (de)activate item toggleItem: { value: function (item) { //console.log('ProjectManager.toggleItem', item, this); var t0 = performance.now(); var value = this._equalsItem(item, this._active) ? null : item; return this.setActiveItem(value) .then(function (result) { var t1 = performance.now(); //console.log("PERFORMANCE", Math.round(t1 - t0), "ProjectManager[toggleItem]"); return result; }); } }, activateByFilter: { value: function (filter) { var mgr = this; return mgr._service.list(filter) .then(function (items) { return mgr.setActiveItem(items.first()); }); } }, activateByQuery: { value: function (filter) { filter = filter || { }; var id = parseInt(Q.query("projectId")); if (id) { filter.id = id; } else { var code = H.query("project") || Q.query("project"); if (code) { filter.code = code; } } if (!filter.id && !filter.code) { filter.id = -1; } console.log("INITIAL_PROJECT", { filter: filter }); return this.activateByFilter(filter); } }, // trigger change item onChangeItem: { value: function (item, prop, value, oldValue) { return this.trigger("change-item", { item: item, prop: prop, value: value, oldValue: oldValue }); } }, // focus (zoom) focus: { value: function (items, options) { var mgr = this; return Promise .enqueue(_.array(items).select(function (x) { return function () { return mgr.find(x.id); }; })) .then(function (details) { var arg = $.extend({}, options, { items: details, extents: [], addExtent: function (extent) { if (extent) { this.extents.push(extent); } } }); return mgr.trigger("request-extents", arg) .then(function () { arg.extents = arg.extents.where(function(x) { return x && x.length === 4 && x[0] && x[1] && x[2] && x[3]; }); if (!arg.extents.length) { return null; } arg.bounds = [ arg.extents.min(function (x) { return x[0] }), arg.extents.min(function (x) { return x[1] }), arg.extents.max(function (x) { return x[2] }), arg.extents.max(function (x) { return x[3] }) ]; return mgr.trigger("focus", arg); }) .then(function () { return arg; }); }); } }, // save save: { value: function (item, display) { var mgr = this; return mgr.validate(item) .then(function (isValid) { if (!isValid) { console.warn("PM.INVALID", { item: item, errors: mgr.errors }); return null; } return common.EntityManager.prototype.save.call(mgr, item) .then(function (saved) { item.id = saved.id; if (mgr.activeItem != null && saved.id === mgr.activeItem.id) { if (mgr.activeItem.geoJson != null && saved.geoJson != null && saved.geoJson.features != null) { mgr.activeItem.geoJson.features = saved.geoJson.features; } } if (mgr.formItem != null && saved.id === mgr.formItem.id) { if (mgr.formItem.geoJson != null && saved.geoJson != null && saved.geoJson.features != null) { mgr.formItem.geoJson.features = saved.geoJson.features; } } if (typeof (display) === "string") { return mgr.setDisplay(display || "list") .then(function () { return saved; }); } return saved; }); }); } }, // validation validate: { value: function (item) { var mgr = this; var errors = mgr.errors; errors.clear(); //console.log("PM.VALIDATING", { item: item, mgr: mgr }); return Promise.resolve([]) .then(function () { if (!item.title) { errors.push("TitleMissing"); } }) .then(function () { return mgr.validateStartAndEndDate(item, errors); }) .then(function () { if (!item.code) { errors.push("CodeMissing"); } return mgr.validateCode(item, errors); }) .then(function () { //console.log("PM.VALIDATED", { item: item, errors: errors, mgr: mgr }); return !errors.length; }); } }, validateCode: { value: function (item, errors) { var mgr = this; errors.remove("CodeInvalid"); return mgr._service.list({ code: item.code }) .then(function (otherItems) { var otherItem = otherItems.first(); if (otherItem != null && otherItem.id !== item.id) { errors.push("CodeInvalid"); return false; } return true; }); } }, validateStartAndEndDate: { value: function (item, errors) { errors.remove("StartDateAfterEndDate"); errors.remove("EndDateBeforeStartDate"); return Promise.resolve() .then(function () { if (item.startDate && item.endDate && item.startDate > item.endDate) { errors.push("StartDateAfterEndDate"); errors.push("EndDateBeforeStartDate"); return false; } return true; }); } }, getReport: { value: function (exportType) { return this._service.getReport(this.activeItem, exportType); } }, setLoadedItems: { value: function (value) { var mgr = this; var oldValue = mgr._loaded.select(); return Promise .enqueue(_.array(value).select(function (x) { return function () { return mgr.find(x.id); }; })) .then(function (items) { var added = items.where(function (v) { return oldValue.all(function (o) { return !mgr._equalsItem(o, v); }); }); var removed = oldValue.where(function (v) { return items.all(function (o) { return !mgr._equalsItem(o, v); }); }); var arg = { oldValue: oldValue, items: mgr._loaded, added: added, removed: removed, hasLoaded: added.length, hasUnloaded: removed.length }; // update loaded items Array.prototype.splice.apply(mgr._loaded, [0, mgr._loaded.length].concat(items)); // only trigger event when changes occured if (arg.hasLoaded || arg.hasUnloaded) { var t0 = performance.now(); return mgr.trigger("change-loaded-items", arg) .then(function (result) { var t1 = performance.now(); //console.log("PERFORMANCE", Math.round(t1 - t0), "ProjectManager[setLoadedItems].trigger[change-loaded-items]"); return result; }); } return arg; }); } }, setActiveItem: { value: function (item) { var mgr = this; //console.log("PM.ACTIVATE", { item: item, mgr: mgr }); return Promise.resolve() .then(function () { if (!mgr.canChangeActiveItem) { return { activated: null, deactivated: null, hasChanged: false }; } //var t0 = performance.now(); return (item ? mgr.details(item.id) : Promise.resolve(null)) .then(function (result) { //var t1 = performance.now(); //console.log("PERFORMANCE", Math.round(t1 - t0), "ProjectManager[setActiveItem.details]"); return result; }) .then(function (details) { var oldValue = mgr._active; mgr._active = details; var arg = { activated: details, deactivated: oldValue, hasChanged: !mgr._equalsItem(details, oldValue) }; var promise = Promise.resolve(); // deactivate current item -> unload if (!details && oldValue) { promise = promise.then(function () { return mgr.unloadItem(oldValue); }); } // new active item - reload if (details) { if (mgr.isLoaded(details)) { // unload first to make sure the most recent version is loaded promise = promise.then(function () { return mgr.unloadItem(details); }); } // load new item promise = promise.then(function () { return mgr.loadItem(details); }); } return promise .then(function () { return arg; }); }); }) .then(function (arg) { //var t0 = performance.now(); return mgr.trigger("change-active-item", arg) .then(function () { return arg; }) .then(function (result) { //var t1 = performance.now(); //console.log("PERFORMANCE", Math.round(t1 - t0), "ProjectManager[setActiveItem].trigger[change-active-item]"); return result; }); }); } }, setFormItem: { value: function (item) { var mgr = this; var oldValue = mgr._formItem; return (item == null || item.id <= 0 ? Promise.resolve(item) : mgr.details(item.id)) .then(function (details) { mgr._formItem = details; var arg = { loaded: details, unloaded: oldValue, hasChanged: !mgr._equalsItem(details, oldValue) }; return mgr.trigger("change-form-item", arg) .then(function () { return arg; }); }); } }, // display setDisplay: { value: function (display) { var mgr = this; var oldDisplay = mgr.display; var arg = { display: display, oldDisplay: oldDisplay }; return Promise.resolve() .then(function () { if (display !== oldDisplay) { mgr._display = display; return Promise.resolve() .then(function () { if (display !== "form") { return mgr.setFormItem(null); } return false; }) .then(function () { return mgr.trigger("change-display", arg); }); } return false; }) .then(function () { return arg; }); } }, isActive: { value: function (item) { return this._equalsItem(item, this._active); } }, isLoaded: { value: function (item) { var mgr = this; return this.loadedItems.any(function (x) { return mgr._equalsItem(x, item); }); } } }); return ProjectManager; })(); var projects = projects || {}; projects.ProjectService = (function () { "use strict"; function ProjectService(config, $http) { EntityServiceBase.call(this, config, $http); } ProjectService.$inject = ["projectsConfig", "$http"]; ProjectService.prototype = Object.create(EntityServiceBase.prototype, { constructor: { value: ProjectService }, _processItem: { value: function (item) { if (item) { "startDate,endDate,created,lastModified".split(",") .forEach(function (x) { if (item[x]) { try { var date = new Date(item[x]); item[x] = date; } catch (error) { console.error('Failed to convert value to Date', item[x]); item[x] = null; } } }); } return item; } }, list: { value: function (o) { var filter = $.extend({}, o); if (filter["date"]) { filter["date"] = moment(filter["date"]).format("YYYY-MM-DD"); } return EntityServiceBase.prototype.list.call(this, filter); } } }); return ProjectService; })(); var projects = projects || {}; projects.ProjectSecurityController = (function () { "use strict"; var _manager; function ProjectSecurityController(manager) { _manager = manager; //console.log("PROJECT_SECURITY_CTRL", { ctrl: this }); } Object.defineProperties(ProjectSecurityController.prototype, { getUsers: { value: function () { return this.projectUsers.select(function (pUser) { return pUser.user; }); } }, project: { get: function () { return _manager.loadedProject; }, enumerable: true }, projectUsers: { get: function () { return _manager.loadedProjectUsers; }, enumerable: true }, isAdministrator: { get: function () { return _manager.isAdministrator(); }, enumerable: true }, isProjectLeider: { get: function () { return _manager.isProjectLeider(); }, enumerable: true }, projectConfig: { get: function () { return _manager.projectConfig; }, enumerable: true }, canCreate: { value: function () { return _manager.canCreate(); } }, canRead: { value: function (project) { return _manager.canRead(project); } }, canEdit: { value: function (project) { return _manager.canEdit(project); } }, addUsers: { value: function (users) { console.log("ADD_USERS", { users: _.array(users) }); return _manager.addLoadedUsers(users); } }, removeUsers: { value: function (users) { console.log("REMOVE_USERS", { users: _.array(users) }); return _manager.removeLoadedUsers(users); } }, listProjectUsers: { value: function () { return _manager.loadProjectAndUsers(this.project); } }, saveProjectUsers: { // { project, projectUsers } value: function () { return _manager.saveProjectUsers(this.project, this.projectUsers); } } }); return ProjectSecurityController; })(); var projects = projects || {}; projects.ProjectSecurityManager = (function () { "use strict"; var _user; var _project; var _projectUsers; var _service; var _projectConfig; function ProjectSecurityManager(config, moduleName, service, projectConfig) { _user = config.user; _service = service; _projectConfig = projectConfig; Object.defineProperties(this, { _moduleName: { value: moduleName } }); } Object.defineProperties(ProjectSecurityManager.prototype, { canCreate: { value: function () { return _service.canCreate(); } }, canRead: { value: function (project) { return _service.canRead(project); } }, canEdit: { value: function (project) { return _service.canEdit(project); } }, canEditModule: { value: function (project) { return _service.canEditModule(project); } }, isAdministrator: { value: function () { return _service.isAdministrator(); } }, isProjectLeider: { value: function () { return _service.isProjectLeider(); } }, projectConfig: { value: function () { return _projectConfig; } }, loadedProject: { get: function () { return _project; }, set: function (value) { _project = value; }, enumerable: true }, loadedProjectUsers: { get: function () { return _projectUsers; }, set: function (value) { _projectUsers = value || []; }, enumerable: true }, getProjectUsers: { value: function (project) { return Promise.resolve() .then(function () { return project == null ? [] : _service.getProjectUsers(project); }); } }, modifyProjectUser: { value: function (projectUser, prop, value) { console.log("ModifyProjectUser", { projectUser: projectUser, prop: prop, value: value, ctrl: this }); switch (prop) { case "editProject": projectUser["edit" + _projectConfig.moduleName] = projectUser["edit" + _projectConfig.moduleName] || value; break; case "edit" + _projectConfig.moduleName: projectUser.editProject = projectUser.editProject && value; break; } projectUser[prop] = value; } }, loadProjectAndUsers: { value: function (project) { _project = project; return this.getProjectUsers(project) .then(function (projectUsers) { _projectUsers = projectUsers; return { project: project, projectUsers: projectUsers }; }); } }, saveProjectUsers: { value: function (project, projectUsers) { return _service.saveProjectUsers({ project: project, projectUsers: projectUsers }); } }, addLoadedUsers: { value: function (users) { _.array(users).forEach(function (user) { _projectUsers.push({ user: user, readOnly: true }); }); } }, removeLoadedUsers: { value: function (users) { _projectUsers.remove(function (pu) { return _.array(users).any(function (u) { return u.username === pu.user.username; }); }); } } }); return ProjectSecurityManager; })(); var projects = projects || {}; projects.ProjectSecurityService = (function () { "use strict"; var _http; var _config; var _user; var _userRoles; var _moduleName; var _projectConfig; function ProjectSecurityService(config, moduleName, $http, projectConfig) { var sv = this; _http = $http; _config = config; _user = config.user; _userRoles = config.userRoles; _moduleName = moduleName; _projectConfig = projectConfig; EntityServiceBase.call(sv, config, $http); //console.log("PROJECT_SECURITY_SERVICE", { service: sv, config: config }); } ProjectSecurityService.prototype = Object.create(EntityServiceBase.prototype, { constructor: { value: ProjectSecurityService }, // roles isAuthorized: { value: function () { return !_config.securityEnabled || _userRoles.any(function (role) { return role.roleName === "module_" + _moduleName }); } }, canRead: { value: function (project) { return !_config.securityEnabled || this.isAdministrator() || (this.isProjectLeider() && project.createdBy === _user) || _userRoles.any(function (role) { return role.roleName === _moduleName + "_project_" + project.id; }); } }, canCreate: { value: function () { return !_config.securityEnabled || this.isAdministrator() || this.isProjectLeider(); } }, canEdit: { value: function (project) { if (project == null) { return false; } return !_config.securityEnabled || this.isAdministrator() || (!project.isLocked && (this.isProjectLeider() && project.createdBy === _user)) || (!project.isLocked && _userRoles.any(function (role) { return role.roleName === _moduleName + "_project_" + project.id + "_edit" })); } }, canEditModule: { value: function (project) { if (project == null) { return false; } return !_config.securityEnabled || this.isAdministrator() || (!project.isLocked && (this.isProjectLeider() && project.createdBy === _user)) || (!project.isLocked && _userRoles.any(function (role) { return role.roleName === _moduleName + "_project_" + project.id + "_edit_" + _moduleName })); } }, isAdministrator: { value: function () { return !_config.securityEnabled || _userRoles.any(function (role) { return role.roleName === _moduleName + "_beheer_beheerder"; }); } }, isProjectLeider: { value: function () { return !_config.securityEnabled || _userRoles.any(function (role) { return role.roleName === _moduleName + "_beheer_projectleider"; }); } }, // crud saveProjectUsers: { // { project, projectUsers } value: function (o) { var sv = this; if (_config.saveProjectUsers) { return _config.saveProjectUsers(o); } return _http .post(_config.saveProjectUsersUrl.replace(/\{projectId\}/g, o.project.id), { usernamesReadOnly: o.projectUsers .where(function (x) { return !x.editProject && !x["edit" + _projectConfig.moduleName]; }) .select(function (x) { return x.user.username; }), usernamesEditProject: o.projectUsers .where(function (x) { return x.editProject; }) .select(function (x) { return x.user.username; }), ["usernamesEdit" + _projectConfig.moduleName]: o.projectUsers .where(function (x) { return x["edit" + _projectConfig.moduleName]; }) .select(function (x) { return x.user.username; }) }) .then(sv._getResponseData); } }, getProjectUsers: { value: function (project) { if (_config.getProjectUsers) { return _config.getProjectUsers(project); } return _http.get(_config.getProjectUsersUrl.replace(/\{projectId\}/g, project.id)) .then(function (response) { var data = response.data; return data.editProject .select(function (user) { return { user: user, editProject: true }; }) .concat(data["edit" + _projectConfig.moduleName].select(function (user) { return { user: user, ["edit" + _projectConfig.moduleName]: true } })) .concat(data.readOnly.select(function (user) { return { user: user, readOnly: true } })) .groupBy(function (pu) { return pu.user.username; }) .select(function (gpu) { return { user: gpu.values.first().user, editProject: gpu.values.any(function (x) { return x.editProject; }), ["edit" + _projectConfig.moduleName]: gpu.values.any(function (x) { return x["edit" + _projectConfig.moduleName]; }), readOnly: gpu.values.any(function (x) { return x.readOnly; }) } }); }); } } }); return ProjectSecurityService; })("projects"); var projects = projects || {}; projects.projectUsersComponent = (function () { function ProjectUsersViewModel() { Object.defineProperties(this, { display: { writable: true }, canEditModuleTitleTranslationKey: { writable: true }, canEditModuleProperty: { writable: true }, project: { writable: true }, projectUsers: { writable: true }, onChange: { writable: true }, onRemove: { writable: true }, onAddNew: { writable: true } }); } Object.defineProperties(ProjectUsersViewModel.prototype, { handleChange: { value: function (e, projectUser, prop, value) { return this.onChange({ event: e, projectUser: projectUser, prop: prop, value: value }); } }, handleRemove: { value: function (e, projectUser) { return this.onRemove({ event: e, projectUser: projectUser }); } }, handleNew: { value: function (e) { return this.onAddNew({ event: e }); } }, displayUser: { value: function (projectUser) { return projectUser.user.displayName || projectUser.user.username; } } }); function projectUsersComponent(templateUrl) { return { controller: ProjectUsersViewModel, bindings: { display: "<", canEditModuleTitleTranslationKey: "<", canEditModuleProperty: "<", project: "<", projectUsers: "<", onChange: "&", onRemove: "&", onAddNew: "&" }, templateUrl: ["config", function (config) { return config.baseUrl + "/" + templateUrl + "?v=" + config.version; }] } } return projectUsersComponent; })(); var projects = projects || {}; projects.module = (function () { "use strict"; return angular.module("geoit.projects", []) .factory("projectConfig", ["$translate", function ($translate) { var projectConfig = { moduleName: 'Signalisatie' }; return projectConfig; }]) .factory("projectSecurityServiceFactory", ["$http", "projectConfig", function ($http, projectConfig) { return { create: function (config, moduleName) { return new projects.ProjectSecurityService(config, moduleName, $http, projectConfig); } } }]) .factory("projectSecurityManagerFactory", ["config", "projectConfig", "projectSecurityService", function (config, projectConfig, service) { return { create: function (moduleName) { return new projects.ProjectSecurityManager(config, moduleName, service, projectConfig); } } }]) .service("projectManager", function () { console.error("ProjectManager should be overriden"); }) .controller("projectSecurityController", ["projectSecurityManager", "config", function (manager, config) { return new projects.ProjectSecurityController(manager, config.user); }]) .component("projectUsers", projects.projectUsersComponent("Content/modules/projects/security/project-users.html")) .component("projectHeader", projects.projectHeaderComponent("Content/modules/projects/components/project-header.html")) .component("projectSelector", projects.projectListComponent("Content/modules/projects/components/project-selector.html")); })("projects"); var aansluitingen = aansluitingen || {}; aansluitingen.DiameterControlDirective = (function (moduleName) { function diameterControlDirective(config, $timeout, aansluitingenModuleService) { return { restrict: "EA", scope: { item: "=", property: "<", validator: "=", disabled: "=", change: "&" }, templateUrl: config.baseUrl + "/content/modules/" + moduleName + "/_controls/diameter-control.html?v=" + config.version, link: function ($scope, $el, $attr) { if (!$el.hasClass('diameter-control')) { $el.addClass('diameter-control'); } var focus = function () { $el.find($scope.isCustom() ? 'input' : 'select').focus(); } Object.defineProperties($scope, { moduleData: { value: aansluitingenModuleService.data }, toggleCustom: { value: function () { if ($scope.item) { aansluitingenModuleService.toggleDiameterCustom($scope.item, $scope.property); } } }, isCustom: { value: function () { return $scope.item && aansluitingenModuleService.diameterIsCustom($scope.item, $scope.property); } }, changed: function () { if ($scope.change) { $timeout(function () { $scope.change.call($scope, { item: $scope.item, property: $scope.property }); }); } } }); //#5391: niet via ng-click want IOS booo: http://stinaq.me/blog/2016/04/19/setting-focus-on-element-programmatically-in-angular-on-ios/ $el.on('click', '.toggle-button', function () { $scope.toggleCustom(); $scope.$apply(); setTimeout(focus, 100); focus(); }); } } } diameterControlDirective.$inject = ["config", "$timeout", "aansluitingenModuleService"]; return diameterControlDirective; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.StraatSelectorDirective = (function (moduleName) { function straatSelectorDirective(config, $timeout, aansluitingenModuleService, crabService) { return { restrict: "EA", scope: { item: "=", property: "<", gemeente: "<", getStraten: "=", validator: "=", disabled: "=", change: "&" }, templateUrl: config.baseUrl + "/content/modules/" + moduleName + "/_controls/straat-selector.html?v=" + config.version, link: function ($scope, $el, $attr) { if (!$el.hasClass('straat-selector')) { $el.addClass('straat-selector'); } var focus = function () { $el.find($scope.isCustom ? '.custom-input' : '.autocomplete-input').focus(); } Object.defineProperties($scope, { moduleData: { value: aansluitingenModuleService.data }, toggleCustom: { value: function () { if ($scope.item) { var customProperty = aansluitingenModuleService.getCustomPropertyName($scope.property); $scope.item[customProperty] = !$scope.item[customProperty]; if (!$scope.item[customProperty] && $scope.item[$scope.property]) { crabService.findGemeente({ naam: $scope.gemeente }) .then(function (gemeente) { return crabService.listStraten({ gemeente: gemeente, term: $scope.item[$scope.property] }); }) .then(function (straten) { if (straten.length === 0) { $timeout(function () { $scope.item[$scope.property] = ''; }); } }); } } } }, isCustom: { get: function () { var customProperty = aansluitingenModuleService.getCustomPropertyName($scope.property); return $scope.item && $scope.item[customProperty]; } }, changed: function () { if ($scope.change) { $timeout(function () { $scope.change.call($scope, { item: $scope.item, property: $scope.property }); }); } } }); $scope.autocomplete = { source: function (request, response) { $scope.getStraten($scope.gemeente, request.term) .then(function(straten) { response(straten); }); }, change: function(arg) { //console.log('straat.change', arg); $scope.item[$scope.property] = arg.item ? arg.item.label : null; }, select: function(arg) { //console.log('straat.select', arg); $scope.item[$scope.property] = arg.item ? arg.item.label : null; } }; //#5391: niet via ng-click want IOS booo: http://stinaq.me/blog/2016/04/19/setting-focus-on-element-programmatically-in-angular-on-ios/ $el.on('click', '.toggle-button', function () { $scope.toggleCustom(); $scope.$apply(); setTimeout(focus, 100); focus(); }); } } } straatSelectorDirective.$inject = ["config", "$timeout", "aansluitingenModuleService", "crabService"]; return straatSelectorDirective; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.AansluitingenEntityControllerBase = (function (moduleName) { "use strict"; function AansluitingenEntityControllerBase(service, config, $timeout, $translate, aansluitingenConfig, aansluitingenModuleService) { EntityControllerBase.call(this, service); var vm = this; Object.defineProperties(vm, { _config: { value: config }, _timeout: { value: $timeout }, _translate: { value: $translate }, _aansluitingenConfig: { value: aansluitingenConfig }, _aansluitingenModuleService: { value: aansluitingenModuleService } }); } AansluitingenEntityControllerBase.injectInto = function(target) { Object.defineProperties(target, { moduleData: { get: function() { return this._aansluitingenModuleService.data; } } }); }; AansluitingenEntityControllerBase.prototype = Object.create(EntityControllerBase.prototype, { constructor: { value: AansluitingenEntityControllerBase } }); AansluitingenEntityControllerBase.injectInto(AansluitingenEntityControllerBase.prototype); return AansluitingenEntityControllerBase; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.AansluitingenEntityServiceBase = (function () { "use strict"; function AansluitingenEntityServiceBase(aansluitingenConfig, entityName, $http) { EntityServiceBase.call(this, { niscode: aansluitingenConfig.niscode, url: aansluitingenConfig.aansluitingenBaseUrl + entityName }, $http); this._config = aansluitingenConfig; } AansluitingenEntityServiceBase.prototype = Object.create(EntityServiceBase.prototype, { constructor: { value: AansluitingenEntityServiceBase }, _processItem: { value: function (item) { if (item && typeof (item) === "object") { this.fillNaam(item); } return Promise.resolve(item); } }, getNaamLanguagePropertyName: { value: function() { var taalcode = this._config.taalcode; return 'naam' + taalcode[0].toUpperCase() + taalcode[1].toLowerCase(); } }, fillNaam: { value: function (item) { if (item && typeof (item) === "object" && item.naamNl !== undefined) { item.naam = this.getNaam(item); } return item; } }, getNaam: { value: function(item) { if (item.naam === undefined && item.naamNl !== undefined) { var naamProperty = this.getNaamLanguagePropertyName(); return item[naamProperty] || item.naamNl; } return item.naam; } }, details: { value: function (o) { var id = o.id || o; var sv = this; return sv._post({ action: "details", So: { Id: id } }) .then(function (response) { return sv._processItem(response.data); }); } }, list: { value: function (o) { var sv = this; o = o || {}; o.taalcode = sv._config.taalcode; return sv._post({ action: "list", So: o }) .then(function (response) { var items = Promise.all(response.data.select(function(x) {return sv._processItem(x); })); //console.log("SERVICE.LIST", { response: response, items: response.data, processed: items }); return items; }); } }, count: { value: function (o) { var sv = this; o = o || {}; o.taalcode = sv._config.taalcode; return sv._post({ action: "count", So: o }) .then(function (response) { return response.data; }); } }, beforeSave: { value: function (item) { } }, save: { value: function (item) { var sv = this; sv.beforeSave(item); return sv._post({ action: "save", niscode: sv._niscode, item: item }) .then(function (response) { var item = response.data; return item ? sv._processItem(item) : null; }); } }, remove: { value: function (item) { var sv = this; return sv._post({ action: "delete", niscode: sv._niscode, item: item }) .then(function (response) { return sv._processItem(response.data); }); } } }); return AansluitingenEntityServiceBase; })(); var aansluitingen = aansluitingen || {}; aansluitingen.AansluitingContainerController = (function (moduleName) { "use strict"; var inject = ["config", "$timeout", "$translate", "aansluitingenConfig", "aansluitingenService", "aansluitingenAansluitingService", "aansluitingenModuleService", "aansluitingenOverviewService", "panelManager", "projectService", "projectManager", "aansluitingenAansluitingStukService", "gisViewerManager", "printService", "formatDateFilter", "printManager", "numberUtils"]; function AansluitingContainerController(config, $timeout, $translate, aansluitingenConfig, aansluitingenService, service, aansluitingenModuleService, aansluitingenOverviewService, panelManager, projectService, projectManager, aansluitingenAansluitingStukService, gisViewerManager, printService, formatDate, printManager, numberUtils) { aansluitingen.AansluitingenEntityControllerBase.call(this, service, config, $timeout, $translate, aansluitingenConfig, aansluitingenModuleService); var vm = this; Object.defineProperties(vm, { _aansluitingenConfig: { value: aansluitingenConfig }, _aansluitingenService: { value: aansluitingenService }, _panelManager: { value: panelManager }, _projectService: { value: projectService }, _projectManager: { value: projectManager }, _aansluitingenOverviewService: { value: aansluitingenOverviewService }, _aansluitingenAansluitingStukService: { value: aansluitingenAansluitingStukService }, _viewer: { value: gisViewerManager }, _printService: { value: printService }, _formatDate: { value: formatDate }, _printManager: { value: printManager }, utils: { value: { number: numberUtils } }, filter: { value: { projectId: null, q: null, isLocked: null, hasPrintLocation: null } }, _onDisplayChanged: { value: function (value) { var vm = this; return aansluitingen.AansluitingenEntityControllerBase.prototype._onDisplayChanged.apply(vm, arguments) .then(function (value) { return vm._aansluitingenOverviewService.setActiveEntityDisplay(value); }); }, configurable: true }, data: { value: Object.defineProperties({}, { projects: { value: null, writable: true }, project: { value: null, writable: true }, showOnderdelenBijlages: { get: function () { return this._showOnderdelenBijlages || false; }, set: function (value) { this._showOnderdelenBijlages = value; vm._showOnderdelenBijlagesChanged(value); } }, list: { //sorting value: {}, writable: true }, ficheProfielTypes: { value: ['zijkant', 'bovenaan'] }, vlarioTypeAansluitingen: { value: ['T-buis', 'T-stuk', 'Y-stuk', 'Flexibele aansluiting', 'Aanboring'] }, vlarioBeschrijvingLiggingen: { value: ['Oprit', 'Voortuin', 'Berm', 'Voetpad', 'Fietspad'] }, vlarioInfiltratiePutten: { value: ['Ja', 'Nee'] }, vlarioGrachtAansluitingen: { value: ['Ja', 'Nee'] }, vlarioRioleringPlaatsen: { value: ['90', '135', '180', '225', '270', 'NVT'] }, vlarioHorizontaal: { value: ['a', 'b', 'c', 'd', 'e', 'f', 'u', 'v', 'w', 'x', 'y', 'z'] }, vlarioVerticaal: { value: ['g', 'h', 'm', 'n'] }, floatProperties: { value: ['afstandDichtstbijzijndePut', 'liggingTovRechterGevel', 'rooilijnDiepte', 'rooilijnToezicht'] } }) } }); aansluitingenOverviewService.on("init", function (e, arg) { switch (arg.display) { case "aansluitingen": { return vm.init(arg); } } return Promise.resolve(); }); } AansluitingContainerController.$inject = inject; AansluitingContainerController.prototype = Object.create(aansluitingen.AansluitingenEntityControllerBase.prototype); //EventHandler.injectInto(AansluitingContainerController.prototype); Object.defineProperties(AansluitingContainerController.prototype, { constructor: { value: AansluitingContainerController }, _entityType: { value: moduleName + "AansluitingContainer" }, init: { value: function (o) { var vm = this; if (!o) o = {}; vm.setDisplay("list"); vm.selected = null; vm.filter.projectId = vm._aansluitingenOverviewService.data.project.id; vm.countFilter.projectId = vm.filter.projectId; vm.printTemplates = vm._aansluitingenModuleService.data.printTemplates; return EntityControllerBase.prototype.init.apply(vm) .then(function (result) { if (o.aansluitingId) { return vm.show(o.aansluitingId, 'form'); //vm.setSelectedId(o.aansluitingId); //if (vm.selected) { // return vm.showAansluitingStukken(o); //} } else if (vm._aansluitingenOverviewService.data.aansluiting) { vm.setSelectedId(vm._aansluitingenOverviewService.data.aansluiting.id); vm._aansluitingenOverviewService.data.aansluiting = vm.selected; } vm._aansluitingenOverviewService.data.aansluitingStuk = null; return result; }); } }, _ignoreFilterKeys: { value: ["taalcode", "projectId"], writable: true }, canEdit: { value: function () { var vm = this; var project = vm._aansluitingenOverviewService.data.project; return project && !project.isLocked && vm._aansluitingenModuleService.canEditAansluitingen(project); } }, isVlario: { value: function () { var vm = this; return vm._aansluitingenOverviewService.isVlario(); } }, itemIsValid: { value: function (item) { return item.geometry != null && item.geometry.wkt != null; } }, addIsVisible: { value: function () { var vm = this; return EntityControllerBase.prototype.addIsVisible.apply(this, arguments) && vm.canEdit(); } }, editIsVisible: { value: function () { var vm = this; return EntityControllerBase.prototype.editIsVisible.apply(this, arguments) && vm.canEdit(); } }, listEditIsVisible: { value: function (item) { var vm = this; return EntityControllerBase.prototype.listEditIsVisible.apply(this, arguments) && vm.canEdit(); } }, _show: { value: function (item) { EntityControllerBase.prototype._show.apply(this, arguments); if (!item) { return item; } var vm = this; var id = item.id || 0; item.isNew = id <= 0; vm.itemIsEditable = vm.canEdit(item); if (!vm.itemIsEditable) { item.isLocked = true; } vm._aansluitingenOverviewService.data.aansluiting = item; //alleen bij het openen if (!vm._isSaving) { vm.data.projects = vm._projectManager.items; vm.data.project = vm._aansluitingenOverviewService.data.project; vm.data.showOnderdelenBijlages = false; vm.data.filesStukken = []; if (item.ficheProfielen === undefined || item.ficheProfielen === null) { item.ficheProfielen = true; } if (vm.data.project.ficheEigenProfielen && (item.ficheEigenProfielen === undefined || item.ficheEigenProfielen === null)) { item.ficheEigenProfielen = true; } if (!item.ficheProfielType) { item.ficheProfielType = vm.data.ficheProfielTypes.first(); } } var project = vm.data.project; if (item.isNew) { item.projectId = project.id; item.datumUitvoering = vm._formatDate(new Date()); } else { item.datumUitvoering = vm._formatDate(item.datumUitvoering); item.vlarioDatumUitvoering = vm._formatDate(item.vlarioDatumUitvoering); } if (!item.geometry) { item.geometry = {}; } if (!item.files) { item.files = []; } if (!item.filesEigenProfielen) { item.filesEigenProfielen = []; } if (!item.rioolDocumenten) { item.rioolDocumenten = []; } if (!item.omhullingDocumenten) { item.omhullingDocumenten = []; } if (!item.tssDocumenten) { item.tssDocumenten = []; } if (!item.funderingDocumenten) { item.funderingDocumenten = []; } if (!item.bijlagen) { item.bijlagen = []; } if (project.locaties && !item.locatie) { if (item.gemeente) { item.locatie = project.locaties.where(function (x) { return x.gemeente === item.gemeente && x.straat === item.straat; }).first(); } else if (project.locaties.length === 1 && item.isNew) { item.locatie = project.locaties.first(); vm.locatieChanged(item); } } vm._aansluitingenModuleService.initDiameterCustom(item, ["defaultDiameter"]); vm.data.floatProperties.forEach(function (property) { item[property] = vm.utils.number.floatToString(item[property]); }); return item; }, enumerable: true, configurable: true }, getGeom: { value: function (item) { return item?.geometry?.wkt }, configurable: true }, _validating: { value: function (o) { var vm = this; var item = o.item || vm.item; if ($(".aansluitingprintsetting-container").is(':visible')) { return vm._translate('aansluitingen.ClosePrintSettingsFirst') .then(function (msg) { throw msg; }); } if (!vm.isVlario()) { vm.validator.validateTarget(vm.validator.isRequired, item, "locatie", 'LocationIsRequired'); vm.validator.validateTarget(vm.validator.isRequired, item, "soort", 'SoortIsRequired'); vm.validator.validateTarget(vm.validator.isRequired, item, "bestemming", 'BestemmingIsRequired'); vm.validator.validateTarget(vm.validator.isRequired, item, "defaultDiameter", 'DiameterIsRequired'); vm.validator.validateTarget(vm.validator.isRequired, item, "defaultMateriaal", 'MaterialIsRequired'); vm.validator.validateTarget(vm.validator.isRequired, item, "nr", 'NumberIsRequired'); vm.validator.validateTarget(vm.validator.isRequired, item, "datumUitvoering", 'DateIsRequired'); } else { vm.validator.validateTarget(vm.validator.isRequired, item, "vlarioBestemming", 'BestemmingIsRequired'); vm.validator.validateTarget(vm.validator.isRequired, item, "vlarioSoort", 'SoortIsRequired'); //vm.validator.validateTarget(vm.validator.isRequired, item, "vlarioEquipmentNummer", 'EquipmentNummerIsRequired'); } vm.validator.validateTarget(vm.validator.isRequired, item, "geometry.wkt", 'WktRequired'); if (item.putId1 && item.putId2) { //validate if dichtsbijzijndeputid is een value van putid1 of putid2 if (item.dichtstbijzijndePutId && [item.putId1, item.putId2].indexOf(item.dichtstbijzijndePutId) === -1) { item.dichtstbijzijndePutId = null; } vm.validator.validateTarget(vm.validator.isRequired, item, "dichtstbijzijndePutId", 'aansluitingen.DichtstbijzijndePutIdIsRequired'); } else if (item.putId2) { vm.validator.validateTarget(vm.validator.isRequired, item, "putId1", 'aansluitingen.PutId1IsRequired'); } return Promise.resolve(); } }, _save: { value: function (o) { var vm = this o.saving.item = $.extend({}, o.saving.item); var item = o.saving.item; if (!item.putId1 && !item.putId2) { item.dichtstbijzijndePutId = null; } else if (item.putId1 && !item.putId2) { item.dichtstbijzijndePutId = item.putId1; } vm.data.floatProperties.forEach(function (property) { item[property] = vm.utils.number.stringToFloat(item[property]); }); item.files = (item.files || []).where(function (x) { return !x.removed; }); item.filesEigenProfielen = (item.filesEigenProfielen || []).where(function (x) { return !x.removed; }); item.rioolDocumenten = (item.rioolDocumenten || []).where(function (x) { return !x.removed; }); item.funderingDocumenten = (item.funderingDocumenten || []).where(function (x) { return !x.removed; }); item.tssDocumenten = (item.tssDocumenten || []).where(function (x) { return !x.removed; }); item.omhullingDocumenten = (item.omhullingDocumenten || []).where(function (x) { return !x.removed; }); item.bijlagen = (item.bijlagen || []).where(function (x) { return !x.removed; }); item.soortId = item.soort ? item.soort.id : 0; item.bestemmingId = item.bestemming ? item.bestemming.id : 0; return EntityControllerBase.prototype._save.call(vm, o); } }, _cancel: { value: function (canceling) { var vm = this; if ($(".aansluitingprintsetting-container").is(':visible')) { return vm._translate('aansluitingen.ClosePrintSettingsFirst') .then(function (msg) { throw msg; }); } return Promise.resolve(); }, configurable: true }, _afterCancel: { value: function (result) { var vm = this; if (vm._service.forceListRefresh()) { return vm.load() .then(function () { return result; }); } return Promise.resolve(result); }, configurable: true }, _afterSave: { value: function () { var vm = this; return EntityControllerBase.prototype._afterSave.apply(vm, arguments) .then(function (result) { return vm._viewer.refreshMap() .then(function () { vm.showAansluitingStukken(); return result; }); }); } }, _afterRemove: { value: function () { var vm = this; return EntityControllerBase.prototype._afterRemove.apply(vm, arguments) .then(function (result) { return vm._viewer.refreshMap() .then(function () { return result; }); }); } }, editGeometryAndSave: { value: function (item) { var ctrl = this; ctrl.validator.checkError(item, 'geometry.wkt'); EntityControllerBase.prototype.details.call(ctrl, item.id).then(function (returnItem) { returnItem.geometry.wkt = item.geometry.wkt; //var aansluiting = ctrl._show(returnItem); //ctrl.save(returnItem); 20/07/2022 - nick: geen idee wrm ik in der tijd dacht dat dit nodig was? ik laat het even staan voor de zekerheid }) } }, setSelectedId: { value: function (id) { var vm = this; var item = id ? vm.items.where(function (x) { return x.id === id; }).first() : null; return vm.setSelected(item); } }, setSelected: { value: function (item) { var vm = this; vm.selected = item; if (item) { vm._aansluitingenOverviewService.data.aansluiting = item; } } }, showAansluitingStukken: { value: function (o) { var vm = this; vm._aansluitingenOverviewService.display = 'aansluitingstukken'; return vm._aansluitingenOverviewService.init(o); } }, exportAansluiting: { value: function (item) { if (!item) { return null; } var vm = this; var state = vm.stateManager.addState("loading"); return vm._aansluitingenService.exportAansluiting({ id: item.id }).then(function (file) { return vm._aansluitingenModuleService.getExportFileNameAansluiting(item).then(function (fileName) { var url = config.baseUrl + "/Handlers/FileHandler.aspx?action=download&file=" + encodeURIComponent(file) + "&delete=1&clientfile=" + encodeURIComponent(fileName) + ".xlsx"; if (!window.open(url, "_blank")) { return vm._translate('global.PopupBlockedWarning') .then(function (msg) { throw msg; }); } return url; }); }) .then(state.completed) .catch(function (error) { state.error(error); vm.handleError(error); }); } }, printAansluiting: { value: function (aansluitingId, o) { var vm = this; var state = vm.stateManager.addState("loading"); return vm._printManager.printAansluiting(aansluitingId, o) .then(state.completed) .catch(function (error) { state.error(error); vm.handleError(error); }); } }, locatieChanged: { value: function (item) { if (item.locatie) { item.gemeente = item.locatie.gemeente; item.straat = item.locatie.straat; item.vlarioGemeente = item.locatie.gemeente; item.vlarioStraat = item.locatie.straat; } } }, bestemmingChanged: { value: function (item) { var vm = this; if (item.bestemming || item.vlarioBestemming) { var bestemmingId = item.bestemming?.id ?? item.vlarioBestemming.id; var project = vm.data.project; var bestemmingDefault = project.bestemmingDefaults.where(function (x) { return x.bestemmingId === bestemmingId; }).first(); if (bestemmingDefault) { item.defaultDiameter = bestemmingDefault.diameter; item.defaultMateriaal = vm._aansluitingenModuleService.data.materiaalItems.where(function (x) { return x.id === bestemmingDefault.materiaalId; }).first(); item.vlarioDiameter = bestemmingDefault.diameter; item.vlarioDefaultMateriaal = item.defaultMateriaal; } } } }, _showOnderdelenBijlagesChanged: { value: function (value) { var vm = this; vm.data.filesStukken = []; if (value) { var state = vm.stateManager.addState("loading"); var aansluitingId = vm.item.id || 0; var filesStukken = []; vm._aansluitingenAansluitingStukService.list({ AansluitingId: aansluitingId }).then(function (items) { return vm._fillAllfilesStukken(aansluitingId, null, null, items, filesStukken); }).then(function (result) { vm.data.filesStukken = filesStukken; return result; }) .then(state.completed) .catch(function (error) { state.error(error); throw error; }); } } }, _fillAllfilesStukken: { value: function (aansluitingId, parentId, parentNr, items, allFiles) { if (!items || !items.any()) { return Promise.resolve(); } var vm = this; allFiles.addRange(items.selectMany(function (x) { return (x.files || []) })); //.select(function (y) { return convertBijlageItemToFile(y); }); })); var funcs = items.where(function (x) { return x.supportChildren; }).select(function (item) { return function () { return vm._aansluitingenAansluitingStukService.list({ AansluitingId: aansluitingId, ParentAansluitingStukId: item.id }).then(function (items) { return vm._fillAllfilesStukken(aansluitingId, item.id, parentNr ? parentNr + '.' + (item.index + 1) : (item.index + 1), items, allFiles); }); }; }); return funcs.aggregate(function (r, x) { return r.then(function () { return x(); }); }, Promise.resolve()); } }, returnToPrevious: { value: function () { var vm = this; vm._aansluitingenOverviewService.display = 'projecten'; } }, getExportFileNameAttachments: { value: function (item) { var vm = this; return vm._aansluitingenModuleService.getExportFileNameAansluiting(item) .then(function (fileName) { return vm._translate('global.Attachments').then(function (translated) { return fileName + ' - ' + translated; }); }); } }, getExportFileNameStukkenAttachments: { value: function (item) { var vm = this; return vm._aansluitingenModuleService.getExportFileNameAansluiting(item) .then(function (fileName) { return vm._translate('aansluitingen.StukkenAttachments').then(function (translated) { return fileName + ' - ' + translated; }); }); } }, getExportFileNameEigenProfielen: { value: function (item) { var vm = this; return vm._aansluitingenModuleService.getExportFileNameAansluiting(item) .then(function (fileName) { return vm._translate('aansluitingen.EigenProfielen').then(function (translated) { return fileName + ' - ' + translated; }); }); } } }); return AansluitingContainerController; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.AansluitingFormDirective = (function (moduleName) { function AansluitingFormDirective() { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, scope: { ctrl: "=" }, link: function ($scope, $el) { } }; } AansluitingFormDirective.$inject = []; return AansluitingFormDirective; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.AansluitingService = (function (moduleName) { "use strict"; function AansluitingService(aansluitingenConfig, $http, aansluitingenModuleService) { aansluitingen.AansluitingenEntityServiceBase.call(this, aansluitingenConfig, "Aansluiting", $http); this.aansluitingenModuleService = aansluitingenModuleService; } AansluitingService.$inject = ["aansluitingenConfig", "$http", "aansluitingenModuleService"]; AansluitingService.prototype = Object.create(aansluitingen.AansluitingenEntityServiceBase.prototype, { constructor: { value: AansluitingService }, _data: { value: { forceListRefresh: false } }, _processItem: { value: function (item) { if (item && typeof (item) === "object") { this.fillNaam(item.bestemming); this.fillNaam(item.soort); } if (item.vlarioSoortId) { item.vlarioSoort = this.aansluitingenModuleService.data.soortItems.where(function (x) { return x.id === item.vlarioSoortId; }).first(); } if (item.vlarioBestemmingId) { item.vlarioBestemming = this.aansluitingenModuleService.data.bestemmingItems.where(function (x) { return x.id === item.vlarioBestemmingId; }).first(); } if(item.vlarioDefaultMateriaalId) { item.vlarioDefaultMateriaal = this.aansluitingenModuleService.data.materiaalItems.where(function (x) { return x.id === item.vlarioDefaultMateriaalId; }).first(); } return Promise.resolve(item); } }, list: { value: function () { var sv = this; return aansluitingen.AansluitingenEntityServiceBase.prototype.list.apply(sv, arguments) .then(function(result) { sv.forceListRefresh(false); return result; }); } }, forceListRefresh: { value: function (value) { var sv = this; if (value !== undefined) { sv._data.forceListRefresh = value === true; } return sv._data.forceListRefresh; } } }); return AansluitingService; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.Bootstrapper = (function (moduleName) { "use strict"; function Bootstrapper(config, projectManager, infoManager, $timeout, $scope) { var bs = this; //console.log("ROOTSCOPE", { scope: $scope, timeout: $timeout, config: config }); //this.initLanguage = function (aansluitingenModuleService) { // $scope.$on("$translateChangeEnd", function (e, arg) { // aansluitingenModuleService.init(); // }); // return Promise.resolve(bs); //}; this.initProjectData = function (indexService, aansluitingenModuleService, aansluitingenOverviewService) { // project events projectManager // active project changed .on("change-active-item", function (e, arg) { var t0 = performance.now(); return Promise.resolve() .then(function() { if (arg.hasChanged) { //console.debug("SB.PROJECT", { project: arg.activated }); indexService.saveUserLastProjectId((arg.activated || {}).id); if (arg.activated) { aansluitingenModuleService.refreshCategorieItems(arg.activated.id); } if (aansluitingenOverviewService.display === 'projecten') { aansluitingenOverviewService.display = 'aansluitingen'; aansluitingenOverviewService.init(); } } return arg; }) .then(function(result) { var t1 = performance.now(); //console.log("PERFORMANCE", Math.round(t1 - t0), "ProjectManager[change-active-item].Aansluitingen[ProjectData]"); return result; }); }); return projectManager .init({ roleRequired: true }) .then(function () { return bs; }); }; this.initProjectGis = function (gisViewer, projectGisManager) { projectManager //.on("change-active-item", function (e, arg) { // //console.log("NB.CHANGE_ACTIVE_PROJECT", { evt: e, arg: arg }); // notitieManager.setProject(arg.activated); // if (arg.activated === null && arg.deactivated === null) { // // initial load without active project // notitieGisManager.filterItems({ projectId: null }); // } // notitieManager.load(); //}) // loaded items changed .on("change-loaded-items", function (e, arg) { //console.log("NB.CHANGE_LOADED_PROJECTS", { evt: e, arg: arg }); var t0 = performance.now(); var projectIds = arg.items.select(function (x) { return x.id; }); return projectGisManager.filterItems({ projectId: projectIds.length ? projectIds : null }) .then(function (result) { var t1 = performance.now(); //console.log("PERFORMANCE", Math.round(t1 - t0), "ProjectManager[change-loaded-items].Aansluitingen[ProjectGisManager.filter]"); return result; }); }) // zoom to project(s) .on("request-extents", function (e, arg) { //console.debug("SBP.REQUEST_EXTENTS", { arg: arg }); var projects = arg.items; var projectIds = projects.select(function (x) { return x.id; }); return projectGisManager.getExtent({ projectIds: projectIds }) .then(function (extent) { arg.addExtent(extent); return extent; }); }) .on("focus", function (e, arg) { //console.debug("SBP.FOCUS", { arg: arg }); return gisViewer.zoomToExtent({ bounds: arg.bounds }); }); return Promise.resolve(bs); }; this.initCommands = function (commandBag, $translate) { commandBag.add([{ name: moduleName + ".Open", content: '', title: function () { return $translate("aansluitingen.Aansluitingen"); } }, { name: moduleName + ".Projects", content: '', title: function () { return $translate("global.Projects"); } }]); return Promise.resolve(bs); }; this.initPanels = function (commandBag) { var panelManager = new PanelManager($(".content-container")); function disableProjectPanel() { panelManager.freezePanel($("#ProjectContainer")); panelManager.disablePanel("right"); commandBag.disable(commandBag.items.where(function (x) { var toIgnore = "security.User,gislegend.Legend,TrackMyLocation,crab.SearchAddress,ZoomIn,ZoomOut,InitialExtent".split(","); return !toIgnore.contains(x.name); })); } function enableProjectPanel() { panelManager.unfreezePanel($("#ProjectContainer")); panelManager.enablePanel("right"); commandBag.enableAll(); } projectManager .on("change-display", function (e, arg) { if (arg.display === "form") { disableProjectPanel(); } else { enableProjectPanel(); } }); return Promise.resolve(bs); }; this.initElements = function (commandBag, projectManager, $compile) { var pm = new PanelManager($(".content-container")); var projectContainer = $('
').hide(); $compile(projectContainer)($scope).appendTo($(".panel-bottom")); commandBag .on("execute", moduleName + ".Projects", function () { pm.show($("#ProjectContainer"), "bottom"); projectManager.setDisplay('list'); }); return Promise.resolve(bs); }; this.initCss = function () { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); return Promise.resolve(bs); }; this.initPrint = function (printService) { printService .on("before-print", function (e, arg) { var project = projectManager.activeItem; //console.log("SM.PRINTING", { evt: e, arg: arg, project: project }); if (project) { arg.addParameter("TITLE", project.title); arg.addParameter("CODE", project.code); //arg.clientFilename = "print-" + project.code + "-" + arg.template.Name + "-" + moment().format("YYYYMMDDhhmmss") + ".pdf"; } }); return Promise.resolve(bs); }; this.initSecurity = function (projectSecurityManager, userManager) { //projectManager // // active project changed // .on("change-active-item", function (e, arg) { // //console.log("SECURITY.CHANGE_PROJECT", { evt: e, arg: arg }); // var t0 = performance.now(); // return projectSecurityManager.loadProjectAndUsers(arg.activated) // .then(function (result) { // var t1 = performance.now(); // //console.log("PERFORMANCE", Math.round(t1 - t0), "ProjectManager[change-active-item].Aansluitingen[Security]"); // return result; // }); // }); return userManager.list() .then(function () { return Promise.resolve(bs); }); }; this.initHashEvents = function (locationHashHelper, commandBag) { var hashEvents = (function () { return { zoomProject: [function () { if (projectManager.activeItem != null) { return projectManager.focus(projectManager.activeItem); } return false; }], project: [function(e) { //console.log("LOCATION_CHANGED", { url: newUrl, project: projectCode }); if (e.project) { projectManager.activateByFilter({ code: e.project }); } }] }; })(); locationHashHelper.addHashchangeEvents(hashEvents); return Promise.resolve(bs); }; this.initToolbar = function (toolbarService) { return toolbarService .buildTree([ "Home", "security.User", "separator", moduleName + ".Projects", moduleName + ".Open", "notities.Open", "schetsen.Open", "dwf.Open", "separator", "Print", "measure.Measure", "crab.SearchAddress", "TrackMyLocation", "featureinfo.ShowSelection", "gislegend.Legend" ].where(function (x) { return x != null; })) .then(function () { return bs; }); }; } return Bootstrapper; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.AansluitingenService = (function (moduleName) { "use strict"; function AansluitingenService(config, $http) { EntityServiceBase.call(this, { niscode: config.niscode, url: config.baseUrl + "/GeoRest/Aansluitingen" }, $http); } AansluitingenService.$inject = ["aansluitingenConfig", "$http"]; AansluitingenService.prototype = Object.create(EntityServiceBase.prototype, { constructor: { value: AansluitingenService }, updateProjectRoleDisplayName: { value: function (o) { var sv = this; return sv._post('UpdateProjectRoleDisplayName', o).then(sv._getResponseData); } }, saveProjectUsers: { value: function (o) { var sv = this; return sv._post('SaveProjectUsers', o).then(sv._getResponseData); } }, getProjectUsers: { value: function (o) { var sv = this; return sv._get('GetProjectUsers', o).then(sv._getResponseData); } }, getProjectBounds: { value: function (o) { var sv = this; return sv._get('GetProjectBounds', o).then(sv._getResponseData); } }, getAansluitingBounds: { value: function (o) { var sv = this; return sv._get('GetAansluitingBounds', o).then(sv._getResponseData); } }, importProject: { value: function (o) { var sv = this; return sv._post('ImportProject', o).then(sv._getResponseData); } }, exportProject: { value: function (o) { var sv = this; return sv._get('ExportProject', o).then(sv._getResponseData); } }, exportAansluiting: { value: function (o) { var sv = this; return sv._get('ExportAansluiting', o).then(sv._getResponseData); } }, getXsltTemplates: { value: function (o) { var sv = this; return sv._get("GetXsltTemplates", o).then(sv._getResponseData); } }, getAansluitingPrint: { value: function (o) { var sv = this; return sv._get('GetAansluitingPrint', o).then(sv._getResponseData); } } }); return AansluitingenService; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.AansluitingPrintSettingContainerController = (function (moduleName) { "use strict"; var inject = ["config", "$timeout", "$translate", "aansluitingenConfig", "aansluitingenService", "aansluitingenAansluitingPrintSettingService", "aansluitingenModuleService", "panelManager", "aansluitingenAansluitingService"]; function AansluitingPrintSettingContainerController(config, $timeout, $translate, aansluitingenConfig, aansluitingenService, service, aansluitingenModuleService, panelManager, aansluitingenAansluitingService) { aansluitingen.AansluitingenEntityControllerBase.call(this, service, config, $timeout, $translate, aansluitingenConfig, aansluitingenModuleService); var vm = this; Object.defineProperties(vm, { _aansluitingenService: { value: aansluitingenService }, _panelManager: { value: panelManager }, _aansluitingenAansluitingService: { value: aansluitingenAansluitingService }, printModule: { value: null, writable: true } }); } AansluitingPrintSettingContainerController.$inject = inject; AansluitingPrintSettingContainerController.prototype = Object.create(aansluitingen.AansluitingenEntityControllerBase.prototype); EventHandler.injectInto(AansluitingPrintSettingContainerController.prototype); Object.defineProperties(AansluitingPrintSettingContainerController.prototype, { constructor: { value: AansluitingPrintSettingContainerController }, _entityType: { value: moduleName + "AansluitingPrintSettingContainer" }, init: { value: function (o) { var vm = this; vm.filter.aansluitingId = o.aansluitingId; return vm.setDisplay("form") .then(function() { return EntityControllerBase.prototype.init.apply(vm).then(function (result) { vm.item = vm.items.first() || {}; return result; }); }); } }, _save: { value: function (o) { var vm = this; var item = o.saving.item; return vm.getPrintCenter().then(function (result) { var center = result[0]; if (!center) { return vm._translate("aansluitingen.InvalidLocation") .then(function (msg) { throw msg; }); } if (!_.isArray(center)) { center = result; } item.aansluitingId = vm.filter.aansluitingId; item.x = center[0]; item.y = center[1]; item.schaal = vm.printModule.item.PrintSchaal; item.dpi = vm.printModule.item.PrintDpi; item.orientation = vm.printModule.item.Rotate; return EntityControllerBase.prototype._save.call(vm, o) .then(function (result) { vm._aansluitingenAansluitingService.forceListRefresh(true); return result; }); }); } }, removeIsVisible: { value: function () { return false; } }, getPrintCenter: { value: function () { return this.trigger("get-print-center"); } } }); return AansluitingPrintSettingContainerController; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.AansluitingPrintSettingContainerDirective = (function () { function AansluitingPrintSettingContainerDirective($translate, aansluitingenModuleService) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, controller: aansluitingen.AansluitingPrintSettingContainerController, controllerAs: "ctrl", scope: {}, link: function ($scope, $el, $attr, $ctrl) { var vm = $ctrl; var globalScope = $scope.$parent; var printModule = globalScope.modules.print.root; vm.printModule = printModule; $el.on("hidden", function () { printModule.taskpane.hidden(); }); Object.defineProperties($scope, { close: { value: function () { globalScope.panels.hide($el); } } }); vm.on("get-print-center", function () { return printModule.getPrintCenter(); }); aansluitingenModuleService.on("request-show-print-settings", function (e, arg) { globalScope.panels.setMode('bottom', 'half'); var o = arg; globalScope.panels.show($el, 'right', 'half'); printModule.el.one("openprint", function (e, arg) { arg.templates = [o.template]; arg.templateId = o.template.Id; arg.schaal = o.schaal; arg.dpi = o.dpi; arg.rotate = o.rotate; }); printModule.taskpane.shown(); return vm.init(o); }); } }; } AansluitingPrintSettingContainerDirective.$inject = ["$translate", "aansluitingenModuleService"]; return AansluitingPrintSettingContainerDirective; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.AansluitingPrintSettingFormDirective = (function () { function AansluitingPrintSettingFormDirective() { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, scope: { ctrl: "=" }, link: function ($scope, $el) { var ctrl = $scope.ctrl; var printModule = ctrl.printModule; $el.find("#AansluitingPrintSettingSchaal").autocomplete({ appendTo: "parent", minLength: 1, autoFocus: false, source: function (request, response) { var schalen = printModule.config.schalen.orderBy(function (x) { return x; }).select(function (x) { return "" + x; }); response(schalen); }, select: function (e, arg) { if (arg.item) { $scope.$apply(function () { printModule.item.PrintSchaal = arg.item.value; printModule.scaleChanged(); }); } } }).on("focus", function () { $(this).autocomplete("search"); }).on("click", function () { $(this).autocomplete("search"); }); } }; } AansluitingPrintSettingFormDirective.$inject = []; return AansluitingPrintSettingFormDirective; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.AansluitingPrintSettingService = (function (moduleName) { "use strict"; function AansluitingPrintSettingService(aansluitingenConfig, $http) { aansluitingen.AansluitingenEntityServiceBase.call(this, aansluitingenConfig, "AansluitingPrintSetting", $http); } AansluitingPrintSettingService.$inject = ["aansluitingenConfig", "$http"]; AansluitingPrintSettingService.prototype = Object.create(aansluitingen.AansluitingenEntityServiceBase.prototype, { constructor: { value: AansluitingPrintSettingService } }); return AansluitingPrintSettingService; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.AansluitingStukContainerController = (function (moduleName) { "use strict"; var inject = ["config", "$timeout", "$translate", "aansluitingenConfig", "aansluitingenService", "aansluitingenAansluitingStukService", "aansluitingenModuleService", "aansluitingenOverviewService", "panelManager", "projectService", "gisViewerManager", "numberUtils"]; function AansluitingContainerStukController(config, $timeout, $translate, aansluitingenConfig, aansluitingenService, service, aansluitingenModuleService, aansluitingenOverviewService, panelManager, projectService, gisViewerManager, numberUtils) { aansluitingen.AansluitingenEntityControllerBase.call(this, service, config, $timeout, $translate, aansluitingenConfig, aansluitingenModuleService); var vm = this; Object.defineProperties(vm, { _aansluitingenService: { value: aansluitingenService }, _panelManager: { value: panelManager }, _projectService: { value: projectService }, _aansluitingenOverviewService: { value: aansluitingenOverviewService }, _viewer: { value: gisViewerManager }, utils: { value: { number: numberUtils } }, filter: { value: { aansluitingId: null, q: null } }, _onDisplayChanged: { value: function (value) { var vm = this; return aansluitingen.AansluitingenEntityControllerBase.prototype._onDisplayChanged.apply(vm, arguments) .then(function (value) { return vm._aansluitingenOverviewService.setActiveEntityDisplay(value); }); }, configurable: true }, data: { value: Object.defineProperties({}, { parent: { value: null, writable: true }, parents: { value: [], writable: true }, floatProperties: { value: ['lengte', 'diepte'] }, terugslagKleppen: { value: ['Ja', 'Nee'] }, priveDomeinen: { value: ['Ja', 'Nee'] } }) } }); aansluitingenOverviewService.on("init", function (e, arg) { switch (arg.display) { case "aansluitingstukken": { return vm.init(arg); } } return Promise.resolve(); }); } AansluitingContainerStukController.$inject = inject; AansluitingContainerStukController.prototype = Object.create(aansluitingen.AansluitingenEntityControllerBase.prototype); EventHandler.injectInto(AansluitingContainerStukController.prototype); Object.defineProperties(AansluitingContainerStukController.prototype, { constructor: { value: AansluitingContainerStukController }, _entityType: { value: moduleName + "AansluitingStukContainer" }, init: { value: function (o) { var vm = this; vm.display = "list"; vm.selected = null; vm.filter.aansluitingId = vm._aansluitingenOverviewService.data.aansluiting.id; vm.countFilter.aansluitingId = vm.filter.aansluitingId; vm.data.parents = []; vm.data.parent = null; return EntityControllerBase.prototype.init.apply(this).then(function (result) { if (o && o.aansluitingStukId) { vm.setSelectedId(o.aansluitingStukId); vm.trigger("requestScrollSelectedIntoView"); } return result; }); } }, load: { value: function (filter) { var vm = this; filter = filter || vm.filter; filter.parentAansluitingStukId = vm.data.parent ? vm.data.parent.id : null; return EntityControllerBase.prototype.load.apply(this, filter); } }, _ignoreFilterKeys: { value: ["taalcode", "aansluitingId"], writable: true }, add: { value: function () { this.display = "new"; }, configurable: true }, canEdit: { value: function () { var vm = this; return vm._aansluitingenOverviewService.data.project && !vm._aansluitingenOverviewService.data.project.isLocked && vm._aansluitingenOverviewService.data.aansluiting && !vm._aansluitingenOverviewService.data.aansluiting.isLocked && vm._aansluitingenModuleService.canEditAansluitingen(); } }, editGeometryAndSave: { value: function (item) { var ctrl = this; ctrl.validator.checkError(item, 'geometry.wkt'); EntityControllerBase.prototype.details.call(ctrl, item.id).then(function (aansluitingStuk) { aansluitingStuk.geometry.wkt = item.geometry.wkt; var splitted = item.geometry.wkt.split(/[() ]/); // split on '(', space and ')'. example: POINT(161266.112351859 210299.745328072) -> ['POINT', '161266.112351859', '210299.745328072', ''] if (splitted[1] && splitted[2]) { aansluitingStuk.vlarioXCoords = splitted[1]; aansluitingStuk.vlarioYCoords = splitted[2]; } ctrl.save(aansluitingStuk); }) } }, addIsVisible: { value: function () { var vm = this; return EntityControllerBase.prototype.addIsVisible.apply(this, arguments) && vm.canEdit(); } }, editIsVisible: { value: function (item) { var vm = this; return EntityControllerBase.prototype.editIsVisible.apply(this, arguments) && vm.canEdit(); } }, listEditIsVisible: { value: function (item) { var vm = this; return EntityControllerBase.prototype.listEditIsVisible.apply(this, arguments) && vm.canEdit(); } }, _show: { value: function (item) { EntityControllerBase.prototype._show.apply(this, arguments); if (!item) { return item; } var vm = this; var id = item.id || 0; item.isNew = id <= 0; vm.itemIsEditable = vm.canEdit(item); if (!item.geometry) { item.geometry = {}; } if (!item.files) { item.files = []; } vm._aansluitingenModuleService.initDiameterCustom(item, ["diameter", "diameter2", "diameter3"]); vm.data.floatProperties.forEach(function (property) { item[property] = vm.utils.number.floatToString(item[property]); }); return item; }, enumerable: true, configurable: true }, getGeom: { value: function (item) { return item.geometry.wkt; }, configurable: true }, //_validating: { // value: function (o) { // var vm = this; // var item = o.item || vm.item; // if (item.diameterAvailable) { // vm.validator.validateTarget(vm.validator.isRequired, item, "diameter", 'DiameterIsRequired'); // } // if (item.diameter2Available) { // vm.validator.validateTarget(vm.validator.isRequired, item, "diameter", 'Diameter2IsRequired'); // } // if (item.diameter3Available) { // vm.validator.validateTarget(vm.validator.isRequired, item, "diameter", 'Diameter3IsRequired'); // } // if (item.lengteAvailable) { // vm.validator.validateTarget(vm.validator.isRequired, item, "lengte", 'LengthIsRequired'); // } // } //}, _save: { value: function (o) { var vm = this; o.saving.item = $.extend({}, o.saving.item); var item = o.saving.item; if (item.materiaal) { item.materiaalId = item.materiaal.id; } if (item.vlarioMateriaal) { item.vlarioMateriaalId = item.vlarioMateriaal.id; } if (item.lengteAvailable) { item.verticaleBuis = !!item.verticaleBuis; } vm.data.floatProperties.forEach(function (property) { item[property] = vm.utils.number.stringToFloat(item[property]); }); item.files = (item.files || []).where(function (x) { return !x.removed; }); return EntityControllerBase.prototype._save.call(vm, o); } }, _afterSave: { value: function () { var vm = this; return EntityControllerBase.prototype._afterSave.apply(vm, arguments) .then(function (result) { //if ($scope.modules.featureinfo) { // $scope.modules.featureinfo.setListeningEnabled(false); //} //viewer.gisviewer("refreshMap", function () { // if ($scope.modules.featureinfo) { // $scope.modules.featureinfo.setListeningEnabled(true); // } //}); return vm._viewer.refreshMap() .then(function () { return result; }); }) .then(function (result) { if (vm._showListAfterSave && vm.display === 'details') { vm._showListAfterSave = false; vm.display = 'list'; } return result; }); } }, removeIsVisible: { value: function () { return false; } }, _afterRemove: { value: function () { var vm = this; return EntityControllerBase.prototype._afterRemove.apply(vm, arguments) .then(function (result) { return vm._viewer.refreshMap() .then(function () { return result; }); }); } }, _afterCancel: { value: function () { var vm = this; return EntityControllerBase.prototype._afterCancel.apply(vm, arguments) .then(function (result) { if (vm._showListAfterSave && vm.display === 'details') { vm._showListAfterSave = false; vm.display = 'list'; } return result; }); } }, toggleSelected: { value: function (item) { var vm = this; if (item && vm.selected && item.id === vm.selected.id) { vm.setSelected(null); } else { vm.setSelected(item); } } }, setSelectedId: { value: function (id) { var vm = this; var item = id ? vm.items.where(function (x) { return x.id === id; }).first() : null; return vm.setSelected(item); } }, setSelected: { value: function (item) { var vm = this; vm.selected = item; vm._aansluitingenOverviewService.data.aansluitingStuk = item; } }, isVlario: { value: function () { var vm = this; return vm._aansluitingenOverviewService.isVlario(); } }, showChildren: { value: function (item) { var vm = this; vm.data.parents.add(item); vm.data.parent = vm.data.parents.last(); return vm.load(); } }, showParent: { value: function () { var vm = this; vm.data.parents.remove(vm.data.parents.last()); vm.data.parent = vm.data.parents.last(); return vm.load(); } }, moveUpAansluitingStuk: { value: function () { var vm = this; var item = vm.selected; if (item == null || item.index === 0) { return Promise.resolve(); } var previousItem = vm.items[item.index - 1]; if (item.id === previousItem.id) { console.log('items', vm.items); console.log('move up index', item.index); throw 'BUG: item en previous zijn dezelfde!'; } item.index--; previousItem.index++; var state = vm.stateManager.addState("loading"); return Promise.all([item, previousItem].select(function (item) { return vm._service.save(item); })) .then(function (result) { vm.sortItems(); vm.trigger("requestScrollSelectedIntoView"); //setTimeout(scrollToSelectedItem, 0); return result; }) .then(state.completed) .catch(function (error) { state.error(error); vm.handleError(error); }); } }, moveDownAansluitingStuk: { value: function () { var vm = this; var item = vm.selected; if (item == null || item.index === vm.items.length - 1) { return Promise.resolve(); } var nextItem = vm.items[item.index + 1]; if (item.id === nextItem.id) { console.log('items', vm.items); console.log('move down index', item.index); throw 'BUG: item en next zijn dezelfde!'; } item.index++; nextItem.index--; var state = vm.stateManager.addState("loading"); return Promise.all([item, nextItem].select(function (item) { return vm._service.save(item); })) .then(function (result) { vm.sortItems(); vm.trigger("requestScrollSelectedIntoView"); //setTimeout(scrollToSelectedItem, 0); return result; }) .then(state.completed) .catch(function (error) { state.error(error); vm.handleError(error); }); } }, sortItems: { value: function (items) { var vm = this; vm._load((items || vm.items).orderBy(function (x) { return x.index; })); } }, addAansluitingStuk: { value: function (item) { var vm = this; var index = (vm.items.length > 0 ? vm.items.max(function (x) { return x.index; }) : -1) + 1; var aansluiting = vm._aansluitingenOverviewService.data.aansluiting; var diameter = item.diameter; if (!diameter) { if (aansluiting.defaultDiameter) { diameter = aansluiting.defaultDiameter; } } var diameter2 = item.diameter2; if (!diameter2) { if (aansluiting.defaultDiameter) { diameter2 = aansluiting.defaultDiameter; } } var diameter3 = item.diameter3; if (!diameter3) { if (aansluiting.defaultDiameter) { diameter3 = aansluiting.defaultDiameter; } } var materiaalId = aansluiting.defaultMateriaalId; var materiaal = vm._aansluitingenModuleService.data.materiaalItems.where(function (x) { return x.id === materiaalId; }).first(); //if (!materiaalId) { // aansluitingStukManager.list.el.messageOverlay($scope.lang.translate('MaterialIsRequired'), { // type: 'validate', // okcallback: function () { // aansluitingStukManager.list.el.find("#AansluitingMateriaal").focus(); // } // }); // return; //} var aansluitingStuk = { aansluitingId: aansluiting.id, niscode: aansluiting.niscode, index: index, code: item.code, naam: item.naam, naamNl: item.naamNl, naamFr: item.naamFr, materiaalId: materiaalId, materiaal: materiaal, previewFilename: item.previewFilename, diameter: item.diameterAvailable ? diameter : null, diameterAvailable: item.diameterAvailable, diameter2: item.diameter2Available ? diameter2 : null, diameter2Available: item.diameter2Available, diameter3: item.diameter3Available ? diameter3 : null, diameter3Available: item.diameter3Available, lengte: item.lengte, lengteAvailable: item.lengteAvailable, diepte: item.diepte, diepteAvailable: item.diepteAvailable, geometryAvailable: item.geometryAvailable, isCustom: item.projectId ? true : false, supportChildren: item.supportChildren, vlarioDiameter: aansluiting.vlarioDiameter, vlarioMateriaal: materiaal, vlarioMateriaalId: materiaalId, vlarioPriveDomein: "Nee" }; if (vm.data.parent) { aansluitingStuk.parentAansluitingStukId = vm.data.parent.id; } vm._aansluitingenModuleService.initDiameterCustom(aansluitingStuk, ["diameter", "diameter2", "diameter3"]); var state = vm.stateManager.addState("saving"); var saveItems; var afterSave; var selectedAansluitingStuk = vm.selected; if (selectedAansluitingStuk && selectedAansluitingStuk.index < vm.items.length - 1) { var items = __extensions.array(vm.items); items.splice(selectedAansluitingStuk.index + 1, 0, aansluitingStuk); for (var i = selectedAansluitingStuk.index; i < items.length; i++) { items[i].index = i; } saveItems = items; afterSave = function (items) { vm.sortItems(items); vm.selected = items.where(function (x) { return x.index === aansluitingStuk.index; }).first(); }; } else { saveItems = [aansluitingStuk]; afterSave = function (items) { vm.items.addRange(items); vm.sortItems(); vm.selected = items.first(); }; } var saveFuncs = saveItems.select(function (item) { return vm._service.save(item); }); return Promise.all(saveFuncs) .then(function (items) { afterSave(items); }) .then(state.completed) .catch(function (error) { state.error(error); vm.handleError(error); }).then(function (result) { if (!vm.itemIsValid(aansluitingStuk)) { vm._showListAfterSave = true; return vm.show(vm.selected.id, 'form'); } vm.display = 'list'; return result; }).then(function () { vm.trigger("requestScrollSelectedIntoView"); //setTimeout(scrollToSelectedItem, 0); }); } }, editCustomStukken: { value: function () { var vm = this; vm.display = 'list'; vm._aansluitingenOverviewService.display = 'stukken'; return vm._aansluitingenOverviewService.init(); } }, parentHasGeometry: { value: function () { //geometry mag niet gezet worden wanneer parent geen geometry heeft (indien niet rootlist ofc) var vm = this; if (vm.data.parent) { return vm.data.parent.geometry != null && vm.data.parent.geometry.wkt; } return null; } }, onGeomSelect: { value: function (o) { var vm = this; if (vm.data.parent) { if (vm.data.parent.geometry == null || !vm.data.parent.geometry.wkt) { return vm._translate('aansluitingen.StukParentIsMissingPoint').then(function (msg) { vm.item.geometry.wkt = null; vm.item.geometryAccuracy = null; throw msg; }); } } return Promise.resolve(); } }, itemIsValid: { value: function (item) { if (this.isVlario()) { var lengteValid = true; if (item.code == "BUIS" && !item.vlarioLengte) { lengteValid = false } return item.diameterAvailable && item.vlarioDiameter && lengteValid; } return !((item.diameterAvailable && !item.diameter) || (item.diameter2Available && !item.diameter2) || (item.diameter3Available && !item.diameter3) || (item.lengteAvailable && !item.lengte)); } }, returnToPrevious: { value: function () { var vm = this; if (vm.data.parent) { vm.showParent(); } else { vm._aansluitingenOverviewService.display = 'aansluitingen'; } } }, getPreviewSource: { value: function (code) { return this._aansluitingenConfig.previewsUrl.replace('{code}', code || 'custom'); } } }); return AansluitingContainerStukController; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.AansluitingStukFormDirective = (function (moduleName) { function AansluitingStukFormDirective(config, $timeout) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, scope: { ctrl: "=" }, link: function ($scope, $el) { } }; } AansluitingStukFormDirective.$inject = ["config", "$timeout"]; return AansluitingStukFormDirective; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.AansluitingStukListDirective = (function () { function AansluitingStukListDirective($timeout) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, scope: { ctrl: "=" }, link: function ($scope, $el) { var ctrl = $scope.ctrl; function scrollSelectedIntoView() { setTimeout(function () { $el.find("tr.selected:first").scrollintoview(); }, 250); } ctrl.on("requestScrollSelectedIntoView", scrollSelectedIntoView); } }; } AansluitingStukListDirective.$inject = ["$timeout"]; return AansluitingStukListDirective; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.AansluitingStukService = (function (moduleName) { "use strict"; function AansluitingStukService(aansluitingenConfig, $http, aansluitingenModuleService) { aansluitingen.AansluitingenEntityServiceBase.call(this, aansluitingenConfig, "AansluitingStuk", $http); this.aansluitingenModuleService = aansluitingenModuleService; } AansluitingStukService.$inject = ["aansluitingenConfig", "$http", "aansluitingenModuleService"]; AansluitingStukService.prototype = Object.create(aansluitingen.AansluitingenEntityServiceBase.prototype, { constructor: { value: AansluitingStukService }, _processItem: { value: function (item) { if (item && typeof (item) === "object") { this.fillNaam(item); this.fillNaam(item.materiaal); } if (item.vlarioMateriaalId) { item.vlarioMateriaal = this.aansluitingenModuleService.data.materiaalItems.where(function (x) { return x.id === item.vlarioMateriaalId; }).first(); } return Promise.resolve(item); } } }); return AansluitingStukService; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.BestemmingService = (function () { "use strict"; function BestemmingService(aansluitingenConfig, $http) { aansluitingen.AansluitingenEntityServiceBase.call(this, aansluitingenConfig, "Bestemming", $http); } BestemmingService.$inject = ["aansluitingenConfig", "$http"]; BestemmingService.prototype = Object.create(aansluitingen.AansluitingenEntityServiceBase.prototype, { constructor: { value: BestemmingService } }); return BestemmingService; })(); var aansluitingen = aansluitingen || {}; aansluitingen.CategorieService = (function () { "use strict"; function CategorieService(aansluitingenConfig, $http) { aansluitingen.AansluitingenEntityServiceBase.call(this, aansluitingenConfig, "Categorie", $http); } CategorieService.$inject = ["aansluitingenConfig", "$http"]; CategorieService.prototype = Object.create(aansluitingen.AansluitingenEntityServiceBase.prototype, { constructor: { value: CategorieService }, _processItem: { value: function (item) { var me = this; if (item.stukItems) { item.stukItems.each(function (stukItem) { stukItem.naam = me.getNaam(stukItem); }); } return Promise.resolve(item); } } }); return CategorieService; })(); var aansluitingen = aansluitingen || {}; aansluitingen.DiameterService = (function () { "use strict"; function DiameterService(aansluitingenConfig, $http) { aansluitingen.AansluitingenEntityServiceBase.call(this, aansluitingenConfig, "Diameter", $http); } DiameterService.$inject = ["aansluitingenConfig", "$http"]; DiameterService.prototype = Object.create(aansluitingen.AansluitingenEntityServiceBase.prototype, { constructor: { value: DiameterService } }); return DiameterService; })(); var aansluitingen = aansluitingen || {}; aansluitingen.DummyPointService = (function () { "use strict"; function DummyPointService(aansluitingenConfig, $http) { aansluitingen.AansluitingenEntityServiceBase.call(this, aansluitingenConfig, "DummyPoint", $http); } DummyPointService.$inject = ["aansluitingenConfig", "$http"]; DummyPointService.prototype = Object.create(aansluitingen.AansluitingenEntityServiceBase.prototype, { constructor: { value: DummyPointService } }); return DummyPointService; })(); var aansluitingen = aansluitingen || {}; aansluitingen.MateriaalService = (function () { "use strict"; function MateriaalService(aansluitingenConfig, $http) { aansluitingen.AansluitingenEntityServiceBase.call(this, aansluitingenConfig, "Materiaal", $http); } MateriaalService.$inject = ["aansluitingenConfig", "$http"]; MateriaalService.prototype = Object.create(aansluitingen.AansluitingenEntityServiceBase.prototype, { constructor: { value: MateriaalService } }); return MateriaalService; })(); var aansluitingen = aansluitingen || {}; aansluitingen.ModuleDirective = (function (moduleName) { function ModuleDirective(config) { return { restrict: "EA", templateUrl: config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".html?v=" + config.version, link: function ($scope) { } }; } ModuleDirective.$inject = ["config"]; return ModuleDirective; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.ModuleService = (function (moduleName) { "use strict"; function ModuleService(config, $http, $translate, projectManager, aansluitingenService, diameterService, materiaalService, bestemmingService, categorieService, soortService, securityManager) { var sv = this; var initialized = false; Object.defineProperties(sv, { initialized: { get: function () { return initialized; } }, init: { value: function () { var promiseFuncs = [ function () { return sv.refreshMateriaalItems(); }, function () { return sv.refreshDiameterItems(); }, function () { return sv.refreshCategorieItems(); }, function () { return sv.refreshSoortItems(); }, function () { return sv.refreshBestemmingItems(); } ]; return Promise.enqueue(promiseFuncs) .then(function () { //niscode niveau return aansluitingenService.getXsltTemplates() .then(function(xsltTemplates) { sv.data.printTemplates = xsltTemplates; }); }) .then(function () { initialized = true; return sv.trigger("initialized"); }) .then(function () { return { initialized: initialized }; }); } }, data: { value: Object.defineProperties({}, { materiaalItems: { value: null, writable: true }, categorieItems: { value: null, writable: true }, soortItems: { value: null, writable: true }, bestemmingItems: { value: null, writable: true }, diameters: { value: null, writable: true }, diametersCustom: { value: null, writable: true }, printTemplates: { value: null, writable: true }, selectedProject: { get: function () { return projectManager.activeItem; } } }) }, _canEditAllProjects: { value: function () { return securityManager.hasRole(moduleName, "beheer_beheerder"); } }, canEditOwnProjects: { value: function () { return this._canEditAllProjects() || securityManager.hasRole(moduleName, "beheer_projectleider"); } }, //de projecten die je niet mag lezen worden in de 1e instantie al niet opgehaald //canReadProject: { // value: function (projectId) { // if (!projectId) { // var project = this.data.selectedProject; // if (!project) return false; // projectId = project.id; // } // return this._canAddEditAll() || securityManager.hasRole(moduleName, "project_" + projectId); // } //}, canEditProject: { value: function (item) { if (!item) { item = this.data.selectedProject; if (!item) return false; } return this._canEditAllProjects() || (this.canEditOwnProjects() && (!item.CreatedBy || item.CreatedBy === config.user)) || securityManager.hasRole(moduleName, "project_" + item.id + "_edit"); } }, canEditAansluitingen: { value: function (item) { if (!item) { item = this.data.selectedProject; if (!item) return false; } return this.canEditProject(item) || securityManager.hasRole(moduleName, "project_" + item.id + "_edit_aansluitingen"); } }, refreshMateriaalItems: { value: function () { return materiaalService.list({}).then(function (items) { sv.data.materiaalItems = items; }); } }, refreshCategorieItems: { value: function (projectId) { return categorieService.list({ projectId: projectId || (projectManager.activeItem ? projectManager.activeItem.id : 0) }).then(function (items) { sv.data.categorieItems = items; sv.data.categorieStukItems = items.selectMany(function (x) { if (x.stukItems) { x.stukItems.each(function (stukItem) { stukItem.isCustom = x.hasProjectStukken; }); } return x.stukItems; }); sv.data.customCategorie = items.where(function (x) { return x.hasProjectStukken }).first(); }); } }, refreshSoortItems: { value: function () { return soortService.list({}).then(function (items) { sv.data.soortItems = items; }); } }, refreshBestemmingItems: { value: function () { return bestemmingService.list({}).then(function (items) { sv.data.bestemmingItems = items; }); } }, refreshDiameterItems: { value: function () { return diameterService.list({}).then(function (items) { return $translate('global.Custom').then(function (custom) { sv.data.diameters = items.select(function (x) { return x.waarde }).distinct(); sv.data.diametersCustom = items.select(function (x) { return x.waarde }).distinct(); sv.data.diametersCustom.add("<" + custom + ">"); }); }); } }, getCustomPropertyName: { value: function(property) { return property + "Custom"; } }, initDiameterCustom: { value: function (item, properties) { if (!properties) { properties = ["diameter"]; } properties.each(function (property) { var value = parseFloat(item[property]); item[sv.getCustomPropertyName(property)] = value && !sv.data.diameters.contains(value); }); } }, toggleDiameterCustom: { value: function (item, property) { if (!property) { property = "diameter"; } var customProperty = sv.getCustomPropertyName(property); if (item[customProperty]) { item[customProperty] = false; var value = parseFloat(item[property]); item[property] = sv.data.diameters.contains(value) ? value : null; } else { item[customProperty] = true; } } }, diameterIsCustom: { value: function (item, property) { return item[sv.getCustomPropertyName(property)]; } }, gotoDiameterCustom: { value: function (item, property) { if (!property) { property = "diameter"; } var value = item[property]; if (value === sv.data.diametersCustom.last()) { item[sv.getCustomPropertyName(property)] = true; item[property] = null; } } }, gotoDiameterSelect: { value: function (item, property) { if (!property) { property = "diameter"; } item[sv.getCustomPropertyName(property)] = false; var value = parseFloat(item[property]); item[property] = sv.data.diameters.contains(value) ? value : null; } }, setGeometry: function (item, wkt, accuracy) { if (!item.geometry) { item.geometry = {}; } item.geometry.wkt = wkt; item.geometryAccuracy = accuracy; }, showPrintSettings: { value: function (o) { var sv = this; return sv.trigger("request-show-print-settings", o); } }, getExportFileNameProject: { value: function (item) { return $translate('global.Project').then(function (projectTranslated) { return projectTranslated + " " + item.code + " " + item.title; }); } }, getExportFileNameAansluiting: { value: function (item) { return $translate("aansluitingen.Aansluiting").then(function (aansluitingTranslated) { var bestemmingNaam = ""; var soortNaam = ""; if (item.bestemming != null) { bestemmingNaam = item.bestemming.naam; } if (item.soort != null) { soortNaam = item.soort.naam; } var filename = aansluitingTranslated + " " + item.gemeente + " " + item.straat + " " + item.nr + " " + bestemmingNaam + " " + soortNaam; return filename.trim(); }); } }, getNaamLanguagePropertyName: { value: function () { var taalcode = config.taalcode; return 'naam' + taalcode[0].toUpperCase() + taalcode[1].toLowerCase(); } }, getNaam: { value: function (item) { if (item.naam === undefined && item.naamNl !== undefined) { var naamProperty = this.getNaamLanguagePropertyName(); return item[naamProperty] || item.naamNl; } return item.naam; } }, }); } EventHandler.injectInto(ModuleService.prototype); return ModuleService; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.OverviewController = (function (moduleName) { "use strict"; function OverviewController($timeout, $translate, config, aansluitingenConfig, aansluitingenModuleService, aansluitingenOverviewService) { ControllerBase.call(this); var vm = this; Object.defineProperties(vm, { _aansluitingenModuleService: { value: aansluitingenModuleService }, _aansluitingenOverviewService: { value: aansluitingenOverviewService } }); } OverviewController.prototype = Object.create(ControllerBase.prototype); EventHandler.injectInto(OverviewController.prototype); Object.defineProperties(OverviewController.prototype, { constructor: { value: OverviewController }, display: { get: function () { return this._aansluitingenOverviewService.display; }, set: function (value) { this._aansluitingenOverviewService.display = value; } }, data: { get: function () { return this._aansluitingenOverviewService.data; } }, isVlario: { value: function () { var vm = this; var project = vm._aansluitingenOverviewService.data.project; if (!project) return; var vlarioKeys = Object.keys(project).filter(x => x.toLowerCase().startsWith('vlario')); for (var i = 0; i < vlarioKeys.length; i++) { var val = project[vlarioKeys[i]]; if (val != null && val != '') { return true; // als er ook maar 1 vlario attribuut is ingevuld is het een vlario project } } return false; } }, //showAansluitingen: { // value: function () { // if (this._aansluitingenOverviewService.activeEntityDisplay !== 'form') { // this.display = 'aansluitingen'; // } // } //} }); OverviewController.$inject = ["$timeout", "$translate", "config", "aansluitingenConfig", "aansluitingenModuleService", "aansluitingenOverviewService"]; return OverviewController; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.AansluitingOverviewDirective = (function (moduleName) { function AansluitingOverviewDirective(config, aansluitingenConfig, commandBag, projectManager, $translate, $timeout, aansluitingenModuleService, aansluitingenOverviewService, panelHelper, gisFeatureService, featureInfoBag) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, scope: {}, controller: aansluitingen.OverviewController, controllerAs: "ctrlOverview", link: function ($scope, $el, $attr, $ctrl) { var lastMode = window.innerWidth < 1280 ? "full" : "half"; var showPanel = function (o) { return panelHelper.show({ el: $el, panel: "bottom", mode: lastMode }) .then(function () { if (o && o.skipRefresh) { return null; } aansluitingenOverviewService.data.aansluiting = null; aansluitingenOverviewService.data.aansluitingStuk = null; if (projectManager.activeItem) { aansluitingenOverviewService.display = "aansluitingen"; return aansluitingenOverviewService.init(o); } return $timeout(function () { $ctrl.display = "projecten"; }); }); }; var showOverview = function (o) { if (aansluitingenOverviewService.activeEntityDisplay === "form") { return showPanel({ skipRefresh: true }) .catch($ctrl.handleError); } return Promise.resolve().then(function () { if (o && o.layerName === aansluitingenConfig.layers.aansluitingen) { var aansluitingId = parseInt(o.featureIds[0]); return gisFeatureService .getFeatureDetails({ layerName: o.layerName, filter: "{id} = " + aansluitingId }) .then(function (items) { var item = items.first(); if (item) { var selectedProjectId = parseInt(item.project_id); var currentProjectId = projectManager.activeItem ? projectManager.activeItem.id : null; if (currentProjectId !== selectedProjectId) { return Promise.reject({ validationMessageTranslationKey: "global.SelectionDoesNotBelongToActiveProject" }); } return showPanel({ aansluitingId: aansluitingId }); } return Promise.reject({ validationMessageTranslationKey: "aansluitingen.AansluitingNotFound" }); }); } if (o && o.layerName === aansluitingenConfig.layers.aansluitingStukken) { var aansluitingStukId = parseInt(o.featureIds[0]); return gisFeatureService .getFeatureDetails({ layerName: o.layerName, filter: "{id} = " + aansluitingStukId }) .then(function (items) { var item = items.first(); if (item) { var selectedProjectId = parseInt(item.project_id); var currentProjectId = projectManager.activeItem.id; if (currentProjectId !== selectedProjectId) { return Promise.reject({ validationMessageTranslationKey: "global.SelectionDoesNotBelongToActiveProject" }); } return showPanel({ aansluitingId: parseInt(item.aansluiting_id), aansluitingStukId: aansluitingStukId }); } return Promise.reject({ validationMessageTranslationKey: "aansluitingen.AansluitingStukNotFound" }); }); } return showPanel(); }); } commandBag.on("execute", moduleName + ".Open", function () { return showOverview().catch($ctrl.handleError); }); //register action featureInfoBag.registerAction({ layerNames: [aansluitingenConfig.layers.aansluitingen, aansluitingenConfig.layers.aansluitingStukken], action: function (arg) { return showOverview(arg); } }); panelHelper.on("resize", function (e, arg) { if (arg && arg.panel === "bottom" && $el.is(":visible")) { lastMode = arg.mode; } }); aansluitingenOverviewService.on("active-entity-display-changed", function (e, arg) { panelHelper.setFreeze({ includes: $el }, arg.display === "form"); }); } }; } AansluitingOverviewDirective.$inject = ["config", "aansluitingenConfig", "commandBag", "projectManager", "$translate", "$timeout", "aansluitingenModuleService", "aansluitingenOverviewService", "panelHelper", "gisFeatureService", "featureInfoBag"]; return AansluitingOverviewDirective; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.OverviewService = (function (moduleName) { function OverviewService(aansluitingenModuleService, featureInfoBag) { var sv = this; Object.defineProperties(sv, { display: { value: null, writable: true }, activeEntityDisplay: { get: function() { return this._activeEntityDisplay || 'list'; } }, setActiveEntityDisplay: { value: function (value) { var vm = this; vm._activeEntityDisplay = value; return featureInfoBag.setDisabled(value === 'form') .then(function() { return sv.trigger(new Event("active-entity-display-changed"), { display: value }); }) .then(function() { return value; }); } }, isVlario: { value: function () { var project = aansluitingenModuleService.data.selectedProject; if (!project) return; var vlarioKeys = Object.keys(project).filter(x => x.toLowerCase().startsWith('vlario')); for (var i = 0; i < vlarioKeys.length; i++) { var val = project[vlarioKeys[i]]; if (val != null && val != '') { return true; // als er ook maar 1 vlario attribuut is ingevuld is het een vlario project } } return false; } }, data: { value: Object.defineProperties({}, { project: { get: function () { return aansluitingenModuleService.data.selectedProject; } }, aansluiting: { value: null, writable: true }, aansluitingStuk: { value: null, writable: true } }) }, init: { value: function (o) { var sv = this; return sv.trigger(new Event("init"), $.extend({}, o || {}, { display: sv.display })); } } }); } OverviewService.$inject = ["aansluitingenModuleService", "featureInfoBag"]; EventHandler.injectInto(OverviewService.prototype); Object.defineProperties(OverviewService.prototype, { constructor: { value: OverviewService } }); return OverviewService; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.ProjectControllerBase = (function () { "use strict"; function ProjectControllerBase(projectConfig, service, projectManager, projectGisManager, commandBag, $timeout, featureInfoBag, $translate) { var vm = this; EntityControllerBase.call(vm, service); Object.defineProperties(vm, { _user: { value: projectConfig.user }, _projectManager: { value: projectManager }, _projectGisManager: { value: projectGisManager }, _commandBag: { value: commandBag }, _timeout: { value: $timeout }, _featureInfoBag: { value: featureInfoBag }, _translate: { value: $translate }, isListening: { value: false, writable: true, enumerable: true }, hasValidCode: { value: false, writable: true, enumerable: true }, hasUnsavedChanges: { value: false, writable: true, enumerable: true }, filter: { value: { q: null, date: null } }, getDisplay: { value: function() { return projectManager.display; }, configurable: true }, setDisplay: { value: function (value) { return projectManager.setDisplay(value); //return EntityControllerBase.prototype.setDisplay.apply(this, arguments) // .then(function (value) { // return projectManager.setDisplay(value); // }); }, configurable: true } }); //console.log("PCB", { ctrl: vm, projectManager: projectManager, commandBag: commandBag }); } ProjectControllerBase.prototype = Object.create(EntityControllerBase.prototype, { constructor: { value: ProjectControllerBase }, _entityType: { value: "Project" }, selected: { get: function () { return this._projectManager.activeItem; }, enumerable: true }, isLoadedInMap: { value: function (item) { return this._projectManager.isLoaded(item); } }, newItem: { get: function () { var baseNewItem = Object.getOwnPropertyDescriptor(EntityControllerBase.prototype, "newItem").get.call(this); return angular.extend({}, baseNewItem, { createdBy: this._user, created: new Date(), lastModified: new Date() }); }, enumerable: true }, select: { value: function (project) { var vm = this; return vm._projectManager.setActiveItem(project); } }, toggle: { value: function (project) { var vm = this; //if (vm.display === "select") { // return vm.select(project); //} var state = vm.stateManager.addState("loading"); var current = vm._projectManager.activeItem; var promiseFuncs = [function () { return vm._projectManager.toggleItem(project); }]; if (current) { promiseFuncs.push(function () { return vm._projectManager.unloadItem(current); }); if (project.id !== current.id) { promiseFuncs.push(function () { return vm._projectManager.loadItem(project) }); } } else { promiseFuncs.push(function () { return vm._projectManager.loadItem(project); }); } return Promise.enqueue(promiseFuncs) .then(state.completed) .catch(function(error) { state.error(error); throw error; }) .then(function (result) { return vm._timeout(function () { return result; }); }); } }, toggleMap: { value: function (project) { var vm = this; if (vm.selected && vm.selected.id === project.id) { return Promise.resolve(); } var state = vm.stateManager.addState("loading"); //console.log("TOGGLE_MAP", { project: project, projectManager: vm._projectManager }); return Promise.resolve() .then(function() { if (vm.isLoadedInMap(project)) { return vm._projectManager.unloadItem(project); } return vm._projectManager.loadItem(project); }) .then(state.completed) .catch(function (error) { state.error(error); throw error; }) .then(function (result) { return vm._timeout(function () { return result; }); }); } }, zoom: { value: function (items) { var me = this; //if (typeof (items) === "undefined") { // items = me.display !== "list" ? me.item : me.loadedItems; //} var state = me.stateManager.addState("loading"); return me._projectManager.focus(items, { minScale: 500 }) .then(state.completed) .catch(function (error) { state.error(error); throw error; }) .then(function (arg) { if (!arg.bounds) { return me._translate('aansluitingen.NoPointsAvailable') .then(function(msg) { throw msg; }); } return arg; }) .catch(function(err) { G.handleError(err); }); } }, getGeom: { value: function (project) { var vm = this; console.log("PCB.GETTING_GEOM", { ctrl: this, project: project }); var state = vm.stateManager.addState("loading"); return vm._projectGisManager.getExtent({ projectIds: [project.id] }) .then(state.completed) .catch(function (error) { state.error(error); throw error; }); } }, showDetails: { value: function (item) { return this.show(item.id, 'details'); }, configurable: true }, showForm: { value: function (item, display) { return this.show(item.id, display); }, configurable: true }, _afterSave: { value: function (o) { var vm = this; //console.log("PCB.AFTERSAVE", { o: o, ctrl: vm }); if (!o.saved.item.layerName && o.original.layerName) { o.saved.item.layerName = o.original.layerName; } return EntityControllerBase.prototype._afterSave.call(vm, o) .then(function () { return vm._projectManager.load(); }) .then(function(result) { if (vm._projectManager.activeItem && vm._projectManager.activeItem.id === o.saved.item.id) { return vm._projectManager.setActiveItem(o.saved.item); } return result; }) .then(function () { return o.saved.item; }); }, configurable: true }, remove: { value: function () { var vm = this; var item = vm.item; return EntityControllerBase.prototype.remove.apply(vm, arguments) .then(function () { if (vm._projectManager.isSelected(item)) { return vm._projectManager.deselectItem(item); } return Promise.resolve(); }) .then(function () { if (vm._projectManager.activeItem && vm._projectManager.activeItem.id === item.id) { return vm._projectManager.setActiveItem(null); } return Promise.resolve(); }) .then(function() { return vm._projectManager.load(); }) .then(function () { vm.display = "list"; return item; }); } }, getUrlTitle: { value: function (item) { //console.log("PCB.GET_URL_TITLE", item); return encodeURIComponent((item || this.item).title.replace(/\s+/g, "-").toLowerCase()); } }, validateCode: { value: function () { return true; } }, _validating: { value: function (o) { var item = o.item || this.item; if (!item.code) { this.validator.addError("CodeMissing"); } else { this.validateCode(item); } if (!item.title) { this.validator.addError("TitleMissing"); } return Promise.resolve(); } }, //_onProjectsChange: { // value: function () { // //console.log("PCB.PROJECTS_CHANGE", this._projectModule.name, { evt: e, arg: arg }); // //if (arg.added.any() || arg.removed.any()) { // return this.load(); // //} // } //}, //_onRequestShow: { // value: function (e, arg) { // var vm = this; // var promise; // if (arg.moduleName === vm._projectModule.name) { // //console.log("PCB.SHOWING", vm._projectModule, { arg: arg, projectManager: vm._projectManager }); // if (arg.project) { // promise = vm.show(arg.project.id, arg.display); // } else { // vm._show(angular.extend({}, vm.newItem, arg.project), arg.display); // promise = Promise.resolve(vm.item); // } // promise = promise.then(function () { // arg.confirmOpened(vm.item); // return vm.item; // }); // } // return (promise || Promise.resolve(null)); // } //}, //_onRequestSave: { // value: function (e, arg) { // var vm = this; // var promise; // if (arg.moduleName === vm._projectModule.name) { // console.log("PCB.SAVING", vm._projectModule.name, { arg: arg, module: vm._projectModule, project: vm.item }); // promise = vm.save(arg.project) // .then(function (saved) { // arg.setOpened(saved); // return arg.setSelected(saved) // .then(function () { // return saved; // }); // }); // } // return promise || Promise.resolve(null); // } //}, //_onRequestDelete: { // value: function (e, arg) { // var vm = this; // var promise; // if (arg.moduleName === vm._projectModule.name) { // //console.log("PCB.REMOVING", arg, vm._projectModule); // promise = vm.remove(arg.project) // .then(function (item) { // arg.undoOpened(); // return item; // }); // } // return promise || Promise.resolve(null); // } //} }); return ProjectControllerBase; })(); var aansluitingen = aansluitingen || {}; //NOTE rik: viewer.GisDependencyInjector is verwijderd, logica nu meer in de ProjectGisManager, kan zijn dat methods ontbreken aansluitingen.ProjectController = (function (moduleName) { "use strict"; function ProjectController(config, aansluitingenConfig, service, projectManager, projectGisManager, commandBag, $timeout, $translate, aansluitingenModuleService, crabService, aansluitingenService, securityUserService, gisViewerManager, panelManager, featureInfoBag, printManager) { var vm = this; aansluitingen.ProjectControllerBase.call(vm, angular.extend({}, aansluitingenConfig, { user: config.user }), service, projectManager, projectGisManager, commandBag, $timeout, featureInfoBag, $translate); Object.defineProperties(vm, { _config: { value: config }, _aansluitingenConfig: { value: aansluitingenConfig }, _aansluitingenModuleService: { value: aansluitingenModuleService } }); vm._crabService = crabService; vm._securityUserService = securityUserService; vm._aansluitingenService = aansluitingenService; vm._viewer = gisViewerManager; vm._panelManager = panelManager; vm._printManager = printManager; vm.filter.categoryId = null; vm.filter.isLocked = null; vm.filter.isArchived = null; vm.filter.roleRequired = true; vm.tabs = [{ code: 'algemeen', displayTranslation: 'global.General', }, { code: 'vlario', displayTranslation: 'global.Vlario', show: function () { if (!vm.item) return; return (vm.isVlario(vm.item) || (vm.item.id <= 0 && vm.isVlarioProject)); } }, //{ // code: 'ficheinstellingen', // displayTranslation: 'aansluitingen.FicheInstellingen', //}, { // code: 'asciifiles', // displayTranslation: 'aansluitingen.AsciiFiles', // }, { code: 'security', displayTranslation: 'aansluitingen.rechten', show: function () { return vm.display === 'form' && vm._aansluitingenModuleService.canEditProject(vm.item); } }]; vm.isVlarioProject = false; vm.selectedFile = null; vm.tabs.forEach(function (tab) { if (tab.show == undefined || tab.show) { tab.src = tab.src || 'Content/modules/' + moduleName + '/project/tabs/' + tab.code + '.html?v=' + config.version; } }); var security = []; var securityUsernames = []; Object.defineProperties(vm, { aantalAansluitingenPerExportItems: { value: [0, 25, 50, 75, 100, 125, 150, 175, 200].select(function (value) { return { value, text: value > 0 ? value.toString() : '' }; }) }, security: { get: function () { return security; }, set: function (value) { security = value; securityUsernames = value.select(function (x) { return x.user.username; }); } }, securityUsernames: { get: function () { return securityUsernames; } } }); vm.loading = {}; var loading = function (type) { var countProperty = "_" + type; $timeout(function () { vm.loading[type] = true; if (!vm.loading[countProperty]) { vm.loading[countProperty] = 0; } vm.loading[countProperty]++; console.log('loading', type, vm.loading[countProperty]); }); return function () { $timeout(function () { vm.loading[countProperty]--; vm.loading[type] = vm.loading[countProperty] > 0; console.log('loading', type, vm.loading[countProperty]); }); } } vm.autocomplete = { gemeente: { source: function (request, response) { var cancel = loading('gemeenten'); crabService.listGemeenten({ term: request.term }) .then(function (gemeenten) { response(gemeenten.select(function (x) { return { label: x.Naam, obj: x }; }).take(10)); }) .then(function (result) { cancel(); return result; }) .catch(function (err) { cancel(); throw err; }); }, change: function (arg) { //console.log('gemeente.change', arg); this.item.gemeente = arg.item ? arg.item.label : null; }, select: function (arg) { //console.log('gemeente.select', arg); this.item.gemeente = arg.item ? arg.item.label : null; } }, straat: { getList: function (gemeenteNaam, term) { var cancel = loading('straten'); return crabService.findGemeente({ naam: gemeenteNaam }) .then(function (gemeente) { //console.log("GEMEENTE", gemeente); return crabService.listStraten({ gemeente: gemeente, term: term }); }) .then(function (straten) { return straten.select(function (x) { return { label: x.Naam, obj: x }; }).take(10); }) .then(function (result) { cancel(); return result; }) .catch(function (err) { cancel(); throw err; }); } } }; } ProjectController.prototype = Object.create(aansluitingen.ProjectControllerBase.prototype, { constructor: { value: ProjectController }, _entityType: { value: "AansluitingProject" }, init: { value: function () { var vm = this; return aansluitingen.ProjectControllerBase.prototype.init.apply(vm, arguments) .then(function (result) { if (vm._aansluitingenModuleService.initialized) { return result; } return new Promise(function (resolve) { vm._aansluitingenModuleService.on("initialized", function () { resolve(result); }); }); }) .then(function (result) { vm.printTemplates = vm._aansluitingenModuleService.data.printTemplates; return result; }); }, configurable: true }, _ignoreFilterKeys: { value: ["taalcode", "roleRequired"], writable: true }, canEdit: { value: function (item) { var vm = this; return vm._aansluitingenModuleService.canEditProject(item); } }, setVlario: { value: function (val) { var vm = this; vm.isVlarioProject = val; } }, addIsVisible: { value: function () { return aansluitingen.ProjectControllerBase.prototype.addIsVisible.apply(this, arguments) && this._aansluitingenModuleService.canEditOwnProjects(); } }, editIsVisible: { value: function () { return aansluitingen.ProjectControllerBase.prototype.editIsVisible.apply(this, arguments) && this.canEdit(); } }, listEditIsVisible: { value: function (item) { return aansluitingen.ProjectControllerBase.prototype.listEditIsVisible.apply(this, arguments) && this.canEdit(item); } }, isVlario: { value: function (item) { if (!item) return; if (item.isVlario) { return true; } var vlarioKeys = Object.keys(item).filter(x => x.toLowerCase().startsWith('vlario')); for (var i = 0; i < vlarioKeys.length; i++) { var val = item[vlarioKeys[i]]; if (val != null && val != '') { return true; // als er ook maar 1 vlario attribuut is ingevuld is het een vlario item } } return false; } }, _show: { value: function (item) { aansluitingen.ProjectControllerBase.prototype._show.apply(this, arguments); if (!item) { return item; } var vm = this; vm.selectedTab = vm.tabs.first(); vm.securitySelectUser = false; var id = item.id || 0; item.isNew = id <= 0; vm.itemIsEditable = vm.canEdit(item); item.locaties = (item.locaties || []).orderBy(function (x) { return (x.gemeente + x.straat).toLowerCase() }); if (!item.locaties.any()) { item.locaties.add({ gemeente: null, straat: null }); } if (!item.bestemmingDefaults) { item.bestemmingDefaults = []; } item.bestemmingDefaults.each(function (bm) { vm._aansluitingenModuleService.initDiameterCustom(bm); bm.bestemming.naam = vm._aansluitingenModuleService.getNaam(bm.bestemming); }); if (vm._aansluitingenModuleService.data.bestemmingItems) { vm._aansluitingenModuleService.data.bestemmingItems.each(function (bestemmingItem) { if (!item.bestemmingDefaults.any(function (x) { return x.bestemmingId === bestemmingItem.id })) { item.bestemmingDefaults.add({ bestemming: bestemmingItem }); } }); } item.bestemmingDefaults = item.bestemmingDefaults.orderBy(function (x) { return x.bestemming.naam }); if (!item.filesDummyPoints) { item.filesDummyPoints = []; } if (!item.filesLogos) { item.filesLogos = []; } //users //if (vm.itemIsEditable) { return vm._aansluitingenService .getProjectUsers({ projectId: id }) .then(function (projectUsers) { projectUsers = JSON.parse(projectUsers); vm.security = []; projectUsers.readOnly.forEach(function (user) { var securityUser = vm.security.where(function (x) { return x.user.username === user.username; }).first(); if (!securityUser) { securityUser = { user: user }; vm.security.add(securityUser); } }); projectUsers.editProject.forEach(function (user) { var securityUser = vm.security.where(function (x) { return x.user.username === user.username; }).first(); securityUser.editProject = true; }); projectUsers.editAansluitingen.forEach(function (user) { var securityUser = vm.security.where(function (x) { return x.user.username === user.username; }).first(); securityUser.editAansluitingen = true; }); vm.security = vm.sortSecurity(vm.security); return item; }).catch(vm.handleError); //} //return item; }, enumerable: true, configurable: true }, _validating: { value: function (o) { var vm = this; var item = o.item || vm.item; vm.validator.validateTarget(vm.validator.isRequired, item, "code", 'CodeIsRequired'); vm.validator.validateTarget(vm.validator.isRequired, item, "title", 'TitleIsRequired'); vm.validator.validateTarget(vm.validator.isRequired, item, "locaties", 'LocationIsRequired'); if (item.locaties) { item.locaties.each(function (x) { vm.validator.validateTarget(vm.validator.isRequired, x, "gemeente", 'TownIsRequired'); vm.validator.validateTarget(vm.validator.isRequired, x, "straat", 'StreetIsRequired'); }); } if (item.bestemmingDefaults) { item.bestemmingDefaults.each(function (x) { vm.validator.validateTarget(vm.validator.isRequired, x, "materiaal", 'MaterialIsRequired'); vm.validator.validateTarget(vm.validator.isRequired, x, "diameter", 'DiameterIsRequired'); }); } return Promise.resolve(); } }, _save: { value: function (o) { var vm = this; var item = o.saving.item; item.isVlario = vm.isVlarioProject; item.filesDummyPoints = (item.filesDummyPoints || []).where(function (x) { return !x.removed; }); item.filesLogos = (item.filesLogos || []).where(function (x) { return !x.removed; }); item.locaties = item.locaties.where(function (x) { return x.gemeente || x.straat; }); return aansluitingen.ProjectControllerBase.prototype._save.call(vm, o).then(function (item) { return vm._aansluitingenService.updateProjectRoleDisplayName({ projectId: item.id }).then(function () { return item; }); }).then(function (item) { if (vm._aansluitingenModuleService.canEditProject()) { return vm._aansluitingenService.saveProjectUsers({ projectId: item.id, usernamesReadOnly: vm.security.where(function (x) { return !x.editAansluitingen && !x.editProject }).select(function (x) { return x.user.username; }), usernamesEditProject: vm.security.where(function (x) { return x.editProject }).select(function (x) { return x.user.username; }), usernamesEditAansluitingen: vm.security.where(function (x) { return x.editAansluitingen }).select(function (x) { return x.user.username; }) }).then(function () { return item; }); } return item; }); } }, remove: { value: function () { var vm = this; var projectId = vm.item.id; return aansluitingen.ProjectControllerBase.prototype.remove.apply(vm, arguments) .then(function () { return vm._aansluitingenService.updateProjectRoleDisplayName({ projectId: projectId }); }); }, configurable: true }, sortSecurity: { value: function (items) { var vm = this; return items.orderBy(function (x) { return (x.user.isGroup ? "0" : "1") + vm._securityUserService.getUserDisplay(x.user); }); } }, uploadFile: { value: function (event) { var vm = this; var state = vm.stateManager.addState("loading"); vm.selectedFile = event.target.files[0]; var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.xlsm)$/; if (regex.test(vm.selectedFile.name.toLowerCase())) { var reader = new FileReader(); reader.onload = function (e) { var workbook = XLSX.read(e.target.result, { type: 'binary' }); var algemeneGegevens = workbook.SheetNames.find(x => x.toLowerCase() == 'algemene gegevens'); /* Rioolbeheerder */ var naamRioolbeheerder = workbook.Sheets[algemeneGegevens]["B4"] ? workbook.Sheets[algemeneGegevens]["B4"].v : null; var projectnummerBeheerder = workbook.Sheets[algemeneGegevens]["B5"] ? workbook.Sheets[algemeneGegevens]["B5"].v : null; var projectnaamBeheerder = workbook.Sheets[algemeneGegevens]["B6"] ? workbook.Sheets[algemeneGegevens]["B6"].v : null; var gemeenteBeheerder = workbook.Sheets[algemeneGegevens]["B7"] ? workbook.Sheets[algemeneGegevens]["B7"].v : null; /* Bouwheer */ var naamBouwheer = workbook.Sheets[algemeneGegevens]["B10"] ? workbook.Sheets[algemeneGegevens]["B10"].v : null; var projectnummerBouwheer = workbook.Sheets[algemeneGegevens]["B11"] ? workbook.Sheets[algemeneGegevens]["B11"].v : null; var projectnaamBouwheer = workbook.Sheets[algemeneGegevens]["B12"] ? workbook.Sheets[algemeneGegevens]["B12"].v : null; /* Opdrachtgever */ var naamOpdrachtgever = workbook.Sheets[algemeneGegevens]["B15"] ? workbook.Sheets[algemeneGegevens]["B15"].v : null; var projectnummerOpdrachtgever = workbook.Sheets[algemeneGegevens]["B16"] ? workbook.Sheets[algemeneGegevens]["B16"].v : null; var projectnaamOpdrachtgever = workbook.Sheets[algemeneGegevens]["B17"] ? workbook.Sheets[algemeneGegevens]["B17"].v : null; /* Aannemer */ var projectnummerAannemer = workbook.Sheets[algemeneGegevens]["B20"] ? workbook.Sheets[algemeneGegevens]["B20"].v : null; var naamAannemer = workbook.Sheets[algemeneGegevens]["B21"] ? workbook.Sheets[algemeneGegevens]["B21"].v : null; var werfleider = workbook.Sheets[algemeneGegevens]["B22"] ? workbook.Sheets[algemeneGegevens]["B22"].v : null; /* project ha */ var projectHa = workbook.SheetNames.find(x => x.toLowerCase() == 'project ha'); var projectHaRows = XLSX.utils.sheet_to_json(workbook.Sheets[projectHa], { range: 3 }); /* project wa */ var projectWa = workbook.SheetNames.find(x => x.toLowerCase() == 'project wa'); var projectWaRows = XLSX.utils.sheet_to_json(workbook.Sheets[projectWa], { range: 5 }); /* project kolk */ var projectKolk = workbook.SheetNames.find(x => x.toLowerCase() == 'project kolk'); var projectKolkRows = XLSX.utils.sheet_to_json(workbook.Sheets[projectKolk], { range: 5 }); vm.importProject({ naamRioolbeheerder, projectnummerBeheerder, projectnaamBeheerder, gemeenteBeheerder, naamBouwheer, projectnummerBouwheer, projectnaamBouwheer, naamOpdrachtgever, projectnummerOpdrachtgever, projectnaamOpdrachtgever, projectnummerAannemer, naamAannemer, werfleider, projectId: vm.item.id, projectHaRows, projectWaRows, projectKolkRows }); vm.selectedFile = null; }; reader.readAsBinaryString(vm.selectedFile); state.completed(); } else { vm.handleError("global.InvalidFileError"); state.error(); } vm.selectedFile = null; } }, importProject: { value: function (data) { var vm = this; var state = vm.stateManager.addState("loading"); return vm._aansluitingenService.importProject(data).then(function (result) { state.completed(); return vm._translate('aansluitingen.ImportSuccess').then(function (translation) { var msg = { type: 'validate', message: translation, status: 400}; vm.handleError(msg); return result; }); }).catch(function (error) { G.handleError(error); state.error(error); vm.handleError(error); }); } }, exportProject: { value: function (item, options) { if (!item) { return null; } options = options || {}; var vm = this; var state = vm.stateManager.addState("loading"); return vm._aansluitingenService.exportProject({ projectId: item.id, type: options.type }).then(function (file) { return vm._aansluitingenModuleService.getExportFileNameProject(item).then(function (fileName) { var extension = file.split('.'); extension = extension[extension.length - 1]; var clientFileName = encodeURIComponent(fileName) + "." + extension; var url = config.baseUrl + "/Handlers/FileHandler.aspx?action=download&file=" + encodeURIComponent(file) + "&delete=1" + "&clientfile=" + clientFileName; if (!window.open(url)) { vm._translate('global.PopupBlockedWarning').then(G.handleError); } state.completed(); return url; }); }).catch(function (error) { G.handleError(error); state.error(error); vm.handleError(error); }); } }, userSelected: { value: function (o) { var vm = this; vm.securitySelectUser = false; var items = o.selected; if (items) { items.each(function (item) { vm.security.add({ user: item, editAansluitingen: true }); vm.selectedSecurity = vm.security.last(); }); } vm.security = vm.sortSecurity(vm.security); } }, userSelectCancelled: { value: function () { var vm = this; vm.securitySelectUser = false; } }, showGroupMembers: { value: function (groupItem) { var vm = this; return vm._securityUserService.getGroupUsers({ groupLogin: groupItem.username }).then(function (users) { return vm._translate('global.GroupMembers').then(function (title) { var msg = title + " " + vm._securityUserService.getUserDisplay(groupItem) + ":"; users.each(function (item) { msg += "
- " + vm._securityUserService.getUserDisplay(item); }); throw msg; }); }).catch(vm.handleError); } }, getExportFileNameLogos: { value: function (item) { var vm = this; return vm._aansluitingenModuleService.getExportFileNameProject(item) .then(function (fileName) { return vm._translate('global.Logos').then(function (translated) { return fileName + ' - ' + translated; }); }); } }, getExportFileNameAsciiFiles: { value: function (item) { var vm = this; return vm._aansluitingenModuleService.getExportFileNameProject(item) .then(function (fileName) { return vm._translate('aansluitingen.AsciiFiles').then(function (translated) { return fileName + ' - ' + translated; }); }); } }, printProject: { value: function (project, o) { var vm = this; return vm._translate("print.BusyPrinting") .then(function (msg) { var overlay = $('body').progressOverlay([msg + "..."]); return vm._printManager.printProject(project, o) .then(function (result) { overlay.remove(); return result; }) .catch(function (error) { overlay.remove(); vm.handleError(error); }); }); } } }); aansluitingen.AansluitingenEntityControllerBase.injectInto(ProjectController.prototype); return ProjectController; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.ProjectGisManager = (function () { "use strict"; function ProjectGisManager(config, $translate, gisViewer, layerTree, geoHelper, geoHandler, aansluitingenService) { Object.defineProperties(this, { //itemLayer: { writable: true, enumerable: true }, //tempLayer: { value: { Code: "__notities_temp__", ShowInLegend: false }, writable: true, enumerable: true }, _selectedItems: { value: [] }, _config: { value: config }, $translate: { value: $translate }, _layers: { writable: true }, _viewer: { value: gisViewer }, _layerTree: { value: layerTree }, _geoHelper: { value: geoHelper }, _geoHandler: { value: geoHandler }, _aansluitingenService: { value: aansluitingenService } }); } EventHandler.injectInto(ProjectGisManager.prototype); Object.defineProperties(ProjectGisManager.prototype, { getLayer: { value: function (item) { var mgr = this; return mgr._viewer.getFeatureLayerName({ filter: "{id} = " + item.id, layerNameTerm: mgr._config.layerName }) .then(function (itemLayerName) { //console.log("NGM.LAYER_NAME", { item: item, layerName: itemLayerName, mgr: mgr }); return mgr.getLayers() .then(function (layers) { return layers.first(function (x) { return x.Code === itemLayerName; }); }); }); } }, getLayers: { value: function () { var mgr = this; if (mgr._layers == null) { return new Promise( function (resolve) { return mgr._viewer.on("map-load", resolve); }) .then(function () { return mgr._layerTree.getAll(); }) .then(function (layers) { var layerNameTerms = _.array(mgr._config.layerName || mgr._config.layerNames); mgr._layers = layers .where(function (x) { return layerNameTerms.any(function (layerNameTerm) { if (layerNameTerm.startsWith("*") && layerNameTerm.endsWith("*")) { return x.Code.contains(layerNameTerm.trim("*")); } else if (layerNameTerm.endsWith("*")) { return x.Code.startsWith(layerNameTerm.trim("*")); } else if (layerNameTerm.startsWith("*")) { return x.Code.endsWith(layerNameTerm.trim("*")); } else { return x.Code === layerNameTerm; } }); }); return mgr._layers; }); } else { return Promise.resolve(mgr._layers); } } }, getExtent: { value: function (o) { var mgr = this; return Promise.all(o.projectIds.map(function(projectId) { return mgr._aansluitingenService.getProjectBounds({ id: projectId }).then(function (bounds) { if (!bounds) { return null; } var extent = [bounds.BotLeft.X, bounds.BotLeft.Y, bounds.TopRight.X, bounds.TopRight.Y]; return extent; }); })).then(function (extents) { extents = extents.where(function (x) { return x; }); if (extents.lenth === 0) { return null; } return [ extents.min(function (x) { return x[0] }), extents.min(function (x) { return x[1] }), extents.max(function (x) { return x[2] }), extents.max(function (x) { return x[3] }) ]; }); } }, setSelection: { value: function (items, minScale, zoomToSelection) { var mgr = this; //console.log("NGM.SET_SELECTION", { items: items, mgr: mgr }); if (!items || !items.length) { return mgr._viewer.clearSelection() .then(function () { return mgr._setSelectedItems([]); }); } return mgr.getGisFilter({ items: items }) .then(function (gisFilter) { return mgr._viewer.setSelectedFeatures({ filter: gisFilter, multi: true, initiator: "system", zoomToSelection: zoomToSelection, minScale: minScale }); }) .then(function (arg) { return mgr._setSelectedItems(items) .then(function () { return arg; }); }); } }, clearSelection: { value: function () { var mgr = this; return mgr._viewer.clearSelection() .then(function () { return mgr.refreshMap(); }); } }, setFeatureEditMode: { value: function (item) { var mgr = this; console.log("NGM.SET_EDITMODE", { item: item, mgr: mgr }); var modifiable = item != null; this._viewer.setFeaturesEditMode(modifiable); if (item != null) { var geom = mgr._geoHelper.getGeom(item.wkt); var transformable = !(geom.type || "").contains("Point", true); this._viewer.setFeaturesTransformMode(!!transformable); } } }, zoom: { value: function (o, minScale) { var mgr = this; return mgr.getExtent(o) .then(function (extent) { return mgr._viewer.zoomToExtent({ extent: extent, minScale: minScale }); }); } }, filterItems: { value: function (o) { var mgr = this; return mgr.getGisFilter(o) .then(function (filter) { return mgr._viewer.filter({ filter: filter }); }); } }, getGisFilter: { value: function (o) { var mgr = this; var filter = mgr._getFilter(o); return mgr.getLayers() .then(function (layers) { return layers.toDictionary(function (x) { return x.Code; }, function () { return filter; }); }); } }, refreshMap: { value: function () { return this._viewer.refreshMap(); } }, _getFilter: { value: function (o) { var conditions = o.filter ? [o.filter] : []; if (o.items && o.items.any(function (x) { return x; })) { var ids = o.items.select(function (x) { return x.id; }); conditions.push("{id} IN (" + ids.join(",") + ")"); } if ("projectId" in o) { if (o.projectId == null) { conditions.push("project_id NULL"); } else { conditions.push("project_id NULL OR project_id IN (" + _.array(o.projectId).join(",") + ")"); } } var filter = conditions.aggregate(function (f, c) { return (f ? " AND " : "") + (f + "(" + c + ")"); }, ""); //console.log("NGM.FILTER", { filter: filter, o: o, mgr: this }); return filter; } }, setGeometry: { value: function (item, geom) { var mgr = this; //console.log("NGM.SET_GEOM", { item: item, geom: geom }); if (geom == null) { return Promise.resolve({ item: item, geom: null }); } return new Promise( function (resolve) { mgr._geoHandler.getMulti(geom.wkt, resolve); }) .then(function (wkt) { item.wkt = wkt; return mgr.trigger("change-geometry", { item: item, geom: geom }); }); } }, _setSelectedItems: { value: function (items) { var mgr = this; var oldValue = mgr._selectedItems.select(); var added = items.except(oldValue); var modified = oldValue.innerJoin(items); var removed = oldValue.except(items); Array.prototype.splice.apply(oldValue, [0, oldValue.length].concat(items)); var arg = { oldValue: oldValue, added: added, modified: modified, removed: removed, items: items }; return this.trigger("change-items", arg) .then(function () { return arg; }); } } }); return ProjectGisManager; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.ProjectSelectDirective = (function (moduleName) { function ProjectSelectDirective(config) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, scope: {}, controller: "projectController", controllerAs: "ctrl", link: function ($scope, $el, $attr, $ctrl) { var vm = $ctrl; vm.display = 'select'; } }; } ProjectSelectDirective.$inject = ["config"]; return ProjectSelectDirective; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.ProjectService = (function (moduleName) { "use strict"; function ProjectService(config, $http) { projects.ProjectService.call(this, { niscode: config.niscode, url: config.aansluitingenBaseUrl + "Project" }, $http); } ProjectService.prototype = Object.create(projects.ProjectService.prototype, { constructor: { value: ProjectService }, details: { value: function (o) { var id = o.id || o; var sv = this; return sv._http.post(sv._getUrl(), { action: "details", So: { Id: id } }) .then(function (response) { return sv._processItem(response.data); }); } }, list: { value: function (o) { var sv = this; return sv._http.post(sv._getUrl(), { action: "list", So: o }) .then(function (response) { var items = response.data.select(function (x) { return sv._processItem(x); }); //console.log("SERVICE.LIST", { response: response, items: response.data, processed: items }); return items; }); } }, count: { value: function (o) { var sv = this; return sv._http.post(sv._getUrl(), { action: "count", So: o }) .then(function (response) { return response.data; }); } }, save: { value: function (item) { var sv = this; return sv._http.post(sv._getUrl(), { action: "save", niscode: sv._niscode, item: item }) .then(function (response) { var item = response.data; return item ? sv._processItem(item) : null; }); } }, remove: { value: function (item) { var sv = this; return sv._http.post(sv._getUrl(), { action: "delete", niscode: sv._niscode, item: item }) .then(function (response) { return sv._processItem(response.data); }); } } }); return ProjectService; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.SoortService = (function () { "use strict"; function SoortService(aansluitingenConfig, $http) { aansluitingen.AansluitingenEntityServiceBase.call(this, aansluitingenConfig, "Soort", $http); } SoortService.$inject = ["aansluitingenConfig", "$http"]; SoortService.prototype = Object.create(aansluitingen.AansluitingenEntityServiceBase.prototype, { constructor: { value: SoortService } }); return SoortService; })(); var aansluitingen = aansluitingen || {}; aansluitingen.StukContainerController = (function (moduleName) { "use strict"; var inject = ["config", "$timeout", "$translate", "aansluitingenConfig", "aansluitingenService", "aansluitingenStukService", "aansluitingenModuleService", "aansluitingenOverviewService", "panelManager", "projectService"]; function StukContainerController(config, $timeout, $translate, aansluitingenConfig, aansluitingenService, service, aansluitingenModuleService, aansluitingenOverviewService, panelManager, projectService) { aansluitingen.AansluitingenEntityControllerBase.call(this, service, config, $timeout, $translate, aansluitingenConfig, aansluitingenModuleService); var vm = this; Object.defineProperties(vm, { _aansluitingenService: { value: aansluitingenService }, _panelManager: { value: panelManager }, _projectService: { value: projectService }, _aansluitingenOverviewService: { value: aansluitingenOverviewService }, filter: { value: { q: null } }, _onDisplayChanged: { value: function (value) { var vm = this; return aansluitingen.AansluitingenEntityControllerBase.prototype._onDisplayChanged.apply(vm, arguments) .then(function (value) { return vm._aansluitingenOverviewService.setActiveEntityDisplay(value); }); }, configurable: true } }); aansluitingenOverviewService.on("init", function (e, arg) { switch (arg.display) { case "stukken": { return vm.init(); } } return null; }); } StukContainerController.$inject = inject; StukContainerController.prototype = Object.create(aansluitingen.AansluitingenEntityControllerBase.prototype, { constructor: { value: StukContainerController }, _entityType: { value: moduleName + "StukContainer" }, init: { value: function () { var vm = this; vm.display = "list"; var item = vm._aansluitingenModuleService.data.customCategorie; vm.filter.categorieId = item.id; vm.countFilter.categorieId = vm.filter.categorieId; return EntityControllerBase.prototype.init.apply(this, arguments); } }, _load: { value: function (items) { var res = EntityControllerBase.prototype._load.apply(this, arguments); items.each(function (x) { x.diametersAvailable = 0; if (x.diameterAvailable) { x.diametersAvailable++; } if (x.diameter2Available) { x.diametersAvailable++; } if (x.diameter3Available) { x.diametersAvailable++; } }); return res; } }, _ignoreFilterKeys: { value: ["taalcode", "categorieId"], writable: true }, _getNewItem: { value: function () { var item = EntityControllerBase.prototype._getNewItem.apply(this, arguments); item.geometryAvailable = true; return item; }, configurable: true }, _validating: { value: function (o) { var vm = this; var item = o.item || vm.item; vm.validator.validateTarget(vm.validator.isRequired, item, "naam", 'NameIsRequired'); return Promise.resolve(); } }, _save: { value: function (o) { var vm = this; var item = o.saving.item; var projectId = vm._aansluitingenModuleService.data.selectedProject.id; item.projectId = projectId; item.categorieId = vm.filter.categorieId; var naamProperty = vm._service.getNaamLanguagePropertyName(); item[naamProperty] = item.naam; return EntityControllerBase.prototype._save.call(vm, o); } }, _afterSave: { value: function () { var vm = this; return EntityControllerBase.prototype._afterSave.apply(vm, arguments) .then(function (result) { return vm._aansluitingenModuleService.refreshCategorieItems() .then(function () { return result; }); }); } }, returnToAansluitingStukken: { value: function () { this._aansluitingenOverviewService.display = 'aansluitingstukken'; } } }); return StukContainerController; })("aansluitingen"); var aansluitingen = aansluitingen || {}; aansluitingen.StukService = (function () { "use strict"; function StukService(aansluitingenConfig, $http) { aansluitingen.AansluitingenEntityServiceBase.call(this, aansluitingenConfig, "Stuk", $http); } StukService.$inject = ["aansluitingenConfig", "$http"]; StukService.prototype = Object.create(aansluitingen.AansluitingenEntityServiceBase.prototype, { constructor: { value: StukService }, beforeSave: { value: function (item) { if (!item.code) { if (item.naam) { while (item.naam.indexOf(' ') != -1) { item.naam = item.naam.replaceAll(/ /, ' '); } } item.code = (item.naam || '').trim().toUpperCase().replaceAll(/ /, '-'); } } }, }); return StukService; })(); var aansluitingen = aansluitingen || {}; aansluitingen.PrintManager = (function (moduleName) { "use strict"; function PrintManager(config, $translate, $http, gisViewerManager, aansluitingenService, aansluitingenModuleService, aansluitingenAansluitingPrintSettingService, aansluitingenAansluitingService, printService) { var pm = this; function printAansluiting(item, o) { o = o || {}; var download = o.download; var usemap = o.usemap; var scale = o.scale; var dpi = o.dpi; var orientation = o.orientation; var center = o.center; var xsltName = o.xsltName; var bulk = o.bulk; if (usemap && (!item.geometry || !item.geometry.wkt)) { return $translate('aansluitingen.AansluitingIsMissingPoint') .then(function (msg) { throw msg; }); } return aansluitingenModuleService.getExportFileNameAansluiting(item) .then(function (filename) { var printTemplateParameters = { template: { MarginTop: 15, MarginRight: 20, MarginBottom: 15, MarginLeft: 20, IsLandscape: false, PageSize: "A4" }, filename: filename + ".doc", download: download, center: center, scale: scale || 100, dpi: dpi || 96, orientation: orientation, bulk: bulk }; return aansluitingenService .getAansluitingPrint({ aansluitingId: item.id, name: xsltName }) .then(function (result) { printTemplateParameters.xsltName = result.xsltName; printTemplateParameters.xmlPath = result.xmlPath; if (!printTemplateParameters.xsltName) { return null; } if (usemap) { printTemplateParameters.template.MapWidth = 160; printTemplateParameters.template.MapHeight = 100; printTemplateParameters.template.ScalebarWidth = 50; printTemplateParameters.template.ScalebarHeight = 10; } //console.log("AANSLUITING_PRINTTEMPLATE_PARAMETERS", { params: printTemplateParameters, vm: vm }); return printService.printTemplate(printTemplateParameters); }); }); } Object.defineProperties(pm, { printAansluiting: { value: function (aansluitingId, o) { o = o || {}; var showprintform = o.showprintform; return Promise.resolve() //print settings .then(function() { if (o.printSetting !== undefined) { return o.printSetting; } return aansluitingenAansluitingPrintSettingService .list({ AansluitingId: aansluitingId }) .then(function(printSettings) { //console.log("AANLSUITING_PRINTSETTINGS", { settings: printSettings, vm: vm }); return printSettings.first(); }); }) .then(function (printSetting) { if (showprintform || (o.usemap && !printSetting)) { var showPrintFormFunc = function () { return gisViewerManager .refreshMap() .then(function () { return aansluitingenModuleService .showPrintSettings({ aansluitingId: aansluitingId, template: { Id: -1, Name: "Huisaansluiting", MapWidth: 160, MapHeight: 100 }, schaal: printSetting ? printSetting.schaal : 150, dpi: printSetting ? printSetting.dpi : 150, rotate: printSetting ? printSetting.orientation : 0 }); }); }; if (printSetting) { return gisViewerManager .zoom({ center: [printSetting.x, printSetting.y], scale: printSetting.schaal }) .then(showPrintFormFunc); } return Promise.resolve() //get aansluiting bounds .then(function () { if (o.bounds) { return o.bounds; } return aansluitingenService .getAansluitingBounds({ id: aansluitingId }) .then(function (bounds) { if (!bounds) { return $translate('aansluitingen.NoPointsAvailable') .then(function (msg) { throw msg; }); } return bounds; }); }) .then(function (bounds) { //zoom to bounds return gisViewerManager .zoomToExtent({ bounds: [bounds.BotLeft.X, bounds.BotLeft.Y, bounds.TopRight.X, bounds.TopRight.Y], minScale: 200 }) .then(showPrintFormFunc); }); } //print adv settings zonder form te tonen return aansluitingenAansluitingService .details(aansluitingId) .then(function (item) { return printAansluiting(item, { download: o.download, usemap: o.usemap, xsltName: o.name, scale: o.usemap ? printSetting.schaal : null, dpi: o.usemap ? printSetting.dpi : null, orientation: o.usemap ? printSetting.orientation : null, center: o.usemap ? [printSetting.x, printSetting.y] : null, bulk: o.bulk }); }); }); } }, printProject: { value: function (project, o) { o = o || {}; return $translate("print.BusyPrinting") .then(function(busyPrintingMessage) { var overlay = $('body').progressOverlay([busyPrintingMessage + "..."]); return aansluitingenAansluitingService.list({ projectId: project.id }) .then(function (aansluitingen) { if (!aansluitingen.length) { return $translate('aansluitingen.NoAansluitingenAvailable') .then(function (msg) { throw msg; }); } if (o.usemap) { return aansluitingenAansluitingPrintSettingService .list({ ProjectId: project.id }) .then(function (printSettings) { return { aansluitingen: aansluitingen, printSettings: printSettings }; }); } return { aansluitingen: aansluitingen, printSettings: null }; }) .then(function (result) { if (result.printSettings) { //valideer dat elke aansluiting een printSettings heeft var aansluitingWithoutPrintSetting = result.aansluitingen .where(function(aansluiting) { var printSetting = result.printSettings .where(function (x) { return x.aansluitingId === aansluiting.id; }) .first(); return !printSetting; }) .first(); if (aansluitingWithoutPrintSetting) { return $translate('aansluitingen.ProjectContainsAansluitingenWithoutPrintSettings') .then(function (msg) { throw msg; }); } } var total = result.aansluitingen.length; var processed = 0; return Promise.enqueue(result.aansluitingen.select(function (aansluiting) { return function () { var printSetting = result.printSettings ? result.printSettings .where(function(x) { return x.aansluitingId === aansluiting.id; }) .first() : undefined; var printParameters = $.extend({}, o, { bulk: true, printSetting: printSetting }); return pm.printAansluiting(aansluiting.id, printParameters).then(function(res) { processed++; overlay.setMessage(busyPrintingMessage + "... " + processed + "/" + total); return res; }); }; })); }) .then(function (result) { var printFiles = result.select(function (x) { return x[0]; }); //console.log('PRINTMANAGER.PrintProject.files', printFiles); if (!printFiles || !printFiles.length) { throw "No files available to zip"; } var params = { files: printFiles.select(function(x) { return { internalFilename: x.filename.internal, zipFilename: x.filename.client } }), renameDuplicates: true }; return $http.post(config.baseUrl + "/Handlers/FileHandler.aspx?action=zip", params) .then(function(result) { return result.data; }); }) .then(function (result) { //console.log('PRINTMANAGER.PrintProject.zip', result); var zipFilename = project.title + "-" + project.code + ".zip"; var url = config.baseUrl + "/Handlers/FileHandler.aspx?action=download&file=" + encodeURIComponent(result.file) + "&delete=1&clientfile=" + encodeURIComponent(zipFilename); if (!window.open(url, "_blank")) { return $translate("global.PopupBlockedWarning") .then(function (msg) { throw msg; }); } return Promise.resolve({ filename: zipFilename }); }) .then(function (result) { overlay.remove(); return result; }) .catch(function (error) { overlay.remove(); throw error; });; }); } } }); } PrintManager.$inject = ["config", "$translate", "$http", "gisViewerManager", "aansluitingenService", "aansluitingenModuleService", "aansluitingenAansluitingPrintSettingService", "aansluitingenAansluitingService", "printService"]; return PrintManager; })("aansluitingen"); var basicviewer = basicviewer || {}; basicviewer.Bootstrapper = (function () { function Bootstrapper(config, gisViewerManager) { var bs = this; this.initPanels = function (panelManager, navigationManager) { panelManager.container .on("resize", F.debounce(function () { gisViewerManager.updateSize(); }, 100)); gisViewerManager .on("map-load", function () { var panels = new PanelManager($(".content-container")); //var panels = $scope.$$childTail.panels; panels.container .on("resize", function (e, arg) { if (arg && arg.panel === "bottom" && panels.getMode("bottom") === "half") { panels.setMode("left", "half"); panels.setMode("right", "half"); } }) .on("shown", function (e, arg) { if (arg && arg.panel === "bottom" && panels.getMode("bottom") === "half") { panels.setMode("left", "half"); panels.setMode("right", "half"); } else if (["left", "right"].contains(arg.panel)) { if (panels.isPanelVisible("bottom") && panels.getMode("bottom") === "half") { panels.setMode(arg.panel, "half"); } // else { // panels.setMode(arg.panel, "full"); //} } }) .on("closed", function (e, arg) { if (arg && arg.panel === "bottom") { panels.setMode("left", "full"); panels.setMode("right", "half"); } }); }) .on("center-change start-digitize request-select", function () { //var panels = new PanelManager($(".content-container")); //var panels = $scope.$$childTail.panels; if (panelManager.isPanelVisible("bottom")) { panelManager.setMode("bottom", "half"); } var panel = panelManager.getPanelContainer("right"); //console.log("BVM.PANEL", { panel: panel, panels: panels, mode: panels.getMode("right") }); if (panelManager.isPanelVisible("right") && panelManager.getMode("right") === "full" && (panel.width() > $(window).width() * .5)) { panelManager.setMode("right", "half"); } }) .on("start-digitize start-copy-geom", function () { var wasDisabled = panelManager.panelsDisabled; var wasFrozen = navigationManager.isFrozen; panelManager.disableAllPanels(); navigationManager.freeze(); gisViewerManager.once("end-digitize end-copy-geom", function () { if (!wasDisabled) { panelManager.enableAllPanels(); } if (!wasFrozen) { navigationManager.unfreeze(); } }); }); return Promise.resolve(bs); }; this.initHashEvents = function (locationHashHelper) { var hashEvents = (function () { function getFilter(s) { //console.log("GET_FILTER", s, v); return new Promise(function (resolve) { gisViewerManager.once("map-load", function () { var filter = {}; var layerSegments = s.split("|"); layerSegments.each(function (x) { var layerName = x; var filterValue = null; if (layerName.contains(":")) { filterValue = layerName.split(":").last(); layerName = layerName.split(":").first(); } if (layerName && filterValue) { if (filterValue.split(",").all(function (x) { return !isNaN(parseInt(x)); })) { filterValue = "{id} IN (" + filterValue + ")"; } filter[layerName] = filterValue; } else { filter[layerName] = ""; } }); resolve(filter); }); }); } return { select: [function (v) { return getFilter(v.select) .then(function (filter) { //console.log("H.SELECT", { filter: filter, v: v }); var layerNames = _.toArray(filter).select(function(x) { return x.key; }); return gisViewerManager.setLayerVisibility({ layerName: layerNames, visible: true, updateParents: true }) .then(function () { return gisViewerManager.setSelectedFeatures({ filter: filter, minScale: v.minScale || 100, multi: 1, zoomToSelection: !v.center, showTooltip: !!v.tooltip, layerNames: layerNames, initiator: "user" }) .then(function(result) { if (!result || result.count === 0) { G.handleError({ translate: 'global.NoFeatureFoundInLayer' }); } return result; }); }); }); }], filter: [function (v) { return getFilter(v.filter) .then(function (filter) { //console.log("H.FILTER", filter); return gisViewerManager.setLayerVisibility({ layerName: _.toArray(filter).select(function (x) { return x.key; }), visible: true, updateParents: true }) .then(function () { return gisViewerManager.filter({ filter: filter }); }); }); }], center: [function (v) { //console.log("H.CENTER", v.center); return gisViewerManager.zoom({ center: v.center.trim().replaceAll(",", " ").split(" ").select(function (x) { return parseFloat(x); }) }); }], scale: [function (v) { //console.log("H.SCALE"); return gisViewerManager.zoom({ scale: v.scale }); }], show: [function (v) { //console.log("H.SHOW", v.show); return gisViewerManager.setLayerVisibility({ layerNames: v.show.split(','), visible: true, updateParents: true }); }], hide: [function (v) { //console.log("H.HIDE", v.hide); return gisViewerManager.setLayerVisibility({ layerNames: v.hide.split(','), visible: false, updateParents: true }); }], selectable: [function (v) { //console.log("H.SELECTABLE", v.selectable); return gisViewerManager.setLayerSelectability({ layerNames: v.selectable.split(','), selectable: true }); }], unselectable: [function (v) { //console.log("H.UNSELECTABLE", v.unselectable); return gisViewerManager.setLayerSelectability({ layerNames: v.unselectable.split(','), selectable: false }); }] }; })(); locationHashHelper.addHashchangeEvents(hashEvents); return Promise.resolve(bs); }; } return Bootstrapper; })("basicviewer"); var beheer = beheer || {}; beheer.BeheerController = (function () { function BeheerController(/*config, $http*/) { this.GetSettings = function (name, callback) { G.get({ controller: "Beheer", action: "GetSettings", parameters: { name: name }, success: callback }); } this.GetConnectionStrings = function (name, callback) { G.get({ controller: "Beheer", action: "GetConnectionStrings", parameters: { name: name }, success: callback }); } this.GetUsers = function (niscode, filter, callback) { G.get({ controller: "Beheer", action: "GetUsers", parameters: { niscode: niscode, filter: filter }, success: callback }); } this.GetCodePatches = function (callback) { G.get({ controller: "Beheer", action: "GetCodePatches", success: callback }); } //this.listSettings = function (name) { // return $http.get(config.baseUrl + "/GeoRest/Beheer/GetSettings?name=" + name + "&clientsession=" + config.clientSession + "&clientlanguage=" + config.userLanguage) // .then(function (response) { // return response.data; // }); //} } //BeheerController.$inject = ["config", "$http"]; return BeheerController; })(); var beheer = beheer || {}; beheer.BeheerDirective = (function (moduleName) { "use strict"; function BeheerDirective(config, commandBag, $translate, $timeout, $compile, $rootScope, beheerService) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, link: function ($scope, $el/*, attr*/) { console.log(moduleName.toUpperCase() + "_ROOT"); var module = $scope.modules[moduleName]; var commands = []; module.root = (function () { return { el: $el, config: config, activateTab: function (code) { commands.each(function (cmd) { cmd.active = cmd.name === code; }); var tabEl = $scope.panels.findByClass("beheer-" + code); if (!tabEl) { tabEl = $("
"); tabEl.addClass("beheer-application"); tabEl.addClass("beheer-" + code); $compile(tabEl)($scope); } $scope.panels.show(tabEl, "bottom", "full"); //window.location.hash = "tab=" + module.root.data.ActiveTabCode; setTimeout(function () { tabEl.find(".filter-input").focus(); }, 100); } }; })(); $rootScope.$on("application.loadend", function () { var icons = [ { code: "security", icon: "icon-users-48px-glyph-2_a-edit" }, { code: "settings", icon: "icon-ui-24px-glyph-1_settings-gear-65" }, { code: "connectionstrings", icon: "icon-link-72" }, { code: "translations", icon: "icon-ic_translate_black_24px" }, { code: "codepatches", icon: "icon-patch-34" } ]; return beheerService.getTabs({ tabCodes: icons.select(function (x) { return x.code; }) }).then(function (tabCodes) { commands.addRange(tabCodes.select(function (code) { return { name: code, title: function () { return $translate(moduleName + "." + code); }, content: "" + "", active: false, callback: function () { module.root.activateTab(code); } }; })); return $timeout(function () { return commandBag.add(commands); }).then(function () { return $timeout(function () { var tab = tabCodes.first(); if (tab) { module.root.activateTab(tab); } }, 100); }); }); }); } } } BeheerDirective.$inject = ["config", "commandBag", "$translate", "$timeout", "$compile", "$rootScope", "beheerService"]; return BeheerDirective; })("beheer"); var beheer = beheer || {}; beheer.BeheerService = (function (moduleName) { "use strict"; function BeheerService(config, $http) { EntityServiceBase.call(this, { niscode: config.niscode, url: config.baseUrl + "/GeoRest/Beheer" }, $http); } BeheerService.$inject = ["config", "$http"]; BeheerService.prototype = Object.create(EntityServiceBase.prototype, { constructor: { value: BeheerService }, getTabs: { value: function (o) { var sv = this; return sv._post('GetTabs', o).then(sv._getResponseData); } } }); return BeheerService; })("beheer"); var beheer = beheer || {}; beheer.CodepatchesDirective = (function (moduleName) { function CodepatchesDirective() { return { restrict: "EA", templateUrl: function (el, attr) { return _.toArray(attr).where(function (x) { return x.key.endsWith("Directive") }).select(function (x) { return x.value; }).first() || attr.src; }, link: function ($scope, $el) { var module = $scope.modules[moduleName]; var controller = new beheer.BeheerController(); module.codepatches = (function () { return { data: { items: null, selectedItem: null, results: [] }, refreshItems: function () { controller.GetCodePatches(function (items) { $scope.$apply(function () { module.codepatches.data.items = items; }); }); }, execute: function (item) { if (!confirm('Bent u zeker dat u de volgende patch wilt uitvoeren?\n\n' + item.Id + ': ' + item.Description)) { return; } var overlay = $el.spinnerOverlay({ minimumTime: 500 }); G.get({ controller: "Beheer", action: "ExecuteCodePatch", parameters: { id: item.Id }, success: function (result) { result.executedAt = new Date(); $scope.$apply(function () { module.codepatches.data.results.add(result); }); module.codepatches.refreshItems(); }, always: function () { overlay.hide(); } }); } }; })(); module.codepatches.refreshItems(); } } } return CodepatchesDirective; })("beheer"); var beheer = beheer || {}; beheer.ConnectionstringsDirective = (function (moduleName) { function ConnectionstringsDirective(securityUserService) { return { restrict: "EA", templateUrl: function (el, attr) { return _.toArray(attr).where(function (x) { return x.key.endsWith("Directive") }).select(function (x) { return x.value; }).first() || attr.src; }, link: function ($scope, $el) { var module = $scope.modules[moduleName]; var controller = new beheer.BeheerController(); var cleanItem = function (item) { item.Niscode = $scope.config.isGlobalNiscode ? item.Niscode || '' : $scope.config.niscode; item.Organization = module.connectionstrings.data.organizations.first(function (x) { return x.Niscode === item.Niscode; }); if (item.MachineOnly === undefined) { item.MachineOnly = false; } return item; } module.connectionstrings = (function () { return { data: { items: null, filteredItems: null, filter: null }, init: function () { return securityUserService.getOrganizations().then(function (organizations) { if ($scope.config.isGlobalNiscode) { module.connectionstrings.data.organizations = [{ Name: '', Niscode: '' }]; } module.connectionstrings.data.organizations.addRange(organizations.where(function (x) { return x.Visible; }).orderBy(function (x) { return x.Name || x.Niscode; })); module.connectionstrings.refreshItems(); }); }, refreshItems: function () { controller.GetConnectionStrings(null, function (items) { //var globalItems = items.where(function (x) { return !x.Niscode }); //globalItems.each(function (x) { // x.NiscodeItem = items.where(function (y) { return y.Niscode && y.Name === x.Name }).first() || { // Niscode: config.niscode, // Name: x.Name // }; //}); items.forEach(cleanItem); $scope.$apply(function () { module.connectionstrings.data.items = items; module.connectionstrings.filterItems(); }); }); }, filterItems: function () { var filter = (module.connectionstrings.data.filter || '').toLowerCase(); module.connectionstrings.data.filteredItems = filter ? module.connectionstrings.data.items.where(function (x) { return !x.Id || (x.Name || '').toLowerCase().contains(filter) || (x.Niscode || '').toLowerCase().contains(filter) || (x.ProviderName || '').toLowerCase().contains(filter) || (x.ConnectionString || '').toLowerCase().contains(filter); }) : module.connectionstrings.data.items; }, resetFilter: function () { module.connectionstrings.data.filter = null; module.connectionstrings.filterItems(); }, save: function () { var items = module.connectionstrings.data.items; var newEmptyItems = items.where(function (x) { return !x.Id && !x.HasChanges; }); if (newEmptyItems.length) { newEmptyItems.forEach(function (x) { items.remove(x); }); module.connectionstrings.filterItems(); } var changedItems = items.where(function (x) { return x.HasChanges && !x.Deleted; }); var deletedItems = items.where(function (x) { return x.Deleted; }); if (!changedItems.any() && !deletedItems.any()) { return; } items.forEach(function (item) { item.Niscode = item.Niscode || null; }); var overlay = $el.spinnerOverlay({ minimumTime: 500 }); G.post({ controller: "Beheer", action: "UpdateConnectionStrings", parameters: { saveItems: changedItems, deleteItems: deletedItems }, success: function () { module.connectionstrings.refreshItems(); }, always: function () { overlay.hide(); } }); }, cancel: function () { module.connectionstrings.refreshItems(); }, clearCache: function () { var changedItems = module.connectionstrings.data.items.where(function (x) { return x.HasChanges || x.Deleted; }); if (changedItems.any()) { if (!confirm('Opgepast: u heeft nog openstaande wijzigingen.\nWilt u toch doorgaan en deze verliezen?')) { return; } } var overlay = $el.spinnerOverlay({ minimumTime: 500 }); G.post({ controller: "Beheer", action: "ClearCacheSettings", success: function () { module.connectionstrings.refreshItems(); }, always: function () { overlay.remove(); } }); }, deleteItem: function (item) { if (item.Id) { item.Deleted = true; } else { module.connectionstrings.data.items.remove(item); module.connectionstrings.filterItems(); } }, addItem: function () { module.connectionstrings.data.items.add(cleanItem({})); module.connectionstrings.filterItems(); } }; })(); module.connectionstrings.init(); } } } ConnectionstringsDirective.$inject = ["securityUserService"]; return ConnectionstringsDirective; })("beheer"); var beheer = beheer || {}; beheer.OrganizationFormDirective = (function (moduleName) { function OrganizationFormDirective(config, userService, $translate) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, link: function ($scope, $el) { $scope.currentLanguage = config.taalcode; var module = $scope.modules[moduleName]; if (!module.security.organization) { module.security.organization = {}; } module.security.organization.form = (function () { return { validation: new ValidationHelper($el), data: null, load: function (niscode) { module.security.organization.form.data = Object.defineProperties({}, { item: { value: null, writable: true } }); if (!niscode) niscode = ''; var overlay = $el.spinnerOverlay(); var isNewItem = !niscode; module.security.organization.form.data.isNewItem = isNewItem; module.security.organization.form.data.originalNiscode = niscode; return userService.getOrganizations().then(function (organizations) { module.security.organization.form.data.item = organizations.where(function (x) { return x.Niscode === niscode; }).first() || {}; return userService.getOrganizationModules({ organizationNiscode: niscode }).then(function (organizationModules) { return userService.getOrganizationModuleRoles({ organizationNiscode: niscode }).then(function (organizationModuleRoles) { var roles = module.security.data.roles; var newModule = function (moduleRole) { var organizationModule = organizationModules.where(function (x) { return x.Module === moduleRole.Module; }).first(); var moduleItem = Object.defineProperties({}, { role: { value: moduleRole }, isSelected: { get: function () { return this._isSelected; }, set: function (value) { this._isSelected = value; this.allModuleRoles = false; if (this.allRoles) { this.allRoles.each(function (x) { x.isSelected = false; }); } } } }); moduleItem.isSelected = moduleRole.IsGlobal || organizationModule ? true : false; moduleItem.selectedCount = 0; moduleItem.allModuleRoles = organizationModule ? organizationModule.AllModuleRoles : false; moduleItem.allRoles = roles.specific.where(function (specificRole) { return specificRole.Module === moduleRole.Module && (specificRole.Niscode === '$' || specificRole.Niscode === niscode); }).select(function (specificRole) { var role = Object.defineProperties({}, { role: { value: specificRole }, isSelected: { get: function () { return this._isSelected; }, set: function (value) { var valueChanged = this._isSelected !== undefined && this._isSelected !== value; this._isSelected = value; if (valueChanged) { moduleItem.selectedCount += (value ? 1 : -1); } } } }); role._isSelected = organizationModuleRoles.any(function (x) { return x.Module === specificRole.Module && x.RoleName === specificRole.RoleName && x.RoleNiscode === specificRole.Niscode; }); if (role.isSelected) { moduleItem.selectedCount++; } return role; }); moduleItem.groups = moduleItem.allRoles.groupBy(function (x) { return x.role.CategoryTranslationKey || ''; }).select(function (x) { return { categoryTranslationKey: x.key, isExpanded: false, roles: x.values } }); return moduleItem; }; module.security.organization.form.data.modules = roles.module.select(newModule); }); }); }).catch(function (error) { G.handleError(error); }).then(function () { overlay.hide(); }); }, save: function () { var item = module.security.organization.form.data.item; if (item.Niscode) { item.Niscode = item.Niscode.trim(); } var customValidations = []; var customValidation = Promise.resolve(); if (item.Niscode && item.Niscode.toLowerCase() === "null") { customValidation = customValidation.then(function() { return $translate('beheer.InvalidNiscodeValue').then(function(msg) { customValidations.add({ message: msg, el: $el.find("#OrganizationFormNiscode") }); }); }); } return customValidation.then(function() { if (!module.security.organization.form.validation.validate(customValidations)) { return null; } var overlay = $el.spinnerOverlay(); var modules = module.security.organization.form.data.modules.where(function (x) { return x.isSelected; }).select( function (x) { return { Module: { Module: x.role.Module, AllModuleRoles: x.allModuleRoles }, Roles: x.allRoles.where(function (x) { return x.isSelected; }).select(function (y) { return y.role; }) }; }); return userService.saveOrganization({ Niscode: module.security.organization.form.data.originalNiscode, Organization: item, Modules: modules }).then(function () { $scope.panels.show(module.security.el); module.security.refreshItems(); }).catch(function (error) { G.handleError(error); }).then(function () { overlay.hide(); }); }); }, cancel: function () { $scope.panels.show(module.security.el); module.security.focusFilterInput(); }, remove: function () { return $translate('global.ConfirmDeleteItem').then(function (message) { if (!confirm(message)) { return null; } var item = module.security.organization.form.data.item; var overlay = $el.spinnerOverlay(); return userService.deleteOrganization({ Organization: item }).then(function () { $scope.panels.show(module.security.el); module.security.refreshItems(); }).catch(function (error) { G.handleError(error); }).then(function () { overlay.hide(); }); }); } }; })(); var niscode = $el.attr('data-niscode'); module.security.organization.form.load(niscode); } } } OrganizationFormDirective.$inject = ["config", "securityUserService", "$translate"]; return OrganizationFormDirective; })("beheer"); var beheer = beheer || {}; beheer.RoleListDirective = (function (moduleName) { function RoleListDirective() { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, link: function (scope, el) { //var module = scope.modules[moduleName]; //if (!module.security.role) { // module.security.role = {}; //} //module.security.role.list = (function () { // return { // data: { // items: null, // filteredItems: null, // filter: null // }, // refreshItems: function () { // var overlay = el.spinnerOverlay(); // G.get({ // controller: "Beheer", // action: "GetAllRoles", // success: function (allRoles) { // var sortedRoles = []; // var roles = allRoles; // sortedRoles.addRange(roles.where(function (x) { return x.roleName.startsWith('niscode_'); })); // sortedRoles.addRange(roles.where(function (x) { return x.RoleName.startsWith('module_'); })); // sortedRoles.addRange(roles.where(function (x) { return !x.RoleName.startsWith('niscode_') && !x.RoleName.startsWith('module_'); })); // scope.$apply(function () { // module.security.role.list.data.items = sortedRoles; // module.security.role.list.filterItems(); // }); // }, // always: function () { // overlay.hide(); // } // }); // }, // filterItems: function () { // module.security.role.list.data.filteredItems = module.security.role.list.data.items.where(function (x) { // return !module.security.role.list.data.filter || x.RoleName.toLowerCase().contains(module.security.role.list.data.filter.toLowerCase()) || (x.DisplayName || '').toLowerCase().contains(module.security.role.list.data.filter.toLowerCase()); // }); // }, // resetFilter: function () { // module.security.role.list.data.filter = null; // module.security.role.list.filterItems(); // }, // save: function () { // var items = module.security.role.list.data.items; // var changedItems = items.where(function (x) { return x.HasChanges && !x.Deleted; }); // var deletedItems = items.where(function (x) { return x.Deleted; }); // if (!changedItems.any() && !deletedItems.any()) { // return; // } // var overlay = el.spinnerOverlay(); // G.post({ // controller: "Beheer", // action: "UpdateRoles", // parameters: { // saveItems: changedItems, // deleteItems: deletedItems // }, // success: function () { // scope.panels.show(module.security.el); // module.security.focusFilterInput(); // }, // always: function () { // overlay.hide(); // } // }); // }, // cancel: function () { // scope.panels.show(module.security.el); // module.security.focusFilterInput(); // }, // deleteItem: function (item) { // item.Deleted = true; // } // }; //})(); ////el.on("shown", function() { //module.security.role.list.refreshItems(); ////}); } } } return RoleListDirective; })("beheer"); var beheer = beheer || {}; beheer.SecurityDirective = (function (moduleName) { "use strict"; function SecurityDirective(config, $compile, securityUserService, $translate) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, link: function ($scope, $el) { $scope.currentLanguage = config.taalcode; var module = $scope.modules[moduleName]; function editUser(o) { var username = o.username; var isGroup = o.isGroup; var tabEl = $('
'); tabEl.addClass('beheer-application'); tabEl.attr('data-username', username); tabEl.attr('data-niscode', module.security.data.filterNiscode); tabEl.attr('data-isgroup', isGroup); $compile(tabEl)($scope); $scope.panels.show(tabEl, 'bottom', 'full'); setTimeout(function () { $scope.panels.activate(tabEl); }, 100); } function editOrganization(niscode) { var tabEl = $('
'); tabEl.addClass('beheer-application'); tabEl.attr('data-niscode', niscode); $compile(tabEl)($scope); $scope.panels.show(tabEl, 'bottom', 'full'); setTimeout(function () { $scope.panels.activate(tabEl); }, 100); } function fillRoleDisplay() { var translationKeys = module.security.data.roles.all.select(function (x) { return x.TranslationKey; }).distinct(); return $translate(translationKeys).then(function (translations) { module.security.data.roles.all.forEach(function (role) { if (!role.display) { role.display = {}; } if (!role.display[config.taalcode]) { var translationKey = role.TranslationKey; var display = translations[translationKey].inject({ display: role.DisplayName || '' }); if (display === translationKey) { display = role.RoleName; } role.display[config.taalcode] = display; } }); module.security.data.roles.niscode = module.security.data.roles.niscode.orderBy(function (x) { return x.display[config.taalcode]; }); module.security.data.roles.module = module.security.data.roles.module.orderBy(function (x) { return (x.IsGlobal ? '0' : '1') + (x.CategoryTranslationKey || '') + x.display[config.taalcode]; }); module.security.data.roles.specific = module.security.data.roles.specific.orderBy(function (x) { return x.RoleName }); }); } $scope.$root.$on("$translateChangeEnd", function () { fillRoleDisplay(); }); module.security = (function () { return { el: $el, _userService: securityUserService, config: config, data: { items: null, filteredItems: null, filter: null, checkAll: false }, init: function () { module.security.data.filterNiscode = config.niscode; var overlay = $el.spinnerOverlay(); return securityUserService.getAllRoles().then(function (allRoles) { module.security.data.roles = { all: allRoles, niscode: allRoles.where(function (x) { return x.RoleName.indexOf("niscode_") === 0; }), module: allRoles.where(function (x) { return x.RoleName.indexOf("module_") === 0; }), specific: allRoles.where(function (x) { return x.RoleName.indexOf("niscode_") !== 0 && x.RoleName.indexOf("module_") !== 0; }) }; module.security.data.roles.all.forEach(function (role) { role.TranslationKey = role.TranslationKey || 'beheer.role_' + role.RoleName.toLowerCase(); }); module.security.data.roles.niscode.forEach(function (role) { var niscode = role.RoleName.substr(8); role.OrganizationNiscode = niscode; if (!role.DisplayName) { role.DisplayName = niscode; } }); module.security.data.roles.module.forEach(function (role) { var module = role.RoleName.substr(7); role.Module = module; role.IsGlobal = module === 'global'; if (!role.DisplayName) { role.DisplayName = module.substr(0, 1).toUpperCase() + module.substr(1).toLowerCase(); } }); module.security.data.roles.specific.forEach(function (role) { var index = role.RoleName.indexOf("_"); var module = role.RoleName.substr(0, index); role.Module = module; }); return fillRoleDisplay().then(function () { return module.security.refreshItems(); }); }).catch(function (error) { G.handleError(error); }).then(function () { overlay.hide(); }); }, getUsernameOrGroupname: function (item) { if (item.isGroup) { return item.username.substr(item.niscode.length + 1); } return item.username; }, setUsernameOrGroupname: function (item, username) { if (item.isGroup) { item.username = item.niscode + '_' + username; } else { item.username = username; } return item.username; }, refreshItems: function () { return securityUserService.getOrganizations().then(function (organizations) { module.security.data.organizations = organizations.where(function (x) { return x.Visible; }).orderBy(function (x) { return x.Name || x.Niscode; }); module.security.data.roles.niscode.forEach(function (role) { var organization = module.security.data.organizations.where(function (x) { return x.Niscode === role.OrganizationNiscode; }).first(); role.Display = role.DisplayName || organization.Name || organization.Niscode; }); return securityUserService.list({ organizationNiscode: '', filter: null }).then(function (items) { module.security.data.items = items.orderBy(function (x) { return x.niscode + '_' + (!x.isGroup) + '_' + x.username; }); module.security.filterItems(); module.security.focusFilterInput(); return items; }); }); }, focusFilterInput: function () { setTimeout(function () { $scope.panels.activate($el); $el.find(".filter-input").focus(); }, 100); }, filterItems: function () { var niscode = module.security.data.filterNiscode; var filter = (module.security.data.filter || '').toLowerCase(); //console.log("SECURITY.FILTER_ITEMS", { niscode: niscode, filter: filter, items: module.security.data.items }); module.security.data.filteredItems = module.security.data.items.where(function (x) { if (x.niscode !== niscode) { return false; } if (!filter) { return true; } if (config.isGlobalNiscode) { if ((x.niscode || '').toLowerCase().contains(filter)) { return true; } } return x.username.toLowerCase().contains(filter) || (x.lastName || '').toLowerCase().contains(filter) || (x.firstName || '').toLowerCase().contains(filter) || (x.phone || '').toLowerCase().contains(filter) || (x.email || '').toLowerCase().contains(filter) || (x.fax || '').toLowerCase().contains(filter); }); }, resetFilter: function () { module.security.data.filter = null; module.security.filterItems(); }, editFirstUser: function () { var user = module.security.data.filteredItems.first(); if (user) { module.security.editItem(user); } }, deleteItem: function (item) { if (!confirm('Bent u zeker dat u de ' + (item.isGroup ? 'groep' : 'gebruiker') + ' ' + item.username + ' wilt verwijderen?')) { return; } var overlay = $el.spinnerOverlay(); G.post({ controller: "Beheer", action: "DeleteUser", parameters: { username: item.username }, success: function () { module.security.data.items.remove(item); $scope.$apply(function () { module.security.filterItems(); }); }, always: function () { overlay.hide(); } }); }, addUser: function () { editUser({ isGroup: false }); }, addGroup: function () { editUser({ isGroup: true }); }, editItem: function (item) { editUser({ username: item.username }); }, editItems: function () { var usernames = module.security.data.items.where(function (x) { return x.isChecked; }).select(function (x) { return x.username; }); if (!usernames.any()) { $el.messageOverlay("Gelieve een gebruiker/groep te selecteren.", { type: 'validate' }); return; } editUser({ username: usernames }); }, editOrganization: function (niscode) { editOrganization(niscode); }, checkAllChanged: function () { module.security.data.items.each(function (x) { x.isChecked = module.security.data.checkAll; }); }, isCheckedChanged: function () { module.security.data.checkAll = module.security.data.items.all(function (x) { return x.isChecked; }); }, editRoles: function () { var tabEl = $('
'); tabEl.addClass('beheer-application'); $compile(tabEl)($scope); $scope.panels.show(tabEl, 'bottom', 'full'); setTimeout(function () { $scope.panels.activate(tabEl); tabEl.find(".filter-input").focus(); }, 100); } }; })(); module.security.init(); } } } SecurityDirective.$inject = ["config", "$compile", "securityUserService", "$translate"]; return SecurityDirective; })("beheer"); var beheer = beheer || {}; beheer.UserFormDirective = (function (moduleName) { function UserFormDirective(config, userService, $translate, $timeout) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, link: function ($scope, $el) { $scope.currentLanguage = config.taalcode; var module = $scope.modules[moduleName]; if (!module.security.user) { module.security.user = {}; } function fillParentGroupNames(parentGroupNames, selectedGroupnames) { if (!selectedGroupnames) { return; } selectedGroupnames.forEach(function (groupName) { var parentNames = module.security.user.form.data.allGroupGroupConnections.where(function (x) { return x.ChildLogin.toLowerCase() === groupName.toLowerCase(); }).select(function (x) { return x.GroupLogin; }); parentGroupNames.addRange(parentNames); fillParentGroupNames(parentGroupNames, parentNames); }); } function fillGroupMemberNames(groupMemberNames, selectedUsernames) { if (!selectedUsernames) { return; } selectedUsernames.forEach(function (groupName) { var memberNames = module.security.user.form.data.allGroupGroupConnections.where(function (x) { return x.GroupLogin.toLowerCase() === groupName.toLowerCase(); }).select(function (x) { return x.ChildLogin; }); groupMemberNames.addRange(memberNames); fillGroupMemberNames(groupMemberNames, memberNames); }); } var organizationCache = {}; function getOrganizationModules(organizationNiscode) { if (!organizationCache.modules) { organizationCache.modules = {}; } if (organizationCache.modules[organizationNiscode]) { return new Promise(function (resolve) { resolve(organizationCache.modules[organizationNiscode]); }); } if (!organizationNiscode) { return new Promise(function (resolve) { resolve(); }); } return userService.getOrganizationModules({ organizationNiscode: organizationNiscode }).then(function (result) { organizationCache.modules[organizationNiscode] = result; return result; }); } function getOrganizationRoles(organizationNiscode) { if (!organizationCache.roles) { organizationCache.roles = {}; } if (organizationCache.roles[organizationNiscode]) { return new Promise(function (resolve) { resolve(organizationCache.roles[organizationNiscode]); }); } if (!organizationNiscode) { return new Promise(function (resolve) { resolve(); }); } return userService.getOrganizationModuleRoles({ organizationNiscode: organizationNiscode }).then(function (result) { organizationCache.roles[organizationNiscode] = result; return result; }); } module.security.user.form = (function () { return { validation: new ValidationHelper($el), data: null, loadUser: function (username, niscode, isGroup) { module.security.user.form.data = Object.defineProperties({}, { groups: { value: [], writable: true }, groupMembers: { value: [], writable: true }, blacklistUsernames: { value: { groups: [], groupMembers: [] } }, item: { value: null, writable: true }, selectedRoles: { value: null, writable: true }, allGroupGroupConnections: { value: null, writable: true } }); var overlay = $el.spinnerOverlay(); var isNewItem = !username; module.security.user.form.data.isNewItem = isNewItem; module.security.user.form.data.organizations = module.security.data.organizations.orderBy(function (x) { return x.Name || x.Niscode; }); return userService.details({ username: username || '' }).then(function (result) { var item = result.user || {}; var data = module.security.user.form.data; data.item = item; item.originalUsername = item.username; data.selectedRoles = result.roles || []; if (isNewItem) { item.niscode = config.isGlobalNiscode && niscode ? niscode : config.niscode; item.isGroup = isGroup; } else { if (item.isGroup) { item.groupname = module.security.getUsernameOrGroupname(item); } } data.organization = data.organizations.where(function (x) { return x.Niscode === item.niscode; }).first(); data.filterRolesNiscode = item.niscode; //groups (alleen bij formsauthentication) if (config.authentication.isFormsAuthenticated) { return userService.getGroupConnections({ childIsGroup: true }).then(function (groupGroupConnections) { data.allGroupGroupConnections = groupGroupConnections; if (isNewItem) { return Promise.resolve(); } return userService.getGroupConnections({ childLogin: username || '' }) .then(function (userGroupConnections) { return Promise.all( userGroupConnections.select(function (userGroupConnection) { return userService.details({ username: userGroupConnection.GroupLogin, inheritedRoles: true }); })).then(function (groups) { data.groups = groups; return userService.getGroupUsers({ groupLogin: username || '' }).then(function (groupUsers) { data.groupMembers = groupUsers.orderBy(function (x) { return (x.isGroup ? "0" : "1") + userService.getUserDisplay(x); }); module.security.user.form.refreshBlacklistUsernames(); return Promise.resolve(); }); }); }); }); } return Promise.resolve(); }) .then(function () { return module.security.user.form.filterRoles(); }) .catch(G.handleError) .then(function () { overlay.hide(); }); }, filterRoles: function () { var overlay = $el.spinnerOverlay(); var data = module.security.user.form.data; var niscode = data.filterRolesNiscode; var roles = module.security.data.roles; var getInheritedFromGroups = function (role) { return module.security.user.form.data.groups.where(function (group) { return group.roles.any(function (x) { return x.RoleName === role.RoleName && x.Niscode === role.Niscode; }); }).select(function (x) { return module.security._userService.getUserDisplay(x.user); }).join(', '); } return getOrganizationModules(niscode).then(function (organizationModules) { return getOrganizationRoles(niscode).then(function (organizationRoles) { var newModule = function (organizationModule) { var moduleRole = roles.module.where(function (x) { return x.Module === organizationModule.Module; }).first(); if (moduleRole == null) { return null; } var moduleItem = Object.defineProperties({}, { role: { value: moduleRole }, _isSelected: { value: moduleRole.IsGlobal ? true : data.selectedRoles.any(function (x) { return x.RoleName === moduleRole.RoleName && x.Niscode === moduleRole.Niscode; }), writable: true }, isSelected: { get: function () { return this._isSelected; }, set: function (value) { var me = this; me._isSelected = value; if (!me.inheritedFromGroups) { me.allRoles.forEach(function (x) { x.isSelected = false; }); } if (value) { data.selectedRoles.add(me.role); } else { data.selectedRoles.remove(function (x) { return x.RoleName === me.role.RoleName && x.Niscode === me.role.Niscode; }); } } }, inheritedFromGroups: { value: getInheritedFromGroups(moduleRole) } }); moduleItem.selectedCount = 0; if (moduleItem.isSelected) { if (moduleItem.inheritedFromGroups) { data.selectedRoles.remove(function (x) { return x.RoleName === moduleItem.role.RoleName && x.Niscode === moduleItem.role.Niscode; }); } } var moduleRoles = roles.specific.where(function (specificRole) { return specificRole.Module === moduleRole.Module && (specificRole.Niscode === '$' || specificRole.Niscode === niscode); }); if (!organizationModule.AllModuleRoles) { moduleRoles = moduleRoles.where(function (specificRole) { return organizationRoles.any(function (organizationRole) { return specificRole.RoleName === organizationRole.RoleName && specificRole.Niscode === organizationRole.RoleNiscode; }); }); } moduleItem.allRoles = moduleRoles.select(function (specificRole) { var role = Object.defineProperties({}, { role: { value: specificRole }, _isSelected: { value: data.selectedRoles.any(function (x) { return x.RoleName === specificRole.RoleName && x.Niscode === specificRole.Niscode; }), writable: true }, isSelected: { get: function () { return this._isSelected; }, set: function (value) { var me = this; var valueChanged = me._isSelected !== undefined && me._isSelected !== value; me._isSelected = value; if (valueChanged) { moduleItem.selectedCount += (value ? 1 : -1); if (value) { data.selectedRoles.add(me.role); } else { data.selectedRoles.remove(function (x) { return x.RoleName === me.role.RoleName && x.Niscode === me.role.Niscode; }); } } } }, inheritedFromGroups: { value: getInheritedFromGroups(specificRole) } }); if (role.isSelected) { moduleItem.selectedCount++; if (role.inheritedFromGroups) { data.selectedRoles.remove(function (x) { return x.RoleName === role.role.RoleName && x.Niscode === role.role.Niscode; }); } } return role; }); moduleItem.groups = moduleItem.allRoles .groupBy(function (x) { return x.role.CategoryTranslationKey || ''; }) .select(function (x) { return { categoryTranslationKey: x.key, isExpanded: false, roles: x.values } }); return moduleItem; }; var newNiscode = function () { var niscodeRole = roles.niscode.where(function (niscodeRole) { return niscodeRole.OrganizationNiscode === niscode; }).first(); var item = Object.defineProperties({}, { role: { value: niscodeRole }, _isSelected: { value: data.selectedRoles.any(function (x) { return x.RoleName === niscodeRole.RoleName && x.Niscode === niscodeRole.Niscode; }), writable: true }, isSelected: { get: function () { return this._isSelected; }, set: function (value) { var me = this; var valueChanged = me._isSelected !== undefined && me._isSelected !== value; me._isSelected = value; if (valueChanged) { if (value) { data.selectedRoles.add(me.role); } else { data.selectedRoles.remove(function (x) { return x.RoleName === me.role.RoleName && x.Niscode === me.role.Niscode; }); } } } }, inheritedFromGroups: { value: getInheritedFromGroups(niscodeRole) } }); return item; }; $timeout(function () { module.security.user.form.data.niscode = newNiscode(); var modules = organizationModules.select(newModule); module.security.user.form.data.modules = modules.where(function (x) { return (x.role.IsGlobal && x.allRoles.any()) || !x.role.IsGlobal; }).orderBy(function (x) { return (x.role.IsGlobal ? '0' : '1') + x.role.display[$scope.currentLanguage]; }); }); return Promise.resolve(); }); }).catch(function (error) { overlay.hide(); throw error; }).then(function (result) { overlay.hide(); return result; }); }, refreshBlacklistUsernames: function () { var data = module.security.user.form.data; data.blacklistUsernames.groups = [data.item.username]; data.blacklistUsernames.groupMembers = [data.item.username]; //alle gekoppelde parents en die hun parents mogen NIET als member gekozen worden var parentGroupNames = data.groups.select(function (x) { return x.user.username; }); data.blacklistUsernames.groups.addRange(parentGroupNames); var allParentGroupnames = parentGroupNames; fillParentGroupNames(allParentGroupnames, allParentGroupnames); data.blacklistUsernames.groupMembers.addRange(allParentGroupnames); //alle members en hun members mogen NIET als parent gekozen worden var groupMemberNames = data.groupMembers.select(function (x) { return x.username; }); data.blacklistUsernames.groupMembers.addRange(groupMemberNames); var allGroupMembernames = groupMemberNames; fillGroupMemberNames(allGroupMembernames, allGroupMembernames); data.blacklistUsernames.groups.addRange(allGroupMembernames); }, userSelectConfirmed: function (o) { var dataType = module.security.user.form.data.isSelectingUser; module.security.user.form.data.isSelectingUser = null; if (dataType === 'groups') { Promise.all(o.selected.select(function (user) { return userService.details({ username: user.username, inheritedRoles: true }); })).then(function (groups) { $timeout(function () { module.security.user.form.data[dataType].addRange(groups); module.security.user.form.refreshBlacklistUsernames(); module.security.user.form.filterRoles(); }); }); } else if (dataType === 'groupMembers') { module.security.user.form.data[dataType].addRange(o.selected); module.security.user.form.refreshBlacklistUsernames(); } }, userSelectCancelled: function () { module.security.user.form.data.isSelectingUser = null; }, showGroupMembers: function (groupItem) { return userService.getGroupUsers({ groupLogin: groupItem.username }).then(function (users) { return $translate('global.GroupMembers').then(function (title) { var msg = title + " " + userService.getUserDisplay(groupItem) + ":"; users.each(function (item) { msg += "
- " + userService.getUserDisplay(item); }); throw msg; }); }).catch(function (error) { G.handleError(error); }); }, save: function () { var item = module.security.user.form.data.item; var customValidations = []; if (item.password1 || item.password2) { if (item.password1 && !item.password2) { customValidations.add({ message: 'Gelieve het nieuwe wachtwoord te herhalen.', el: $el.find("#UserFormPassword2") }); } else if (!item.password1 && item.password2) { customValidations.add({ message: 'Gelieve het nieuwe wachtwoord te herhalen.', el: $el.find("#UserFormPassword1") }); } else if (item.password1 !== item.password2) { customValidations.add({ message: 'Gelieve het nieuwe wachtwoord correct te herhalen.', el: $el.find("#UserFormPassword1") }); } } if (!item.isGroup && item.username && item.username.toLowerCase().startsWith(item.niscode.toLowerCase() + '_')) { customValidations.add({ message: 'Een gebruikersnaam mag niet beginnen met de niscode gevolgd door een liggend streepje.', el: $el.find("#UserFormUsername") }); } if (!module.security.user.form.validation.validate(customValidations)) { return null; } var username = item.username; if (item.isGroup) { username = module.security.setUsernameOrGroupname(item, item.groupname); } if (item.originalUsername && item.originalUsername !== username) { if (!confirm('Opgepast: u gaat de ' + (item.isGroup ? 'groepsnaam' : 'gebruikersnaam') + ' veranderen, bent u zeker dat u wilt doorgaan?')) { return null; } } var overlay = $el.spinnerOverlay(); return Promise.resolve().then(function () { var selectedRoles = module.security.user.form.data.selectedRoles; var roleNames = selectedRoles.toDictionary(function (x) { return x.Niscode; }, function (x) { return selectedRoles.where(function (y) { return y.Niscode === x.Niscode; }).select(function (y) { return y.RoleName; }); }); return userService.save({ User: item, NewPassword: item.password1, OldUsername: item.originalUsername, RoleNames: roleNames, GroupNames: module.security.user.form.data.groups.select(function (x) { return x.user.username; }), GroupMemberNames: module.security.user.form.data.groupMembers.select(function (x) { return x.username; }) }).then(function () { $scope.panels.show(module.security.el); return module.security.refreshItems(); }); }).catch(function (error) { G.handleError(error); }).then(function () { overlay.hide(); }); }, cancel: function () { $scope.panels.show(module.security.el); module.security.focusFilterInput(); } }; })(); var username = $el.attr('data-username'); var niscode = $el.attr('data-niscode'); var isGroup = $el.attr('data-isgroup') && $el.attr('data-isgroup') === "true"; module.security.user.form.loadUser(username, niscode, isGroup); } } } UserFormDirective.$inject = ["config", "securityUserService", "$translate", "$timeout"]; return UserFormDirective; })("beheer"); var beheer = beheer || {}; beheer.SettingsDirective = (function (moduleName) { function SettingsDirective(securityUserService, langConfig) { return { restrict: "EA", //templateUrl: function ($el, $attr) { // return $attr.beheerSettings || $attr.src; //}, templateUrl: ModuleManager.templateUrl, link: function ($scope, $el) { $scope.modules = $scope.modules || {}; $scope.modules[moduleName] = $scope.modules[moduleName] || {}; var module = $scope.modules[moduleName]; var controller = new beheer.BeheerController(/*config, $http*/); var cleanItem = function (item) { item.Niscode = $scope.config.isGlobalNiscode ? item.Niscode || '' : $scope.config.niscode; item.Organization = module.settings.data.organizations.first(function (x) { return x.Niscode === item.Niscode; }); if (item.MachineOnly === undefined) { item.MachineOnly = false; } return item; } module.settings = (function () { return { data: { items: null, filteredItems: null, filter: null }, init: function () { module.settings.data.languages = [{ code: '' }]; module.settings.data.languages.addRange(langConfig.languages); return securityUserService.getOrganizations().then(function (organizations) { if ($scope.config.isGlobalNiscode) { module.settings.data.organizations = [{ Name: '', Niscode: '' }]; } module.settings.data.organizations.addRange(organizations.where(function (x) { return x.Visible; }).orderBy(function (x) { return x.Name || x.Niscode; })); module.settings.refreshItems(); }); }, refreshItems: function () { controller.GetSettings(null, function (items) { //var globalItems = items.where(function(x) { return !x.Niscode }); //globalItems.each(function (x) { // x.NiscodeItem = items.where(function(y) { return y.Niscode && y.Name === x.Name }).first() || { // Niscode: config.niscode, // Name: x.Name // }; //}); items.forEach(cleanItem); $scope.$apply(function () { module.settings.data.items = items; module.settings.filterItems(); }); }); //return controller.listSettings(null) // .then(function (items) { // $timeout(function () { // module.settings.data.items = items; // module.settings.filterItems(); // }); // }); }, filterItems: function () { var filter = (module.settings.data.filter || '').toLowerCase(); module.settings.data.filteredItems = filter ? module.settings.data.items.where(function (x) { return !x.Id || (x.Name || '').toLowerCase().contains(filter) || (x.Value || '').toLowerCase().contains(filter) || (x.Niscode || '').toLowerCase().contains(filter); }) : module.settings.data.items; }, resetFilter: function () { module.settings.data.filter = null; module.settings.filterItems(); }, save: function () { var items = module.settings.data.items; var newEmptyItems = items.where(function (x) { return !x.Id && !x.HasChanges; }); if (newEmptyItems.length) { newEmptyItems.forEach(function (x) { items.remove(x); }); module.settings.filterItems(); } var changedItems = items.where(function (x) { return x.HasChanges && !x.Deleted; }); var deletedItems = items.where(function (x) { return x.Deleted; }); if (!changedItems.any() && !deletedItems.any()) { return; } items.forEach(function (item) { item.Niscode = item.Niscode || null; }); var overlay = $el.spinnerOverlay({ minimumTime: 500 }); G.post({ controller: "Beheer", action: "UpdateSettings", parameters: { saveItems: changedItems, deleteItems: deletedItems }, success: function () { module.settings.refreshItems(); }, always: function () { overlay.hide(); } }); }, cancel: function () { module.settings.refreshItems(); }, clearCache: function () { var changedItems = module.settings.data.items.where(function (x) { return x.HasChanges || x.Deleted; }); if (changedItems.any()) { if (!confirm('Opgepast: u heeft nog openstaande wijzigingen.\nWilt u toch doorgaan en deze verliezen?')) { return; } } var overlay = $el.spinnerOverlay({ minimumTime: 500 }); G.post({ controller: "Beheer", action: "ClearCacheSettings", success: function () { module.settings.refreshItems(); }, always: function () { overlay.remove(); } }); }, deleteItem: function (item) { if (item.Id) { item.Deleted = true; } else { module.settings.data.items.remove(item); module.settings.filterItems(); } }, addItem: function () { module.settings.data.items.add(cleanItem({})); module.settings.filterItems(); } }; })(); module.settings.init(); } } } SettingsDirective.$inject = ["securityUserService", "langConfig"]; return SettingsDirective; })("beheer"); var beheer = beheer || {}; beheer.TranslationsDirective = (function (moduleName) { function TranslationsDirective(config) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, link: function ($scope, $el) { var module = $scope.modules[moduleName]; var hasChangesInjectInto = function(target) { Object.defineProperties(target, { HasChanges: { get: function () { return this._hasChanges; }, set: function (value) { this._hasChanges = value; if (value) { module.translations.data.hasChanges = true; } } } }); return target; } module.translations = (function () { return { data: { items: null, filteredItems: null, filter: { lang: config.preferredLanguage, showOnlyEmpty: false }, languages: null, newItem: {}, hasChanges: false }, refreshItems: function () { G.get({ url: config.translateUrl + "&flatlist=true", success: function (items) { $scope.$apply(function () { module.translations.data.hasChanges = false; module.translations.data.items = items; items.forEach(hasChangesInjectInto); module.translations.data.languages = items.select(function (x) { return x.Language; }).distinct().where(function (x) { return x !== 'nl' }).orderBy(function (x) { return x; }); if (!module.translations.data.languages.contains(module.translations.data.filter.lang)) { module.translations.data.filter.lang = module.translations.data.languages.first(); } module.translations.filterItems(); }); } }); }, filterItems: function () { var allItems = module.translations.data.items; if (!allItems) { return; } var filter = module.translations.data.filter; var filterText = (filter.text || '').toLowerCase(); var filteredItems = allItems.where(function (x) { //if (filter.lang) { // if (x.Language.toLowerCase() !== filter.lang.toLowerCase()) { // return false; // } //} if (filter.module) { if (x.Module.toLowerCase() !== filter.module.toLowerCase()) { return false; } } if (filter.code) { if (!x.Code.toLowerCase().contains(filter.code.toLowerCase())) { return false; } } if (filter.label) { if (!x.Label.toLowerCase().contains(filter.label.toLowerCase())) { return false; } } return !filterText || x.Module.toLowerCase().contains(filterText) || (x.Code || '').toLowerCase().contains(filterText) || (x.Label || '').toLowerCase().contains(filterText); }); var result = []; var modules = filteredItems.select(function (x) { return x.Module; }).distinct().orderBy(function (x) { return x; }); modules.each(function (module) { var codes = filteredItems.where(function (x) { return x.Module === module; }).select(function (x) { return x.Code; }).distinct().orderBy(function (x) { return x; }); codes.each(function (code) { var nl = allItems.where(function (x) { return x.Module === module && x.Code === code && x.Language.toLowerCase() === 'nl'; }).first(); if (nl === null) { nl = hasChangesInjectInto({ Module: module, Code: code, Language: 'nl', Label: '' }); allItems.add(nl); } var lang = filter.lang !== 'nl' ? allItems.where(function (x) { return x.Module === module && x.Code === code && x.Language.toLowerCase() === filter.lang.toLowerCase(); }).first() || null : null; if (lang === null) { lang = hasChangesInjectInto({ Module: module, Code: code, Language: filter.lang.toLowerCase(), Label: '' }); allItems.add(lang); } result.add({ Module: module, Code: code, nl: nl, lang: lang }); }); }); if (filter.showOnlyEmpty) { result = result.where(function (x) { return !x.nl.Label || !x.lang.Label; }); } module.translations.data.filteredItems = result; }, resetFilter: function () { module.translations.data.filter.text = null; module.translations.filterItems(); }, save: function () { var items = module.translations.data.items; var changedItems = items.where(function (x) { return x.HasChanges; }); //&& !x.Deleted var deletedItems = items.where(function (x) { return x.Deleted; }); if (!changedItems.any() && !deletedItems.any()) { return; } if (deletedItems.any()) { //dit zijn de nl translations, haal ook de rest op var otherDeletedItems = items.where(function (x) { return deletedItems.any(function (y) { return y.Module === x.Module && y.Code === x.Code; }); }); deletedItems.addRange(otherDeletedItems); } var overlay = $el.spinnerOverlay({ minimumTime: 500 }); var hideOverlay = function () { overlay.hide(); }; G.post({ url: config.translateHandlerUrl + "?action=save", parameters: JSON.stringify(changedItems), success: function () { G.post({ url: config.translateHandlerUrl + "?action=delete", parameters: JSON.stringify(deletedItems), success: function () { module.translations.refreshItems(); }, always: hideOverlay }); }, afterError: hideOverlay }); }, cancel: function () { module.translations.refreshItems(); }, changeLang: function (lang) { module.translations.data.filter.lang = lang; module.translations.filterItems(); }, addItem: function () { var key = prompt("Vertaling key (module.code)"); if (key) { var label = prompt("Nederlandse label"); if (label) { var data = key.trim().split('.'); var moduleName = (data.length === 2 ? data[0] : "global").toLowerCase(); var code = data.length === 2 ? data[1] : data[0]; module.translations.data.items.add({ Module: moduleName, Code: code, Language: 'nl', Label: label, HasChanges: true }); module.translations.data.hasChanges = true; module.translations.filterItems(); } } } }; })(); module.translations.refreshItems(); } } } TranslationsDirective.$inject = ["config"]; return TranslationsDirective; })("beheer"); var bomen = bomen || {}; bomen.BomenDirective = (function (moduleName) { function BomenDirective(config, boomService, geoHelper, gisViewerManager, gisVectorManager, $translate, $timeout) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, controller: bomen.BoomController, controllerAs: "ctrl", link: function ($scope, $el, $attr, $ctrl) { console.log(moduleName.toUpperCase(), config, $.extend(true, {}, $scope), $attr, $ctrl, $el, $el.find(".upload-container")); var fm = $el.find(".upload-container"); var moduleScope = {}; $scope.modules["bomen"] = $.extend(moduleScope, { css: $.loadCss("Content/modules/bomen/bomen.css"), mapName: null, layer: null, overlay: null, openForm: function () { $scope.panels.show($el, "bottom", "half"); }, show: function (id) { return $ctrl.show(id, "form") .then(function (item) { $ctrl.item.files = ($ctrl.item.files || []).select(function (file) { return moduleScope.convertGisDocumentToFile(file); }); return item; }) .then(function (item) { var soort = $ctrl.soorten.first(function (x) { return x.scientific === item.soort; }); if (soort) { moduleScope.soortImg = config.baseUrl + "/Handlers/SymbolHandler.aspx?img=Bomen/" + soort.image; } return item; }); }, cancel: function () { return moduleScope.show($ctrl.item ? $ctrl.item.id : null) .then(function (item) { return new Promise( function (resolve) { geoHelper.getGeometryObject(item.wkt, function (geom) { resolve(geom); }); }) .then(function (geom) { moduleScope.updateGeom(geom); return item; }); }); }, save: function () { var filesToUpload = $ctrl.item.files.where(function (x) { return x.file; }).select(function (x) { return x.file; }); $ctrl.item.files = $ctrl.item.files.where(function (x) { return !x.deleted; }).select(function (x) { return x.data; }); console.log("B.SAVING", $ctrl.item, filesToUpload); $el.spinnerOverlay(); fm.filemanager("upload", filesToUpload, function (arg) { filesToUpload.each(function (file) { var uploadSuccess = arg.uploaded.any(function (x) { return x.name === file.alias }); if (!uploadSuccess) { throw "Uploaden bestand '" + file.alias + "' is mislukt."; } }); $ctrl.save() .then(function () { $el.removeOverlay(); $ctrl.item.files = ($ctrl.item.files || []).select(function (file) { return moduleScope.convertGisDocumentToFile(file); }); return gisViewerManager.refreshMap(); }); }); }, browseFile: function (callback) { fm.filemanager("browse", callback); }, updateGeom: function (geom) { console.log("B.UPDATE_GEOM", $ctrl.item, geom); var promise; if ($ctrl.hasNewItem()) { promise = moduleScope.toGeoJsonFeature($ctrl.item) .then(function (feature) { console.log("B.NEW", feature); return gisVectorManager.feature.add({ layer: moduleScope.layer, features: [feature] }) .then(function () { return [feature]; }); }); } else { promise = gisVectorManager.feature.find({ layer: moduleScope.layer, filter: function (x) { return x.properties.id === $ctrl.item.id; } }); } promise .then(function (features) { console.log("B.FIND", features); return features; }) .then(function (features) { var feature = features.first(); feature.geometry = geom; return feature; }) .then(function (feature) { return gisVectorManager.feature.update({ layer: moduleScope.layer, features: [feature] }); }); }, setGeometry: function (o) { return new Promise( function (resolve) { switch (o.type) { case "Point": $scope.gis.digitize.point(function (geom) { resolve(geom); }); break; case "MyLocation": $scope.gis.digitize.myLocation(function (geom) { gisViewerManager.zoom({ center: geom.geoJson.coordinates }) .then(function () { resolve(geom); }); }); break; } }) .then(function (geom) { return $timeout(function () { $ctrl.item.wkt = geom.wkt; return geom; }) .then(function (geom) { return moduleScope.updateGeom(geom.geoJson); }); }); }, loadSelection: function () { return gisViewerManager.getSelectedFeatures({ layerName: config.layerName, properties: 1 }) .then(function (items) { var id = null; if (items[config.layerName] && items[config.layerName].any()) { id = items[config.layerName].select(function (x) { return x[Object.keys(x).first()]; }).first(); } return $timeout(function () { return moduleScope.show(id); }); }); }, toGeoJsonFeature: function (item) { return new Promise(function (resolve) { var iconUrl = null; var soort = $ctrl.soorten.first(function (x) { return x.scientific === item.soort; }); if (soort) { iconUrl = config.baseUrl + "/Handlers/SymbolHandler.aspx?img=Bomen/" + soort.image; } if (!iconUrl) { iconUrl = config.baseUrl + "/Handlers/SymbolHandler.aspx?img=Bomen/Tree-1.png"; } geoHelper.getGeometryObject(item.wkt, function (geom) { var feature = { type: "Feature", geometry: geom, properties: { id: item.id, style: { transparency: 25, image: { iconUrl: iconUrl, positioning: "center center", width: 20, height: 20, scale: 100, minHeight: 1 } } } }; resolve(feature); }); }); }, getFileSrc: function (file) { return config.baseUrl + "/Handlers/GisDocumentHandler.aspx?niscode=" + config.niscode + "&id=" + file.id + "&v=" + new Date().getTime(); }, convertGisDocumentToFile: function (item, file) { console.log("B.CONVERT", item, file); return { file: file, data: item, name: item.document, src: file ? null : moduleScope.getFileSrc(item) } } }); $scope.gis.addEvents(moduleScope.gisEvents, moduleName); gisViewerManager .on("map-load", function (e, arg) { moduleScope.mapName = arg.mapinfo.Name; //var commands = [ // { name: "menu" }, // { parent: "menu", name: "Home" }, // { parent: "menu", module: "Languages", name: "ChooseLanguage" }, // { parent: "menu", name: "Logout" }, // { module: moduleName, name: "OpenBomen" }, // { module: "Print", name: "Print" }, // { module: "MyLocation", name: "ShowMyLocation" }, // { module: "Crab", name: "ToggleCrab" }, // { module: "Measure", name: "Measure" }, // { name: "Refresh" }, // { name: "Legend" } //]; //NavigationManager.addCommands(commands); $translate("bomen.Trees") .then(function (bomenTitle) { return gisVectorManager.layer.createIfNotExists({ Code: config.layerName, Title: bomenTitle }); }) .then(function (layer) { moduleScope.layer = layer; console.log("B.LAYER", layer); return $ctrl.init() .then(function (items) { console.log("B.ITEMS", items); Promise.all(items.select(function (x) { return moduleScope.toGeoJsonFeature(x); })) .then(function (features) { console.log("B.FEATURES", features); return gisVectorManager.feature.add({ layer: layer, features: features }); }); }); }); }) .on("selection-change", function (e, arg) { console.log("B.SELECTION", arg); function removeOverlay() { return new Promise(function (resolve) { $scope.gis.viewer.gisviewer("removeOverlay", { el: moduleScope.overlay }, function (arg) { resolve(arg); }); }); } function setOverlay(o) { return new Promise(function (resolve) { $scope.gis.viewer.gisviewer("setOverlay", { el: o.el, geom: o.geom, positioning: "bottom center" }, function (arg) { resolve(arg.el); }); }); } function edit(itemId) { $timeout(function () { return moduleScope.show(itemId); }) .then(function (item) { return new Promise(function (resolve) { geoHelper.getGeometryObject(item.wkt, function (geom) { resolve(geom); }); }); }) .then(function (geom) { return removeOverlay() .then(function () { return geom; }); }) .then(function (geom) { moduleScope.openForm(); return geom; }) .then(function (geom) { return gisViewerManager.zoom({ center: geom.coordinates, scale: 500 }); }); } var promise = removeOverlay(); var selectedId = arg.selection && arg.selection.features && arg.selection.features[config.layerName] ? arg.selection.features[config.layerName].select(function (x) { return x.properties.id; }).first() : null; if (!selectedId) { return; } promise.then( function () { return boomService.details(selectedId); }) .then(function (item) { $translate(["global.Edit", "global.Close"]) .then(function (translations) { console.log("B.TRANSLATIONS", translations); return $("
") .addClass("boom-overlay") .append($("").text("Boom " + item.id)) .append( $("
").append("soort,description".split(",").select(function (x) { return "
" + x + "
" + item[x] + "
"; })) ) .append(item.files && item.files.any() ? $("
").addClass("thumbnail").append($("").attr({ src: moduleScope.getFileSrc(item.files.first()) })) : null) .append( $("").addClass("edit") .attr({ href: "#", title: translations["global.Edit"] }) .append('') .click(function () { edit(item.id); }), $("").addClass("close") .attr({ href: "#", title: translations["global.Close"] }) .append('') .click(function () { removeOverlay() .then(function () { return gisViewerManager.clearSelection(); }); }) ); }) .then(function (el) { return setOverlay({ el: el, geom: item.wkt }); }) .then(function (overlay) { moduleScope.overlay = overlay; }); }); }); //ModuleManager.registerCommands(moduleName, [{ // name: "OpenBomen", // icon: "glyphicon glyphicon-tree-deciduous", // title: function () { // return $scope.lang.translate("Trees", moduleName); // }, // callback: function () { // //new item // gisViewerManager.clearSelection() // .then(function () { // return $timeout(function () { // return moduleScope.show(null); // }); // }) // .then(function () { // moduleScope.openForm(); // }); // } //}]); fm .filemanager({ files: [], uploadUrl: "Upload/Html5Upload.aspx?niscode=" + config.niscode, overwrite: true, accept: "image/*", multiple: true, autoUpload: false, droppable: true, update: function (e, arg) { var item = $ctrl.item; if (!item) { return; } $timeout(function () { arg.added.each(function (x) { var gisDocument = { Kaart: moduleScope.mapName, Laag: moduleScope.layer.Code, Feature: $ctrl.item.id, Gebruiker: config.user, Document: null } $ctrl.item.files.add(moduleScope.convertGisDocumentToFile(gisDocument, x)); }); }); } }); $("#Soort") .autocomplete({ minLength: 0, autoFocus: true, source: function (request, response) { var term = request.term.toLowerCase(); var soorten = $ctrl.soorten.where(function (x) { return x.scientific.toLowerCase().startsWith(term) || x.title.toLowerCase().startsWith(term); }); response(soorten.select(function (x) { return { label: x.scientific + " - " + x.title, value: x.scientific, obj: x }; }).take(10)); }, select: function (e, arg) { $timeout(function () { if (arg.item) { $ctrl.item.soort = arg.item.value; moduleScope.soortImg = config.baseUrl + "/Handlers/SymbolHandler.aspx?img=Bomen/" + arg.item.obj.image; } else { moduleScope.soortImg = null; } }); }, change: function (e, arg) { $timeout(function () { if (arg.item) { moduleScope.soortImg = config.baseUrl + "/Handlers/SymbolHandler.aspx?img=Bomen/" + arg.item.obj.image; } else { moduleScope.soortImg = null; } }); } }) .focus(function () { $(this).autocomplete("search", $(this).val()); }); } }; }; BomenDirective.$inject = ["bomenConfig", "boomService", "geoHelper", "gisViewerManager", "gisVectorManager", "$translate", "$timeout"]; return BomenDirective; })("bomen"); var bomen = bomen || {}; bomen.BoomController = (function () { function BoomController(service, soortService) { EntityControllerBase.call(this, service); Object.defineProperties(this, { soorten: { writable: true, enumerable: true }, _soortService: { value: soortService } }); } BoomController.$inject = ["boomService", "soortService"]; BoomController.prototype = Object.create(EntityControllerBase.prototype, { constructor: { value: BoomController }, init: { value: function () { var vm = this; return EntityControllerBase.prototype.init.call(vm) .then(function (items) { console.log("BOOM", vm); return vm._soortService.list() .then(function (soorten) { vm.soorten = soorten; }) .then(function () { return items; }); }); }, enumerable: true } }); return BoomController; })("bomen"); var bomen = bomen || {}; bomen.OverlayContainer = (function (moduleName) { function OverlayContainer() { return { restrict: "EA", controller: bomen.BoomController, controllerAs: "ctrl", scope: { boomId: "=boomId" }, template: "
{{ ctrl.item.soort }}

{{ ctrl.item.description }}

", link: function ($scope, $el, $attr, $ctrl) { $ctrl.show(); } } } })("bomen"); var bomen = bomen || {}; bomen.BoomService = (function () { function BoomService(config, $http) { EntityServiceBase.call(this, { niscode: config.niscode, url: config.url }, $http); } BoomService.$inject = ["bomenConfig", "$http"]; BoomService.prototype = Object.create(EntityServiceBase.prototype, { constructor: { value: BoomService } }); return BoomService; })("bomen"); var bomen = bomen || {}; bomen.SoortService = (function () { function SoortService(config, $http) { EntityServiceBase.call(this, { niscode: config.niscode, url: config.url }, $http); Object.defineProperties(this, { _config: { value: config } }); } SoortService.$inject = ["bomenConfig", "$http"]; SoortService.prototype = Object.create(EntityServiceBase.prototype, { constructor: { value: SoortService }, list: { value: function () { return Promise.resolve([ { scientific: "Acer_rufinerve", title: "Grijze slangenbast esdoorn", image: "acer.png" }, { scientific: "Ailanthus_altissima", title: "Hemelboom", image: "ailanthus.png" }, { scientific: "Alnus_cordata", title: "Hartbladige_els", image: "alnus.png" }, { scientific: "Catalpa_bignonioides", title: "Trompetboom", image: "catalpa.png" }, { scientific: "Cornus_mas", title: "Gele kornoelje", image: "cornus.png" }, { scientific: "Ficus_carica", title: "Vijg", image: "ficus.png" }, { scientific: "Gleditsia_triacanthos", title: "Valse christusdoorn", image: "gleditsia.png" }, { scientific: "Gymnocladus_dioicus", title: "Doodsbeenderenboom", image: "gymnocladus.png" }, { scientific: "Laburnum_anagyroides", title: "Gouden regen", image: "laburnum.png" }, { scientific: "Quercus_robur", title: "Zomereik", image: "quercus.png" }, { scientific: "Salix_purpurea", title: "Bittere wilg", image: "salix.png" }, { scientific: "Ulmus_minor", title: "Gladde iep", image: "ulmus.png" } ]); }, enumerable: true } }); return SoortService; })("bomen"); var burgerloket = burgerloket || {}; burgerloket.BurgerloketDirective = (function (moduleName) { function BurgerloketDirective(config) { return { restrict: "EA", template: '
' }; } return BurgerloketDirective; })("burgerloket"); var crab = crab || {}; crab.CrabController = (function() { function CrabController(crabService) { var vm = this; vm.selected = {}; vm.input = {}; vm.listGemeenten = function(term) { return crabService.listGemeenten({ term: term }); }; vm.listStraten = function(term) { return crabService.listStraten({ gemeente: vm.selected.gemeente, term: term }); }; vm.listHuisnrs = function(term) { return crabService.listHuisnrs({ gemeente: vm.selected.gemeente, straat: vm.selected.straat, straatNaam: vm.input.straat, term: term }); }; vm.findGemeente = function(niscode) { if (vm.selected.gemeente) { return new Promise(function(resolve) { resolve(vm.selected.gemeente); }); } return crabService .findGemeente({ niscode: niscode }) .then(function(gemeente) { vm.selected.gemeente = gemeente; return gemeente; }); }; vm.findStraat = function() { if (vm.selected.straat && vm.selected.straat.Geometry && vm.selected.straat.Geometry.WKT) { return new Promise(function(resolve) { resolve(vm.selected.straat); }); } return crabService .findStraat({ gemeente: vm.selected.gemeente, straatNaam: vm.input.straat }) .then(function(straat) { vm.selected.straat = straat; return straat; }); }; vm.findHuisnr = function() { if (vm.selected.huisnr && vm.selected.huisnr.Geometry && vm.selected.huisnr.Geometry.WKT) { return new Promise(function(resolve) { resolve(vm.selected.huisnr); }); } return crabService .findHuisnr({ gemeente: vm.selected.gemeente, straat: vm.selected.straat, straatNaam: vm.input.straat, huisnrNr: vm.input.huisnr }) .then(function(huisnr) { vm.selected.huisnr = huisnr; return huisnr; }); }; vm.reset = function() { return new Promise(function(resolve) { vm.selected = { gemeente: null, straat: null, huisnr: null }; vm.input = { gemeente: null, straat: null, huisnr: null }; resolve(); }); }; } CrabController.$inject = ["crabService"]; return CrabController; })(); var crab = crab || {}; crab.CrabDirective = (function (moduleName) { function CrabDirective(config, commandBag, $translate, $timeout, gisViewerManager) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, scope: {}, controller: crab.CrabController, controllerAs: "crabCtrl", link: function ($scope, $el, $attr, $ctrl) { //console.log(moduleName.toUpperCase(), this, $.extend(true, {}, $scope)); var oldScope = $scope; while (!oldScope.modules && oldScope !== oldScope.$parent) { oldScope = oldScope.$parent; } $scope.loading = {}; var loading = function (type) { var countProperty = "_" + type; $timeout(function() { $scope.loading[type] = true; if (!$scope.loading[countProperty]) { $scope.loading[countProperty] = 0; } $scope.loading[countProperty]++; //console.log('loading', type, $scope.loading[countProperty]); }); return function () { $timeout(function() { $scope.loading[countProperty]--; $scope.loading[type] = $scope.loading[countProperty] > 0; //console.log('loading', type, $scope.loading[countProperty]); }); } } $scope.zoom = function () { var overlay = $el.spinnerOverlay(); return $ctrl.findHuisnr() //probeer eerst op huisnr te zoomen .then(function (huisnr) { if (huisnr && huisnr.Geometry && huisnr.Geometry.WKT) { var center = oldScope.gis.helpers.geoHelper.getCenter(huisnr.Geometry.WKT); return gisViewerManager.zoom({ center: center, scale: 500 }) .then(function() { return true; }); } else { return false; } }) //zoom op straat .then(function (success) { if (success) { return true; } return $ctrl.findStraat() .then(function (straat) { if (straat && straat.Geometry && straat.Geometry.WKT) { var bounds = oldScope.gis.helpers.geoHelper.getBounds(straat.Geometry.WKT); return gisViewerManager.zoomToExtent({ bounds: bounds, minScale: 500 }) .then(function () { return true; }); } else { return false; } }); }) //mislukt? .then(function (success) { if (!success) { var adresDisplay = $ctrl.input.gemeente || ''; if ($ctrl.input.straat) { adresDisplay += ', ' + $ctrl.input.straat; } if ($ctrl.input.huisnr) { adresDisplay += ' ' + $ctrl.input.huisnr; } console.error("CRAB-zoom failed", adresDisplay); } return success; }) .then(function (success) { overlay.remove(); return success; }) .catch(function(err) { overlay.remove(); G.handleError(err); }); }; $scope.reset = function () { return $ctrl.reset() .then(function () { return $ctrl.listGemeenten() .then(function(gemeenten) { //compatibility with aansluitingen oldScope.modules[moduleName].data.gemeenten = gemeenten; return gemeenten; }); }) .then(function () { if (parseInt(config.niscode)) { $ctrl.findGemeente(config.niscode) .then(function (gemeente) { if (gemeente) { $ctrl.selected.gemeente = gemeente; $timeout(function () { $ctrl.input.gemeente = gemeente.Naam; }); } }); } }); } oldScope.modules[moduleName] = { _initialized: false, data: { gemeenten: [] }, zoom: $scope.zoom, reset: $scope.reset, //compatibility with aansluitingen refreshGemeenten: function () { console.warn("CRAB.refreshGemeenten: obsolete"); }, //compatibility with aansluitingen clearStraten: function () { console.warn("CRAB.clearStraten: obsolete"); }, init: function () { oldScope.modules[moduleName]._initialized = true; function onGemeenteSelect(e, arg) { $timeout(function () { if (!arg.item) { $ctrl.selected.gemeente = null; } else { $ctrl.selected.gemeente = arg.item.obj; $ctrl.input.gemeente = arg.item.label; $el.find("#Adres").focus(); } $ctrl.selected.straat = null; $ctrl.selected.huisnr = null; $ctrl.input.straat = null; $ctrl.input.huisnr = null; //console.log("GEMEENTE_CHANGED", $ctrl); }); } function onStraatSelect(e, arg) { $timeout(function () { if (!arg.item) { $ctrl.selected.straat = null; } else { $ctrl.selected.straat = arg.item.obj; $ctrl.input.straat = arg.item.label; $el.find("#HuisNr").focus(); } $ctrl.selected.huisnr = null; $ctrl.input.huisnr = null; //console.log("STRAAT_CHANGED", $ctrl); }); } function onHuisNrSelect(e, arg) { $timeout(function () { if (!arg.item) { $ctrl.selected.huisnr = null; } else { $ctrl.selected.huisnr = arg.item.obj; $ctrl.input.huisnr = arg.item.label; } //console.log("HUISNR_CHANGED", $ctrl); }); } $el.find("#Gemeente") .autocomplete({ minLength: 1, autoFocus: true, source: function (request, response) { var cancel = loading('gemeenten'); $ctrl.listGemeenten(request.term) .then(function (gemeenten) { response(gemeenten.select(function (x) { return { label: x.Naam, obj: x }; }).take(10)); }) .then(function (result) { cancel(); return result; }) .catch(function (err) { cancel(); throw err; }); }, select: onGemeenteSelect, change: onGemeenteSelect }); $el.find("#Adres") .autocomplete({ minLength: 1, autoFocus: true, source: function (request, response) { var cancel = loading('straten'); $ctrl.listStraten(request.term) .then(function (straten) { response(straten.select(function (x) { return { label: x.Naam, obj: x }; }).take(10)); }) .then(function (result) { cancel(); return result; }) .catch(function (err) { cancel(); throw err; }); }, select: onStraatSelect, change: onStraatSelect }); $el.find("#HuisNr") .autocomplete({ minLength: 0, autoFocus: false, source: function (request, response) { var cancel = loading('huisnrs'); $ctrl.listHuisnrs(request.term) .then(function (huisnrs) { response(huisnrs.select(function (x) { return { label: x.Nummer, obj: x }; }).take(10)); }) .then(function (result) { cancel(); return result; }) .catch(function (err) { cancel(); throw err; }); }, select: onHuisNrSelect, change: onHuisNrSelect }) .on("focus", function () { if (!$(this).val()) { $(this).autocomplete("search", ""); } }); $scope.reset(); } }; //command commandBag.on("execute", "crab.SearchAddress", function () { oldScope.panels.show($el, "right"); if (!oldScope.modules[moduleName]._initialized) { oldScope.modules[moduleName].init(); } }); } }; }; CrabDirective.$inject = ["config", "commandBag", "$translate", "$timeout", "gisViewerManager"]; return CrabDirective; })("crab"); var crab = crab || {}; crab.CrabService = (function () { function CrabService(config, $http, $translate) { var sv = this; var gemeenten = null; sv.listGemeenten = function (o) { var term = o ? o.term : null; var promise; if (gemeenten) { promise = new Promise(function (resolve) { resolve(gemeenten); }); } else { promise = $http.get("Content/data/gemeenten.min.json") .then(function (response) { return response.data; }); } return promise.then(function (gemeenten) { if (term) term = term.cleanSpecialCharacters(); return gemeenten .where(function (x) { return !term || (x["nl"].cleanSpecialCharacters()).startsWith(term, true) || (x["fr"].cleanSpecialCharacters()).startsWith(term, true); }) .select(function (x) { return { Niscode: x.nis, Postcode: x.zip, Naam: x[$translate.use()], TaalCode: x.lang } }) .orderBy(function (x) { return x.Naam; }); }); }; sv.listStraten = function (o) { var gemeente = o.gemeente, term = o.term; if (!gemeente) { throw new Error("Kan enkel straten tonen wanneer de gemeente gekend is"); } var so = { Term: term, GemeenteSearchObject: { //Naam: gemeente.Naam, Postcode: gemeente.Postcode } }; return $http.post(config.baseUrl + "/" + config.application + "/Handlers/CRAB/Straat?action=list", { so: so }) .then(function (response) { return response.data; }) .then(function (straten) { return straten .orderBy(function (x) { return x.Naam || x.Naam2; }); }); }; sv.listHuisnrs = function (o) { var gemeente = o.gemeente, straatNaam = o.straatNaam, straat = o.straat, term = o.term; if (!(gemeente && (straatNaam || straat))) { throw new Error("Kan enkel huisnummers tonen wanneer de gemeente en de straat gekend zijn"); } var so = { Term: term, StraatSearchObject: { Naam: straatNaam, GemeenteSearchObject: { Postcode: gemeente.Postcode } } }; if (straat) { so.StraatId = straat.Id; } return $http.post(config.baseUrl + "/" + config.application + "/Handlers/CRAB/Huisnummer?action=list", { so: so }) .then(function (response) { return response.data; }) .then(function (huisnrs) { return huisnrs.naturalSort(function (x) { return x.Nummer; }); }); }; sv.findGemeente = function (o) { var naam = o.naam; var niscode = o.niscode; if (!naam) { return Promise.resolve(null); } return sv.listGemeenten() .then(function (gemeenten) { var gemeente = gemeenten.first(function (x) { return (!niscode || x.Niscode === niscode.toString()) && (!naam || x.Naam.toLowerCase() === naam.toLowerCase()); }); return gemeente; }); }; sv.findStraat = function (o) { var gemeente = o.gemeente, straatNaam = o.straatNaam, straatId = o.straatId; if (!gemeente || !straatNaam) { return Promise.resolve(null); } var so = { Id: straatId, Naam: straatNaam, GemeenteSearchObject: { Postcode: gemeente.Postcode } }; return $http.post(config.baseUrl + "/" + config.application + "/Handlers/CRAB/Straat?action=details", { so: so }) .then(function (response) { return response.data; }); }; sv.findHuisnr = function (o) { var gemeente = o.gemeente, straat = o.straat, straatNaam = straat ? straat.Naam : o.straatNaam, straatId = straat ? straat.Id : o.straatId, huisnrNr = o.huisnrNr, huisnrId = o.huisnrId; if (!gemeente || !straatNaam || !huisnrNr) { return Promise.resolve(null); } var so = { Id: huisnrId, Nummer: huisnrNr, StraatId: straatId, StraatSearchObject: { Naam: straatNaam, GemeenteSearchObject: { Postcode: gemeente.Postcode } } }; return $http.post(config.baseUrl + "/" + config.application + "/Handlers/CRAB/Huisnummer?action=details", { so: so }) .then(function (response) { return response.data; }); }; } CrabService.$inject = ["config", "$http", "$translate"]; return CrabService; })(); var dwf = dwf || {}; dwf.Bootstrapper = (function (moduleName) { "use strict"; function Bootstrapper(config, dwfManager, $timeout) { var bs = this; this.initCommands = function (commandBag, $translate) { commandBag.add([ { name: moduleName + ".Open", content: '', title: function () { return $translate("global.Dwf"); } } ]); return Promise.resolve(bs); }; this.loadProject = function(project) { return Promise.resolve() .then(function() { return dwfManager.setProject(project); }) .then(function(result) { dwfManager.load(); //parallel return result; }); }; this.initProjects = function (projectManager, dwfGisManager) { projectManager .on("change-active-item", function (e, arg) { //console.log("NB.CHANGE_ACTIVE_PROJECT", { evt: e, arg: arg }); var visibleItems = dwfManager.items.where(function (x) { return x.IsVisible === true; }); return bs.loadProject(arg.activated) .then(function (dwfLayers) { if (visibleItems.length) { return dwfGisManager.setVisibility(visibleItems, false) .then(function () { return dwfLayers; }); } return dwfLayers; }) .then(function (dwfLayers) { if (arg.activated) { var firstLayer = dwfLayers.where(function (x) { return x.Type === 'L'; }).first(); if (firstLayer) { return Promise.resolve() .then(function () { if (config.activateFirstOnProjectChange) { return dwfManager.toggle(firstLayer) .then(function () { return dwfGisManager.refreshMap(); }); } }) .then(function () { if (config.zoomToFirstOnProjectChange) { return new Promise(function (resolve) { setTimeout(function () { dwfManager.focus([firstLayer]) .then(resolve); }, 500); // NOTE 2023-07-35 #8439 // We gebruiken hier een timeout as last resort // Ergens onderliggend (refreshmap of toggle?) wordt de resolve te snel uitgevoerd. // Wie zal het weten waar exact het probleem zich voordoet, maar het probleem is nu dat er een race condition is // Lower level code zit jammer genoeg vol met delays/timeouts, vermoedelijk zal het daar mee te maken hebben }); } }) } } }) ; }); return Promise.resolve(bs); }; this.initDwfGis = function (dwfGisManager, projectManager) { var dwfGroup; dwfManager // zoom to dwf(s) .on("focus", function (e, arg) { return Promise.resolve() .then(function () { return dwfGisManager.zoom({ items: arg.items }, arg.minScale); }); }) .on("change-visibility", function (e, arg) { return dwfGisManager.setVisibility(arg.item, arg.visible); }) .on("change-items", function (e, arg) { return Promise.resolve() .then(function () { if (arg.removed && arg.removed.length) { return dwfGisManager.removeLayers(arg.removed); } return false; }) .then(function () { if (arg.added && arg.added.length) { return Promise.resolve() .then(function () { if (dwfGroup == null) { return dwfManager.getGroup(); } return dwfGroup; }) .then(function (group) { return [group].concat(arg.added); }) .then(function (items) { return dwfGisManager.addLayers(items); }); } return false; }) .then($timeout); }); projectManager .on("request-extents", function (e, arg) { return Promise.resolve() .then(function () { return dwfGisManager.getExtent({ items: dwfManager.items }); }) .then(function (extent) { arg.addExtent(extent); return extent; }); }); return Promise.resolve(bs); }; this.initElements = function (commandBag) { var pm = new PanelManager($(".content-container")); var moduleContainer = $("#DwfContainer"); commandBag .on("execute", moduleName + ".Open", function () { pm.show(moduleContainer, "right"); }) .on("execute", moduleName + ".Close", function () { pm.hide(moduleContainer, "right"); }); //pm.container.on("closed", function (e, arg) { // if (arg.element.get(0) === moduleContainer.get(0)) { // } //}); return Promise.resolve(bs); }; this.initCss = function () { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); return Promise.resolve(bs); }; } return Bootstrapper; })("dwf"); var dwf = dwf || {}; dwf.DwfController = (function () { "use strict"; function dwfController(config, manager, fileHelper, $timeout) { var ctrl = this; common.EntityController.call(ctrl, manager, $timeout); Object.defineProperties(ctrl, { _fileHelper: { value: fileHelper }, projectsEnabled: { value: config.enableProjects !== false } }); //console.log("NOTITIE_CTRL", { ctrl: ctrl }); } dwfController.prototype = Object.create(common.EntityController.prototype, { constructor: { value: dwfController }, _super: { value: common.EntityController.prototype}, project: { get: function () { return this._entityManager.project; }, enumerable: true }, canEdit: { get: function () { return this._entityManager.canEdit; }, enumerable: true }, display: { get: function () { return this._entityManager.display; }, set: function (value) { this._entityManager.display = value; }, enumerable: true }, toggle: { value: function (item) { return this._entityManager.toggle(item); } }, // init init: { value: function () { return this._super.list.call(this); } }, resetFilter: { value: function () { return this._entityManager.resetFilter(); } }, addFiles: { value: function () { var ctrl = this; return ctrl._fileHelper.browse({ multiple: true, accept: ".dwf" }) .then(function (files) { var state = ctrl.stateManager.addState("loading"); return ctrl._entityManager.addFiles(files) .then(state.completed) .catch(function(err) { state.error(err); throw err; }); }); //.then(function () { // window.history.go(0); //}); } }, focus: { value: function () { var ctrl = this; var state = ctrl.stateManager.addState("loading"); return this._super.focus.apply(ctrl, arguments) .then(state.completed) .catch(function (err) { state.error(err); throw err; });; } }, // CRUD save: { value: function (item) { return this._entityManager.save(item); } }, remove: { value: function (item) { var ctrl = this; var state = ctrl.stateManager.addState("loading"); return this._entityManager.remove(item) .then(state.completed) .catch(function (err) { state.error(err); throw err; }); } } }); return dwfController; })("dwf"); var dwf = dwf || {}; dwf.DwfDirective = (function (moduleName) { "use strict"; function DwfDirective(config) { return { restrict: "EA", template: '
' } } return DwfDirective; })("dwf"); var dwf = dwf || {}; dwf.DwfGisManager = (function () { "use strict"; function DwfGisManager(gisViewer, layerTree) { this._viewer = gisViewer; this._layerTree = layerTree; } EventHandler.injectInto(DwfGisManager.prototype); Object.defineProperties(DwfGisManager.prototype, { zoom: { value: function (o) { var me = this; var item = _.array(o.items).first(); return me._viewer.setLayerVisibility({ layer: item, visible: true }) .then(function () { return me._viewer.getLayerExtent({ layerName: item.Code }); }) .then(function (extent) { return me._viewer.zoomToExtent({ extent: extent }); }); } }, getExtent: { value: function (o) { var me = this; var items = _.array(o.items); return Promise.all(items .select(function (item) { return me._viewer.getLayerExtent({ layerName: item.Code }); })) .then(function (extents) { return [ extents.min(function (x) { return x[0] }), extents.min(function (x) { return x[1] }), extents.max(function (x) { return x[2] }), extents.max(function (x) { return x[3] }) ]; }); } }, setVisibility: { value: function (items, visible) { var me = this; return me._viewer.setLayerVisibility({ layers: _.array(items), visible: visible }); } }, addLayers: { value: function (items) { var me = this; var layersToAdd = items.where(function (x) { return me._layerTree.tree.all(function (l) { return l.Code !== x.Code; }); }); return me._viewer.addLayers({ layers: layersToAdd }); } }, removeLayers: { value: function (items) { var me = this; return me._viewer.removeLayers({ layers: items }); } }, refreshMap: { value: function () { var me = this; return me._viewer.refreshMap(); } } }); return DwfGisManager; })("dwf"); var dwf = dwf || {}; dwf.DwfManager = (function () { "use strict"; function DwfManager(service) { common.EntityManager.call(this, service); Object.defineProperties(this, { enabled: { value: true, writable: true }, _project: { writable: true }, _display: { value: "list", writable: true } }); } DwfManager.prototype = Object.create(common.EntityManager.prototype, { constructor: { value: DwfManager }, project: { get: function () { return this._project; }, enumerable: true }, display: { get: function () { return this._display; }, set: function (value) { this.setDisplay(value); } }, selectedItems: { get: function () { return this.items.where(function (x) { return x.IsVisible; }); } }, // init init: { value: function (o) { o = o || {}; //console.log("DWF.INIT", { o: o, mgr: this }); if ("canEdit" in o) { this.canEdit = !!o.canEdit; } return common.EntityManager.prototype.init.call(this, o); } }, getNewItem: { value: function () { var mgr = this; return common.EntityManager.prototype.getNewItem.call(this) .then(function (item) { Object.defineProperty(item, "projectId", { get: function () { return mgr.project != null ? mgr.project.id : null; }, enumerable: true }); return item; }); } }, // display setDisplay: { value: function (display) { var oldDisplay = this.display; console.log("DWF.SET_ITEM", { display: display, oldDisplay: oldDisplay, mgr: this }); var arg = { display: display, oldDisplay: oldDisplay }; var promise = Promise.resolve(); if (display !== oldDisplay) { this._display = display; promise = this.trigger("change-display", arg); } return promise .then(function () { return arg; }); } }, load: { value: function () { var mgr = this; var onReady; return mgr.trigger("loading", { onReady: function (callback) { onReady = callback; } }) .then(function () { return mgr.list(); }) .then(function () { mgr._itemsCount = mgr.items.length; if (typeof (onReady) === "function") { return onReady({ items: mgr.items, count: mgr.itemsCount }); } return true; }) .then(function () { return mgr.items; }); } }, toggle: { value: function (item) { var visible = !item.IsVisible; // set visibility => improve performance item.IsVisible = visible; return this.trigger("change-visibility", { item: item, visible: visible }); } }, // CRUD addFiles: { value: function (files) { var mgr = this; console.log("DWF.ADD_FILES", { files: files, project: mgr.project }); return mgr._service.saveFiles(files, (mgr.project || {}).id) .then(function (addedItems) { return mgr.load() .then(function (response) { return mgr.trigger("add-items", { items: addedItems }) .then(function () { return response; }); }); }); } }, remove: { value: function (item) { var mgr = this; item.removed = true; console.log("DWF.REMOVE", { item: item, project: mgr.project }); return mgr._service.remove(item, (mgr.project || {}).id) .then(function () { return mgr.load() .then(function (response) { return mgr.trigger("remove-item", { item: item }) .then(function () { return response; }); }); }); } }, setProject: { value: function (project) { //var mgr = this; //console.log("DWF.SET_PROJECT", { project: project, mgr: this }); this._project = project; return this._service.setProject(project ? project.id : null); } }, getGroup: { value: function () { return this._service.getGroup(); } }, // compare _equalsItem: { value: function (item1, item2) { return item1 === item2 || (item1 != null && item2 != null && item1.Code === item2.Code); } } }); return DwfManager; })("dwf"); var dwf = dwf || {}; dwf.DwfService = (function () { var _promise = Promise.resolve(); function DwfService(config, fileHelper, $http) { EntityServiceBase.call(this, { niscode: config.niscode, url: config.url }, $http); var sv = this; Object.defineProperties(sv, { _clientSession: { value: config.clientSession }, _setProjectUrl: { value: config.setProjectUrl }, _saveUrl: { value: config.saveUrl }, _deleteUrl: { value: config.deleteUrl }, _fileHelper: { value: fileHelper } }); } DwfService.prototype = Object.create(EntityServiceBase.prototype, { constructor: { value: DwfService }, _groupCode: { value: "DWF" }, _layers: { value: [], writable: true }, _group: { value: null, writable: true }, getGroup: { value: function () { return Promise.resolve(this._group); } }, list: { value: function (/*o*/) { var sv = this; return Promise.resolve(sv._layers.where(function (x) { return x.ParentCode === sv._groupCode; }) .orderBy(function (x) { return x.Title || x.Code; })); } }, saveFiles: { //{ items: [File] } value: function (files, projectId) { var sv = this; var url = sv._saveUrl + "/?clientSession=" + encodeURIComponent(sv._clientSession); if (projectId) { url += "&projectId=" + projectId; } _promise = _promise .then(function () { return sv._fileHelper.send(url, files); }) .then(function (layers) { var layersToAdd = layers.where(function (x) { return sv._layers.all(function (l) { return x.Code !== l.Code; }) }); sv._layers.addRange(layersToAdd); return layers; }); return _promise; } }, remove: { //{ items: [Layer] } value: function (item, projectId) { var sv = this; var url = sv._deleteUrl + "/?name=" + item.Code; if (projectId) { url += "&projectId=" + projectId; } _promise = _promise .then(function () { return sv._http.post(url); }) .then(function () { sv._layers.remove(function (x) { return x.Code === item.Code }); return item; }); return _promise; } }, setProject: { value: function (projectId) { var sv = this; var url = sv._setProjectUrl + "/?projectId=" + (projectId || 0); _promise = _promise .then(function () { return sv._http.post(url); }) .then(function (response) { var items = response.data; sv._group = items.first(function (x) { return x.Type === "G"; }); sv._layers = items.where(function (x) { return x.Type === "L" }); return items; }); return _promise; } } }); return DwfService; })("dwf"); var errors = errors || {}; errors.ConnectionToolbarDirective = (function (moduleName) { "use strict"; function ConnectionToolbarDirective(config, $timeout, errorService) { return { restrict: "EA", scope: { }, //controller: errors.ErrorToolbarController, //controllerAs: "ctrl", templateUrl: function () { return config.baseUrl + "/content/modules/errors/connection/connection-toolbar.html?v=" + config.version; }, link: function ($scope, $el) { $el.addClass('connection-toolbar'); var waitForRetry = function () { $timeout(function () { $scope.data.waitSeconds = 5; $scope.data.interval = setInterval(function () { $timeout(function () { $scope.data.waitSeconds--; if (!$scope.data.waitSeconds) { $scope.ping(); } }); }, 1000); }); }; Object.defineProperties($scope, { close: { value: function () { $el.hide(); } }, data: { value: { interval: null, waitSeconds: null, pinging: false } }, ping: { value: function () { console.log("CN.PING", { scope: $scope, online: navigator.onLine }); $scope.data.pinging = true; if ($scope.data.interval) { clearInterval($scope.data.interval); $scope.data.interval = null; } $scope.data.waitSeconds = null; setTimeout(function () { G.get({ controller: 'Index', action: 'Ping', success: function () { $scope.close(); }, error: function () { $el.show(); waitForRetry(); }, always: function () { $scope.data.pinging = false; } }); }, 1000); } } }); errorService.on('connection-lost', function () { if ("onLine" in navigator && navigator.onLine === true) { setTimeout(function () { $scope.ping(); }, 3000); } }); } } } ConnectionToolbarDirective.$inject = ["config", "$timeout", "errorService"]; return ConnectionToolbarDirective; })("errors"); var errors = errors || {}; errors.ErrorService = (function (moduleName) { "use strict"; function ErrorService(config, $rootScope, $translate, $compile, panelHelper) { var sv = this; G._container.on('error', function (e, arg) { return sv.handleError(arg); }); Object.defineProperties(sv, { _container: { value: $("body") }, handleError: { value: function (o) { return Promise.resolve({ type: 'error' }) .then(function (error) { if (typeof (o) === "string") { error.message = o; error.translate = o; return error; } if (o.angular) { console.error('ANGULAR', o); error.message = o.exception; //var cause = o.cause; return error; } if (o.translate) { error.translate = o.translate; error.data = o.data; return error; } var errorObj = (o.statusText !== undefined ? o : o.data && o.data.error ? o.data.error : o.error) || o; if (typeof (errorObj) === "string") { error.message = errorObj; error.translate = errorObj; return error; } var data = o.responseJSON || o.data; if (data) { if (data.exceptionType) { error.translate = 'errors.' + data.exceptionType; } else { error.translate = 'errors.' + errorObj.status; } error.message = data.message ?? errorObj.statusText; error.data = data.exceptionData; switch (errorObj.status) { case 400: error.type = 'validate'; return error; case 401: error.okcallback = function () { window.location.reload(); }; return error; case 500: return error; } console.error('JSON', o); error.message = errorObj.status + ': ' + (data.Message ? data.Message : errorObj.statusText); if (data.MessageDetail) { error.message += '
' + data.MessageDetail; } return error; } if (errorObj.statusText) { if (errorObj.statusText === "error" && errorObj.status === 0) { console.error('STATUS', o); return sv.trigger('connection-lost', errorObj) .then(function () { return null; }); } } var e = o.data; if (e) { if (e.error) { if (!e.error.stack) { result.message = e.error.toString(); } if (e.error.fileName) { result.message += " fileName " + e.error.fileName + ": " + (e.error.lineNumber || ""); } if (e.error.stack) { result.message += '
' + e.error.stack.replace(/\\n/g, "
").replace(/ at /g, "
at "); } } else if (e.message) { result.message = e.message; } while (e.innerException) { var innerException = e.innerException; if (!innerException.stack) { result.message += '
' + innerException.toString(); } if (innerException.fileName) { result.message += " fileName " + innerException.fileName + ": " + (innerException.lineNumber || ""); } if (innerException.stack) { result.message += '
' + innerException.stack.replace(/\\n/g, "
").replace(/ at /g, "
at "); } e = innerException; } return result; } console.error('ERROR', o); if (errorObj.statusText && (errorObj.statusText !== "error" || errorObj.status !== 0)) { error.message = errorObj.status + ': ' + errorObj.statusText; } else if (errorObj.message) { error.message = errorObj.message; } else { error.message = o; } return error; }) .then(function (error) { if (error && error.translate) { try { return $translate(error.translate) .catch(function () { return error.message || error.translate; }) .then(function (message) { error.message = __stringextensions.inject(message, error.data); return error; }); } catch (e) { } } return error; }) .then(function (error) { if (error) { return sv._container.messageOverlay(error.message, { type: error.type, okcallback: error.okcallback }); } return error; }); } } }); } ErrorService.$inject = ["config", "$rootScope", "$translate", "$compile", "panelHelper"]; EventHandler.injectInto(ErrorService.prototype); return ErrorService; })("errors"); var evacuatie = evacuatie || {}; evacuatie.BackupManager = (function () { function BackupManager() { Object.defineProperties(this, { items: { value: [], enumerable: true }, _restoreIndex: { value: 0, writable: true }, _busy: { value: false, writable: true }, _canUndo: { value: false, writable: true }, _canRedo: { value: false, writable: true }, _refreshCanUndoRedo: { value: function() { this._canUndo = this.items.length > 0 && this._restoreIndex > 0 && !this._busy; this._canRedo = this.items.length > 0 && this._restoreIndex < this.items.length - 1 && !this._busy; } }, setBusy: { value: function () { var me = this; if (me._busy) { return Promise.reject("Action in progress"); } me._busy = true; me._refreshCanUndoRedo(); return Promise.resolve(function() { me._busy = !me._busy; me._refreshCanUndoRedo(); }); } } }); } EventHandler.injectInto(BackupManager.prototype); Object.defineProperties(BackupManager.prototype, { canUndo: { get: function () { return this._canUndo; }, enumerable: true }, canRedo: { get: function () { return this._canRedo; }, enumerable: true }, backup: { value: function (item) { var me = this; return me.setBusy() .then(function(cancel) { var backup = JSON.stringify(item); me.items.splice(me._restoreIndex + 1); if (me.items.last() !== backup) { me.items.push(backup); me._restoreIndex = me.items.length - 1; } var arg = { index: me._restoreIndex, backup: item }; return me.trigger("backup", arg) .then(function () { return arg; }) .then(function (result) { cancel(); return result; }) .catch(function (error) { cancel(); throw error; }); }); } }, restore: { value: function (index) { var me = this; return me.setBusy() .then(function (cancel) { me._restoreIndex = index; var arg = { index: index, backup: JSON.parse(me.items[index]) }; return me.trigger("restore", arg) .then(function () { return arg; }) .then(function (result) { cancel(); return result; }) .catch(function (error) { cancel(); throw error; }); }); } }, undo: { value: function () { var me = this; return me.restore(me._restoreIndex - 1); } }, redo: { value: function () { var me = this; return me.restore(me._restoreIndex + 1); } }, clear: { value: function () { var me = this; return me.setBusy() .then(function (cancel) { me.items.clear(); me._restoreIndex = 0; var arg = { index: me._restoreIndex }; return me.trigger("clear", arg) .then(function () { return arg; }) .then(function (result) { cancel(); return result; }) .catch(function (error) { cancel(); throw error; }); }); } } }); return BackupManager; })(); var evacuatie = evacuatie || {}; evacuatie.CategoryService = (function () { "use strict"; function CategoryService(config, $http) { var sv = this; EntityServiceBase.call(sv, { niscode: config.niscode, url: config.url }, $http); } CategoryService.prototype = Object.create(EntityServiceBase.prototype, { constructor: { value: CategoryService }, _processItem: { value: function (item) { if (!("titleNL" in item)) { item.titleNL = item.title; } if (!("titleFR" in item)) { item.titleFR = item.titleFR || item.category.title; } return item; } } }); return CategoryService; })(); var evacuatie = evacuatie || {}; evacuatie.Bootstrapper = (function (moduleName) { "use strict"; function Bootstrapper(config, evacuatieConfig, categoryService, projectManager, infoManager, $timeout, $scope, $http) { var bs = this; var failedChangeProjectMessage; var evacuatieContainer; //console.log("ROOTSCOPE", { scope: $scope, timeout: $timeout, config: config }); this.initProjectData = function (indexService) { // project events projectManager // active project changed .on("change-active-item", function (e, arg) { if (arg.hasChanged) { //console.debug("SB.PROJECT", { project: arg.activated }); indexService.saveUserLastProjectId((arg.activated || {}).id); } }); return categoryService .list() // init project-manager .then(function (categories) { return projectManager .init({ canEdit: config.canEdit, categories: categories, autoLoad: true }); }) .then(function () { return bs; }); }; this.initProjectGis = function (projectGisManager, snappingManager, gisViewer) { projectManager // loaded items changed .on("change-loaded-items", function (e, arg) { return Promise.enqueue(arg.removed.select(function (x) { return function () { return projectGisManager.removeItemFromMap(x); }; })) .then(function () { //console.log("SB.ADD_PROJECT_LAYER", { evt: e, arg: arg }); return Promise.enqueue(arg.added.select(function (x) { return function () { return projectGisManager.addItemToMap(x); }; })) .then(function () { if (projectManager.activeItem) { return projectGisManager.getLayer(projectManager.activeItem) .then(function (layer) { if (layer) { return snappingManager.list() .then(function () { //console.debug("SB.SNAPPING_MANAGER", { snappingManager: snappingManager, layer: layer }); return snappingManager.setSelected(layer); }); } return false; }); } return false; }) .then(function (result) { return result; }); }); }) // zoom to project(s) .on("request-extents", function (e, arg) { //console.debug("SBP.REQUEST_EXTENTS", { arg: arg }); return projectGisManager.getExtent(arg.items) .then(function (extent) { arg.addExtent(extent); return extent; }); }) .on("focus", function (e, arg) { //console.debug("SBP.FOCUS", { arg: arg }); return gisViewer.zoomToExtent({ bounds: arg.bounds }); }); return Promise.resolve(bs); }; this.initFeatureData = function (featureManager, featureHelper, projectSecurityManager) { //console.log("SB.FEATURE_DATA", { config: config, projMgr: projectManager, featMgr: featureManager }); projectManager .on("change-active-item", function (e, arg) { //console.log("ACTIVE_PROJECT", { projectMgr: projectManager, featureMgr: featureManager, evt: e, arg: arg }); if (!arg.hasChanged) { return; } var project = arg.activated; var features = project ? project.geoJson.features : []; var canEditModule = projectSecurityManager.canEditModule(project); // don't use return -> messes up order of events (project-change > features-init) featureManager .init({ items: features, modes: canEditModule && project && !project.isLocked ? ["gis", "html", "style"] : [] }); }); // select feature after creation featureManager .on("change-selected-items", function (e, arg) { if (arg.selectedItems.length === 1) { return $timeout(function () { if (arg.selectedItems.length === 1) {// check again after timeout var itemId = featureHelper.getProperty(arg.selectedItems.first(), "id"); //console.log("SB.SCROLLING_TO", { evt: e, arg: arg, itemId: itemId, mgr: featureManager }); $("#EvacuatieContainer").find(".feature-list-item[data-id=" + itemId + "]").scrollTo(); } }, 250); } return $timeout(); }) .on("change-interface-modes", function ( /*e, arg*/) { //console.log("SB.FM_INTERFACE_MODES", { evt: e, arg: arg, mgr: featureManager }); }) .on("save-items", function (e, arg) { //console.log("SB.SAVE_ITEM_DATA", { evt: e, arg: arg, mgr: featureManager }); // recalculate resized img var ih = new ImageHelper(); return Promise.all( arg.items .where(function (item) { return featureHelper.isImage(item); }) .select(function (item) { var imgStyle = featureHelper.getStyle(item).image; return Promise.resolve(imgStyle._imgEl) .then(function (img) { if (!img) { return ih.getImageFromUrl(imgStyle.iconUrl) .then(function(iconImage) { imgStyle._imgEl = iconImage; return iconImage; }); } return img; }) .then(function(img) { var transformedSize = featureHelper.calcTransformedIconSize(item); if (transformedSize) { return ih.resizeFixed(img, transformedSize[0], transformedSize[1]) .then(function (resizedBlob) { imgStyle.transformedIconUrl = ih.createUrl(resizedBlob); return img; }); } imgStyle.transformedIconUrl = imgStyle.iconUrl; return img; }) .then(function (img) { if (item.properties && item.properties.resizeByScale) { imgStyle.resizedUrl = imgStyle.transformedIconUrl; } else if (img && (img.width !== imgStyle.width || img.height !== imgStyle.height)) { //console.debug("DISTORTED", { imgStyle: imgStyle, img: img }); var width = imgStyle.width > 1 ? imgStyle.width : 1; var height = imgStyle.height > 1 ? imgStyle.height : 1; return ih.resizeFixed(img, width, height) .then(function (resizedBlob) { imgStyle.resizedUrl = ih.createUrl(resizedBlob); }); } return false; }); })) .then($timeout); }) .on("focussing", function (e, arg) { //console.log("SB.FM_FOCUSSING", { evt: e, arg: arg }); arg.onReady(function (/*o*/) { //console.log("SB.FM_FOCUSED", o); }); }); return Promise.resolve(bs); }; this.initFeatureStyle = function (featureStyleManager, featureManager, featureHelper) { //return Promise.resolve(bs); featureManager // loaded changed .on("change-loaded-items", function (e, arg) { //console.log("SB.CHANGE_LOADED", { evt: e, arg: arg, featureStyleManager: featureStyleManager }); return featureStyleManager .init({ items: arg.items }) .then(function () { return $timeout(); }); }) .on("save-items", function (e, arg) { var hasModifiedLoadedItems = arg.items.innerJoin(featureManager.loadedItems).length; // update style features if (hasModifiedLoadedItems) { featureStyleManager .init({ items: featureManager.loadedItems }); } }); featureStyleManager .on("change-style", function (e, arg) { //console.debug("SB.CHANGE_STYLE", { arg: arg }); if (["height", "width"].contains(arg.prop)) { if (!parseFloat(arg.style[arg.prop])) { return false; } } featureHelper.updateItems(arg.items, arg.style, arg.scale, arg.upp, arg.keepRatio); return featureManager.save(arg.items); }); return Promise.resolve(bs); }; this.initFeatureGis = function (featureGisManager, featureManager, projectGisManager, snappingManager, gisViewer, featureHelper) { var modeName = "gis"; var prevSnappable = []; var setSnappableFeatures = function () { return Promise.resolve() .then(function () { if (prevSnappable.length > 0) { return gisViewer.removeSnappable(prevSnappable); } return false; }) .then(function () { var canSnap = config.canEdit && featureManager.enabled; if (canSnap && featureGisManager.layer != null) { return Promise.resolve() .then(function () { if (snappingManager.selected) { return snappingManager.selected; } //return projectGisManager.getLayer(projectManager.activeItem); return null; }) .then(function (layer) { if (layer) { return snappingManager.list() .then(function () { return snappingManager.setSelected(layer); }); } return false; }); //var snappableFeatures = featureManager.items // .where(function (feature) { // return featureHelper.getProperty(feature, "snappable"); // }); //prevSnappable = snappableFeatures; //gisViewer.addSnappable(snappableFeatures); } return false; }); } var setSelectedGisItems = function (selectedItems) { return featureGisManager.setSelectedItems(selectedItems) .then(function () { var hasValidSelectedItems = selectedItems.any(function (x) { return featureHelper.isSimplePoint(x) || featureHelper.isLineString(x) || featureHelper.isPolygon(x); }); var canModifyFeatures = config.canEdit && featureManager.enabled && hasValidSelectedItems && featureManager.hasMode(modeName); var canTransformFeatures = config.canEdit && featureManager.enabled && hasValidSelectedItems && featureManager.hasMode(modeName) && !selectedItems.all(function (x) { return featureHelper.isSimplePoint(x); }); featureGisManager.setEditMode(canModifyFeatures); featureGisManager.setTransformMode(canTransformFeatures); return setSnappableFeatures(); }); }; // map events gisViewer .on("feature-change", function (e, arg) { //console.log("SB.FEATURE_CHANGE", { evt: e, arg: arg }); //if ((arg.layers || []).contains(featureGisManager.layer)) { // featureManager.save(arg.features); //} if (featureGisManager.layer.Code) { var features = arg.changed[featureGisManager.layer.Code] || []; if (features.length > 0) { featureManager.save(features); } } }); // project event projectManager .on("change-active-item", function (e, arg) { if (!arg.hasChanged) { return false; } var t0 = performance.now(); var project = arg.activated; var features = project ? project.geoJson.features : []; return projectGisManager.getLayer(projectManager.activeItem) .then(function (layer) { return featureGisManager .init({ layer: layer, items: features }) .then(function () { return setSnappableFeatures(); }); }) .then(function (result) { var t1 = performance.now(); //console.log("PERFORMANCE", Math.round(t1 - t0), "ProjectManager[change-active-item].Evacuatie[FeatureGisManager]"); return result; }); }); // feature events featureManager .on("change-enabled", function () { return setSelectedGisItems(featureManager.selectedItems); }) .on("change-interface-modes", function (e, arg) { if (arg.added.contains(modeName)) { return featureGisManager.enable(true); } else if (arg.removed.contains(modeName)) { return featureGisManager.enable(false); } return null; }) // init //.on("init", function () { // featureGisManager.refreshLayer(); //}) // selection changed .on("change-selected-items", function (e, arg) { //console.log("SB.FM_SELECTION", { evt: e, arg: arg, mgr: featureGisManager }); return setSelectedGisItems(arg.selectedItems); }) // zoom to feature(s) .on("focus", function (e, arg) { return featureGisManager.zoom(arg.items, arg.minScale); }) // item moved in list .on("change-item-index", function ( /*e, arg*/) { featureGisManager.update(featureManager.items); }) .on("save-items", function (e, arg) { //console.log("SB.SAVE_ITEM_GIS", { evt: e, arg: arg, features: featureManager.items, mgr: featureGisManager }); return Promise .all([ featureGisManager.add(arg.added), featureGisManager.update(arg.modified) ]) .then(function () { return setSnappableFeatures(); }); }) // item(s) removed .on("remove-items", function (e, arg) { //console.log("FG.REMOVE", { selected: featureGisManager.selectedItems.select(), evt: e, arg: arg }); return featureGisManager.remove(arg.items); }) .on("change-interface-modes", function (e, arg) { return featureGisManager.enable(arg.items.contains(modeName)); }); featureGisManager .on("change-enabled", function () { return setSelectedGisItems(featureManager.selectedItems); }) .on("change-selected-items", function (e, arg) { //console.log("SB.FGM_SELECTION", { evt: e, arg: arg, mgr: featureGisManager }); // ignore when event is not triggered by a user-action on the map if (arg.initiator !== "user" || (!arg.selectedItems.length && !featureManager.selectedItems.length)) { // no changes -> do nothing return null; } // set selected features return featureManager.setSelectedItems(arg.selectedItems); }); return Promise.resolve(bs); }; this.initFeatureHtml = function (featureHtmlManager, featureManager, featureHelper, featureGisManager, gisViewer) { var modeName = "html"; var filterHtmlItems = function (items) { return items.where(function (x) { return featureHelper.isLabel(x) || featureHelper.isImage(x); }); }; var setHtmlItems = F.debounce(function () { var items = filterHtmlItems(featureManager.items); var selected = filterHtmlItems(featureManager.selectedItems); //console.log("SB.SET_HTML", { items: items, selected: selected, mgr: featureHtmlManager }); return Promise.resolve() .then(function () { if (!config.canEdit || !featureManager.enabled || !featureHtmlManager.enabled) { var deselected = selected; items = []; selected = []; return featureGisManager.show(deselected); } return false; }) .then(function () { return featureHtmlManager.setItems(items); }) .then(function () { return featureHtmlManager.setSelectedItems(selected); }) .then(function () { return $timeout(250); }); }, 50); var saveHtmlItems = F.debounce(function (items) { return featureManager.save(items); }, 50); featureManager .on("change-enabled", function () { return setHtmlItems(); }) .on("change-items", function () { setHtmlItems(); }) .on("change-selected-items", function (e, arg) { //console.log("SB.FM.SELECTION", { selected: featureManager.selectedItems.select(), manager: featureHtmlManager }); if (!config.canEdit || !featureManager.enabled || !featureHtmlManager.enabled) { return featureHtmlManager.setItems([]) .then($timeout); } var selected = filterHtmlItems(arg.selectedItems); //var deselected = filterHtmlItems(arg.removed); return featureHtmlManager.setItems(selected) .then(function () { return featureHtmlManager.setSelectedItems(selected); }) .then($timeout); }) .on("save-items", function (e, arg) { var hasModifiedSelectedItems = filterHtmlItems(featureManager.selectedItems).innerJoin(arg.modified).length; //console.log("SB.SAVE_ITEM_HTML", { hasModifiedSelectedItems: hasModifiedSelectedItems, evt: e, arg: arg, mgr: featureHtmlManager }); if (hasModifiedSelectedItems) { return featureHtmlManager.setItems(arg.items) .then(function () { return featureHtmlManager.setSelectedItems(featureManager.selectedItems); }) .then($timeout); } return null; }) .on("change-interface-modes", function (e, arg) { return featureHtmlManager.enable(arg.items.contains(modeName)); }); featureHtmlManager .on("change-enabled", function () { return setHtmlItems(); }) .on("change-selected-items", function (e, arg) { //console.log("SB.FHM_SELECTION", { evt: e, arg: arg, mgr: featureHtmlManager }); if (!config.canEdit || !featureManager.enabled || !featureHtmlManager.enabled) { return null; } var selected = arg.selectedItems; var deselected = arg.removed; return Promise.resolve() .then(function () { if (selected.length > 0) { return featureGisManager.hide(selected); } return true; }) .then(function () { if (deselected.length) { return featureGisManager.show(deselected); } return true; }) .then(function () { if (selected.length > 0) { return featureGisManager.update(selected); } return true; }); }) .on("copy-item", function (e, arg) { return gisViewer.getCoordinateFromPixel(arg.pixel) .then(function (coordinate) { return featureManager.copyItem(arg.item, { type: "Point", coordinates: coordinate }); }) .then(function (items) { return featureManager.save(items); }) .then(function (items) { // select cloned feature after creation if (featureHtmlManager.enabled) { return featureManager.selectItems(items); } return true; }); }) .on("move-item", function (e, arg) { return gisViewer.getCoordinateFromPixel(arg.pixel) .then(function (coordinate) { var geometry = featureHelper.getGeometry(arg.item); geometry.coordinates = coordinate; return featureManager.save(arg.item); }); }) .on("resize-item", function (e, arg) { var style = featureHelper.getStyle(arg.item); var factor = arg.size[1] / arg.originalSize[1]; if ("height" in style) { style.height *= factor; } if ("width" in style) { style.width *= factor; } if (arg.type === "image") { style.image.scale *= factor; } else if (arg.type === "label") { style.label.scale *= factor; } return saveHtmlItems(arg.item); }) .on("rotate-item", function (e, arg) { var style = featureHelper.getStyle(arg.item); style.rotation = arg.rotation; return featureManager.save(arg.item); }); gisViewer .on("scale-change center-change resize-map", function () { //console.log("SB.VC", e.type, { args: arguments }); setHtmlItems(); }); var windowSize = [$(window).width(), $(window).height()]; $(window).on("resize", function () { var newSize = [$(window).width(), $(window).height()]; if (windowSize[0] !== newSize[0] || windowSize[1] !== newSize[1]) { windowSize = newSize; setHtmlItems(); } }); return Promise.resolve(bs); }; this.initFeatureFabric = function (featureFabricManager, featureManager, featureHelper, featureGisManager, gisViewer) { var modeName = "fabric"; var filterFabricItems = function (items) { var fabricItems = items.where(function (x) { return featureHelper.isImage(x); }); return gisViewer.getMapInfo() .then(function (info) { return Promise.all(fabricItems.select(function (x) { return info.extent.contains(featureHelper.getGeometry(x)) .then(function (valid) { if (valid) { return x; } return null; }); })); }) .then(function (fabricItems) { return fabricItems.where(function (x) { return x != null; }); }); }; var setSelectedItems = function () { return filterFabricItems(featureManager.selectedItems) .then(function (selected) { if (!config.canEdit || !featureManager.enabled || !featureFabricManager.enabled) { selected = []; } return featureFabricManager.setSelectedItems(selected); }); }; var setFabricItems = F.debounce(function () { return filterFabricItems(featureManager.items) .then(function (items) { if (!config.canEdit || !featureManager.enabled || !featureFabricManager.enabled) { items = []; } return items; }) .then(function (items) { return Promise.resolve() .then(function () { return featureFabricManager.init({ items: items }); }) .then(function () { if (featureFabricManager.enabled) { return featureGisManager.hide(items); } else { return featureFabricManager.getFeatures() .then(function (items) { return featureGisManager.show(items); }); } }); }) .then(function () { return setSelectedItems(); }) .then($timeout); }, 50); featureManager .on("change-enabled", function (/*e, arg*/) { //console.log("SB.FM_ITEMS", { evt: e, arg: arg, mgr: featureFabricManager }); return featureFabricManager .init({ enabled: featureManager.hasMode(modeName) }); }) .on("change-items", function () { return setFabricItems(); }) .on("change-selected-items", function (/*e, arg*/) { //console.log("SB.FM.SELECTION", { selected: featureManager.selectedItems.select(), manager: featureFabricManager }); return setSelectedItems(); }) .on("change-interface-modes", function (e, arg) { return featureFabricManager.enable(arg.items.contains(modeName)); }) .on("save-items", function (/*e, arg*/) { //console.log("SB.SAVE_ITEM_FABRIC", { evt: e, arg: arg, mgr: featureFabricManager }); setFabricItems(); }); featureFabricManager .on("change-enabled", function () { //console.log("SB.FFM_ENABLED", { mgr: featureFabricManager }); if (featureFabricManager.enabled) { return infoManager.push({ info: "global.MapDisabled", cancel: function () { return featureManager.setModes(["style", "gis", "html"]); } }); } else { return infoManager.cancel(); } }) .on("change-enabled modify-items", function () { var currentSelection = featureManager.selectedItems.select(); if (featureFabricManager.canvas == null || projectManager.activeItem == null) { return $timeout(); } return Promise.resolve() // show/hide canvas .then(function () { if (featureFabricManager.enabled) { $(featureFabricManager.canvas.wrapperEl) .appendTo(gisViewer.element) .show(); } else { $(featureFabricManager.canvas.wrapperEl) .hide(); } }) .then(function () { // deselect items first to ungroup them (causes problems with rotating multiple features at once) return featureFabricManager.setSelectedItems([]) // update features .then(function () { return filterFabricItems(featureManager.items) .then(function (items) { console.debug("SBF.MODIFY_FEATURES", { items: items }); return featureFabricManager.updateFeatures(items); }) .then(function (items) { return featureManager.save(items); }); }) // show features .then(function () { if (!featureFabricManager.enabled) { return filterFabricItems(featureManager.items) .then(function (items) { return featureGisManager.show(items); }); } return true; }) // restore selected items .then(function () { return featureFabricManager.setSelectedItems(currentSelection); }); }) .then(function () { setFabricItems(); }); }) .on("change-selected-items", function (e, arg) { //console.log("SB.FFM_SELECTED", { evt: e, arg: arg, mgr: featureFabricManager }); return Promise.resolve(arg.selectedItems) .then(function (features) { // ignore when event is not triggered by a user-action on the map // no changes -> do nothing if (arg.initiator !== "user" || (!features.length && !featureManager.selectedItems.length)) { return null; } // set selected features return featureManager.setSelectedItems(features); }); }) .on("start-copy", function (e, arg) { //console.log("SB.START_COPY", { evt: e, arg: arg, mgr: featureFabricManager }); return featureGisManager.show(arg.items); }) .on("end-copy", function (e, arg) { return Promise .enqueue(arg.items.select(function (clone) { return function () { return gisViewer.getCoordinateFromPixel(clone.pixel) .then(function (coordinate) { return featureManager.copyItem(clone.item, { type: "Point", coordinates: coordinate }); }); }; })) .then(function (items) { return featureManager.save(items); }); }); gisViewer .on("scale-change center-change resize-map", function (/*e*/) { if (featureFabricManager.enabled) { //console.log("SB.FFM_CHANGE_MAP", { evt: e, args: arguments }); setFabricItems(); } }); var windowSize = [$(window).width(), $(window).height()]; $(window).on("resize", function () { var newSize = [$(window).width(), $(window).height()]; if (windowSize[0] !== newSize[0] || windowSize[1] !== newSize[1]) { windowSize = newSize; setFabricItems(); } }); return Promise.resolve(bs); }; this.initBackup = function (featureManager, backupManager) { var _ignoreBackup = false; function backup() { if (_ignoreBackup) { return; } backupManager.backup(featureManager.items); } projectManager .on("change-active-item", function (e, arg) { if (!arg.hasChanged) { return; } backupManager.clear(); }) .on("save-features", function (/*e, arg*/) { //console.log("SB.PROJECT_FEATURES_SAVE", { evt: e, arg: arg }); backupManager.clear(); projectManager.canChangeActiveItem = true; }); featureManager .on("init remove-items save-items change-item-index", function (/*e, arg*/) { //console.log("SB.FEATURES_CHANGE", { evt: e, arg: arg }); backup(); }); backupManager .on("backup", function () { // nothing... projectManager.canChangeActiveItem = !backupManager.canUndo; }) .on("restore", function (e, arg) { _ignoreBackup = true; return featureManager.remove(featureManager.items) .then(function () { return featureManager.save(arg.backup); }) .then(function () { projectManager.canChangeActiveItem = !backupManager.canUndo; if (failedChangeProjectMessage != null && projectManager.canChangeActiveItem) { failedChangeProjectMessage.cancel(); } _ignoreBackup = false; return $timeout(); }); }); return Promise.resolve(bs); }; this.initDroppableViewer = function (gisViewer, featureManager, pictureService) { gisViewer.element .on("dragover", function (e) { e.preventDefault(); }) .on("drop", function (e) { var dt = e.dataTransfer || e.originalEvent.dataTransfer; if (dt && dt.files) { e.preventDefault(); e.stopImmediatePropagation(); if (!featureManager.enabled) { return null; } var files = e.target.files || dt.files; var position = { x: e.originalEvent.offsetX, y: e.originalEvent.offsetY }; if (files && files.length) { var file = files[0]; var pixel = [parseInt(position.x, 10), parseInt(position.y, 10)]; return pictureService.createNew(file) .then(function (symbol) { return pictureService.save(symbol); }) .then(function (savedSymbol) { return gisViewer.getCoordinateFromPixel(pixel) .then(function (coordinate) { var factor = (savedSymbol.width > 640) ? (640 / savedSymbol.width) : 1; //console.log("SB.SAVED_SYMBOL", { pic: savedSymbol }); return featureManager.getNewImage({ url: pictureService.getUrl(savedSymbol, $scope.currentLanguage), width: savedSymbol.width, height: savedSymbol.height, scale: gisViewer.scale * factor }, { type: "Point", coordinates: coordinate }); }) .then(function (item) { return featureManager.save(item); }); }); } } return null; }); return Promise.resolve(bs); }; this.initCommands = function (commandBag, $translate) { var configProjectenTitle = config.projectenTitle; var configEvacuatieTitle = config.evacuatieTitle; commandBag.add([{ name: moduleName + ".Projects", content: '', title: function () { return $translate("global.Projects"); } }, { name: moduleName + ".ShowEvacuatie", content: '', title: function () { return configEvacuatieTitle || $translate(moduleName + ".Signalling"); } }]); return Promise.resolve(bs); }; this.initPanels = function (commandBag, backupManager) { var panelManager = new PanelManager($(".content-container")); function disableProjectPanel() { panelManager.freezePanel($("#ProjectContainer")); panelManager.disablePanel("right"); commandBag.disable(commandBag.items.where(function (x) { var toIgnore = "security.User,gislegend.Legend,TrackMyLocation,crab.SearchAddress,ZoomIn,ZoomOut,InitialExtent".split(","); return !toIgnore.contains(x.name); })); } function enableProjectPanel() { panelManager.unfreezePanel($("#ProjectContainer")); panelManager.enablePanel("right"); commandBag.enableAll(); } function disableEvacuatiePanel() { panelManager.freezePanel($("#EvacuatieContainer")); panelManager.disablePanel("bottom"); commandBag.disable(commandBag.items.where(function (x) { var toIgnore = "security.User,gislegend.Legend,TrackMyLocation,crab.SearchAddress,ZoomIn,ZoomOut,InitialExtent".split(","); return !toIgnore.contains(x.name); })); } function enableEvacuatiePanel() { panelManager.unfreezePanel($("#EvacuatieContainer")); panelManager.enablePanel("bottom"); commandBag.enableAll(); } projectManager .on("change-display", function (e, arg) { if (arg.display === "form") { disableProjectPanel(); } else { enableProjectPanel(); } }); backupManager .on("backup restore clear", function () { //console.log("SB.CHECK_PANELS", { args: arguments }); var disable = backupManager.canUndo; if (disable) { disableEvacuatiePanel(); } else { enableEvacuatiePanel(); } }); return Promise.resolve(bs); }; this.initElements = function (commandBag, featureManager, $compile) { var pm = new PanelManager($(".content-container")); var projectContainer = $('
').hide(); $compile(projectContainer)($scope).appendTo($(".panel-bottom")); evacuatieContainer = $("#EvacuatieContainer"); commandBag .on("execute", moduleName + ".Projects", function () { pm.show($("#ProjectContainer"), "bottom"); }) .on("execute", moduleName + ".ShowEvacuatie", function () { pm.show($("#EvacuatieContainer"), "right", "full"); }); pm.container .on("shown closed", function () { var isVisible = evacuatieContainer.is(":visible"); featureManager.enable(isVisible); }); // feature html markers var featureHtmlContainer = $('
'); $compile(featureHtmlContainer)($scope).appendTo($(".viewer-container:first")); return Promise.resolve(bs); }; this.initCss = function () { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); return Promise.resolve(bs); }; this.initPrint = function (printService) { printService .on("before-print", function (e, arg) { var project = projectManager.activeItem; //console.log("SM.PRINTING", { evt: e, arg: arg, project: project }); if (project && project.geoJson && project.geoJson.properties) { arg.addParameter("TITLE", project.title); arg.addParameter("CODE", project.code); arg.addParameter("PROJECT_DESCRIPTION", project.description); arg.addParameter("PROJECT_STARTDATE", project.startDate); arg.addParameter("PROJECT_ENDDATE", project.endDate); arg.addParameter("PROJECT_CATEGORY_NL", project.category.titleNL); arg.addParameter("PROJECT_CATEGORY_FR", project.category.titleFR); var identifiers = project.geoJson.features .where(function (f) { return f.properties.style.image && f.properties.style.image.iconUrl; }) .select(function (f) { return Q.queryUrl("identifier", f.properties.style.image.iconUrl); }); arg.addParameter("SYMBOL_LEGEND_URL", window.location.origin + config.baseUrl + "/Handlers/DynamicSymbolLegend.aspx?niscode=" + $scope.niscode + "&identifier=" + identifiers.join(",")); arg.clientFilename = "print-" + project.code + "-" + arg.template.Name + "-" + moment().format("YYYYMMDDhhmmss") + ".pdf"; var props = project.geoJson.properties; Object.keys(props).forEach(function (key) { arg.addParameter(key, props[key]); }); } }); return Promise.resolve(bs); }; this.initShortCuts = function (hotkeyService, featureManager, featureHelper, gisViewerManager) { function getPointFeatures() { if (featureManager.enabled) { return featureManager.selectedItems.where(function (x) { return featureHelper.isPoint(x); }); } return []; } hotkeyService .on("alt+f", function (e /*, handler*/) { //console.log("HOTKEY_SERVICE", { evt: e, handler: handler, thisScope: this, featureManager: featureManager }); if (featureManager.enabled) { e.preventDefault(); var modes = !featureManager.interfaceModes.contains("fabric") ? ["style", "fabric"] : ["style", "gis", "html"]; featureManager.setModes(modes); } }); hotkeyService .on("up,right,down,left", function (e) { var features = getPointFeatures(); if (!features.any()) { return; } features.forEach(function (feature) { var geometry = featureHelper.getGeometry(feature); var coordinates = geometry.coordinates; switch (e.code) { case "ArrowUp": coordinates[1]++; break; case "ArrowRight": coordinates[0]++; break; case "ArrowDown": coordinates[1]--; break; case "ArrowLeft": coordinates[0]--; break; } }); featureManager.save(features); }); hotkeyService .on("shift+up,shift+down", function (e) { var features = getPointFeatures() .where(function (f) { return !featureHelper.isSimplePoint(f); }); if (!features.any()) { return; } features.forEach(function (feature) { var featureStyle = featureHelper.getStyle(feature); var style = { height: featureStyle.height }; if (style.height == null) { style.height = featureHelper.calcHeightUnits(feature, gisViewerManager.scale, gisViewerManager.unitsPerPixel); } switch (e.code) { case "ArrowUp": style.height++; break; case "ArrowDown": if (style.height > 1) { style.height--; } break; } featureHelper.updateItems([feature], style, gisViewerManager.scale, gisViewerManager.unitsPerPixel, null); }); featureManager.save(features); }); return Promise.resolve(bs); }; this.initSecurity = function (projectSecurityManager, userManager) { projectManager // active project changed .on("change-active-item", function (e, arg) { //console.log("SECURITY.CHANGE_PROJECT", { evt: e, arg: arg }); projectSecurityManager.loadProjectAndUsers(arg.activated); }); return userManager.list() .then(function () { return Promise.resolve(bs); }); }; this.initHashEvents = function (locationHashHelper, commandBag) { var hashEvents = (function () { return { showEvacuatie: [function () { commandBag.execute(moduleName + ".ShowEvacuatie"); }], project: [function (v) { var activeItem = projectManager.activeItem; var projectCode = v.project; if ((!activeItem && projectCode) || (activeItem && activeItem.code !== projectCode)) { projectManager.activateByFilter({ code: projectCode }); } }], zoomProject: [function () { if (projectManager.activeItem != null) { return projectManager.focus(projectManager.activeItem); } return false; }] }; })(); locationHashHelper.addHashchangeEvents(hashEvents); return Promise.resolve(bs); }; this.initToolbar = function (toolbarService) { return toolbarService .buildTree([ "Home", "security.User", "separator", //---------- !evacuatieConfig.submitProjectUrl ? moduleName + ".Projects" : null, moduleName + ".ShowEvacuatie", //!evacuatieConfig.submitProjectUrl && evacuatieConfig.gipodEnabled ? "Gipod.ShowHandhaving" : null, //!evacuatieConfig.submitProjectUrl && evacuatieConfig.gipodEnabled ? "ToggleGipodFilter" : null, !evacuatieConfig.submitProjectUrl ? "notities.Open" : null, //"notities.AddGpsNotitie", //"schetsen.Open", !evacuatieConfig.submitProjectUrl ? "dwf.Open" : null, //"separator", //---------- "Print", //"measure.Measure", //"crab.SearchAddress", //"TrackMyLocation", //"featureinfo.ShowSelection", "gislegend.Legend" ].where(function (x) { return x != null; })) .then(function () { return bs; }); }; this.initOnlineState = function (onlineStateService) { var offlineMsg = null; onlineStateService .on("change-online-state", function (e, arg) { if (!arg.isOnline) { return infoManager.push({ info: "global.Offline" }) .then(function (msg) { offlineMsg = msg; return $timeout(); }); } else if (offlineMsg != null) { offlineMsg.cancel(); } return $timeout(); }); return bs; }; //this.initGipodConfig = function() { // if (evacuatieConfig.gipodEnabled) { // return Promise.resolve() // .then(function() { // if (!config.gipodConfigApi) { // throw "Missing configuration: gipodConfigApi"; // } // return $http.get(config.gipodConfigApi) // .then(function (gipodConfig) { // evacuatieConfig.gipod = gipodConfig.data; // evacuatieConfig.trigger("gipodLoad", evacuatieConfig.gipod); // return bs; // }); // }) // .catch(function(err) { // G.handleError({ translate: 'gipod.ConfigurationMissing' }); // console.error("Failed to load Gipod configuration", err, config.gipodConfigApi); // return bs; // }); // } // return bs; //}; } return Bootstrapper; })("evacuatie"); var evacuatie = evacuatie || {}; evacuatie.buttonsComponent = (function () { "use strict"; function ButtonsViewModel() { Object.defineProperties(this, { canEdit: { writable: true }, canAdd: { writable: true }, canSelectProject: { writable: true }, container: { writable: true }, containerDisplay: { writable: true }, display: { writable: true }, isLocked: { writable: true }, displayfilter: { writable: true }, fabricmodeEnabled: { writable: true }, displayscalebar: { writable: true }, scalebarValue: { value: 100, writable: true }, moveEnabled: { writable: true }, submitProjectUrl: { writable: true }, onChangeContainer: { writable: true }, onChangeContainerDisplay: { writable: true }, onChangeDisplay: { writable: true }, onChangeFilterdisplay: { writable: true }, onChangeFabricmode: { writable: true }, onChangeScalebardisplay: { writable: true }, onFocus: { writable: true }, onSave: { writable: true }, onCancel: { writable: true }, onChangeListposition: { writable: true }, onExportGeoJson: { writable: true }, onImportGeoJson: { writable: true }, onExportReport: { writable: true }, onUndo: { writable: true }, onRedo: { writable: true }, onSubmitProject: { writable: true } }); } Object.defineProperties(ButtonsViewModel.prototype, { setContainer: { value: function (e, container) { return this.onChangeContainer({ event: e, container: container }); } }, setContainerDisplay: { value: function (e, containerDisplay) { return this.onChangeContainerDisplay({ event: e, containerDisplay: containerDisplay }); } }, setDisplay: { value: function (e, display) { return this.onChangeDisplay({ event: e, display: display }); } }, toggleFilter: { value: function (e) { return this.onChangeFilterdisplay({ event: e, visible: !this.displayfilter }); } }, toggleFabricmode: { value: function (e) { return this.onChangeFabricmode({ event: e, enabled: !this.fabricmodeEnabled }); } }, toggleScalebar: { value: function (e) { return this.onChangeScalebardisplay({ event: e, visible: !this.displayscalebar }); } }, handleFocus: { value: function (e) { return this.onFocus({ event: e }); } }, handleSave: { value: function (e) { return this.onSave({ event: e }); } }, handleCancel: { value: function (e) { return this.onCancel({ event: e }); } }, handleMove: { value: function (e, steps) { return this.onChangeListposition({ event: e, steps: steps }); } }, handleExportGeoJson: { value: function (e) { return this.onExportGeoJson({ event: e }); } }, handleImportGeoJson: { value: function (e) { return this.onImportGeoJson({ event: e }); } }, handleExportReport: { value: function (e) { return this.onExportReport({ event: e }); } }, handleRemove: { value: function (e) { return this.onRemove({ event: e }); } }, handleReset: { value: function (e) { return this.onReset({ event: e }); } }, handleZoom: { value: function (e) { return this.onZoom({ event: e }); } }, handleUndo: { value: function (e) { return this.onUndo({ event: e }); } }, handleRedo: { value: function (e) { return this.onRedo({ event: e }); } }, submitProject: { value: function (e) { return this.onSubmitProject({ event: e }); } }, }); function buttonsComponent(templateUrl) { return { controller: ButtonsViewModel, bindings: { canEdit: "<", canAdd: "<", canUndo: "<", canRedo: "<", canSelectProject: "<", container: "<", containerDisplay: "<", display: "<", isLocked: "<", displayfilter: "<", fabricmodeEnabled: "<", displayscalebar: "<", scalebarValue: "<", moveEnabled: "<", submitProjectUrl: "<", onChangeContainer: "&", onChangeDisplay: "&", onChangeContainerDisplay: "&", onChangeFilterdisplay: "&", onChangeFabricmode: "&", onChangeScalebardisplay: "&", onFocus: "&", onSave: "&", onCancel: "&", onChangeListposition: "&", onExportGeoJson: "&", onImportGeoJson: "&", onExportReport: "&", onUndo: "&", onRedo: "&", onSubmitProject: "&" }, templateUrl: ["config", function (config) { return config.baseUrl + "/" + templateUrl + "?v=" + config.version; }], transclude: { count: "?countTemplate", filter: "?filterTemplate", scalebar: "?scalebarTemplate" } }; } return buttonsComponent; })(); var evacuatie = evacuatie || {}; evacuatie.EvacuatieController = (function (moduleName) { "use strict"; var _display = "form"; function EvacuatieController(projectManager, featureManager, backupManager, featureHelper, featureHtmlManager, featureFabricManager, imageHelper, gisViewerManager, $timeout, evacuatieConfig) { var ctrl = this; Object.defineProperties(ctrl, { //container: home, list, styling container: { value: "list", writable: true, enumerable: true }, containerDisplay: { value: "digitize", writable: true, enumerable: true }, //display: form, details loading: { value: false, writable: true }, showfilter: { value: false, writable: true }, showscalebar: { value: false, writable: true }, _projectManager: { value: projectManager }, _featureManager: { value: featureManager }, _backupManager: { value: backupManager }, _featureHelper: { value: featureHelper }, _featureHtmlManager: { value: featureHtmlManager }, _featureFabricManager: { value: featureFabricManager }, _imageHelper: { value: imageHelper }, _fileHelper: { value: imageHelper }, _gisViewer: { value: gisViewerManager }, _timeout: { value: F.debounce($timeout, 25) }, stateManager: { value: StateManagerFactory.createEntityStateManager(_.newGuid(), { controller: ctrl, entityType: 'Evacuatie', module: moduleName }), enumerable: true }, evacuatieConfig: { value: evacuatieConfig } }); featureManager .on("change-selected-items", function (e, arg) { if (arg.selectedItems.length) { ctrl.container = "list"; } }); ctrl.featuremode = "gis"; //console.log("S.CTRL", { ctrl: ctrl }); } Object.defineProperties(EvacuatieController.prototype, { interfaceModes: { get: function () { return this._featureManager.interfaceModes; }, enumerable: true }, canEditModule: { get: function () { return this.interfaceModes.length > 0; }, enumerable: true }, display: { get: function () { return this.canEditModule ? _display : "details"; }, set: function (value) { _display = value || "details"; }, enumerable: true }, canUndo: { get: function () { return this.canEditModule && this._backupManager.canUndo; }, enumerable: true }, canRedo: { get: function () { return this.canEditModule && this._backupManager.canRedo; }, enumerable: true }, formProject: { get: function () { return this._projectManager.formItem; }, enumerable: true }, activeProject: { get: function () { return this._projectManager.activeItem; }, enumerable: true }, projects: { get: function () { return this._projectManager.items; }, enumerable: true }, features: { get: function () { return this._featureManager.items; }, enumerable: true }, scale: { get: function () { return this._gisViewer.scale; }, enumerable: true }, unitsPerPixel: { get: function () { return this._gisViewer.unitsPerPixel; }, enumerable: true }, selectProject: { value: function (project) { var ctrl = this; if (project == null) { return ctrl._projectManager.setActiveItem(null); } //console.log("SC.SELECT_PROJECT", { project: project, ctrl: ctrl }); ctrl.container = "list"; var unloadProject; if (ctrl.activeProject != null) { if (project.id === ctrl.activeProject.id) { // no changes, list features again return Promise.resolve(ctrl.activeProject); } else { // unload previous active project unloadProject = ctrl.activeProject; } } return ctrl._projectManager.setActiveItem(project) .then(function (arg) { if (unloadProject != null) { return ctrl._projectManager.unloadItem(unloadProject) .then(function () { return arg; }); } return arg; }); } }, loadFeatures: { value: function (features) { var ctrl = this; //console.log("SC.LOAD_FEATURES", { items: features, ctrl: ctrl }); var loaded = _.array(features || []); var selected = ctrl._featureManager.selectedItems; if (!loaded.length) { loaded = selected.length ? selected : ctrl.features; } return ctrl._featureManager.setLoadedItems(loaded) .then(function (arg) { ctrl.container = "styling"; ctrl._timeout(); return arg; }); } }, focusLoadedFeatures: { value: function (options) { return this._featureManager.focus(this._featureManager.loadedItems, options); } }, save: { value: function () { var ctrl = this; var state = ctrl.stateManager.addState("loading"); //console.log("SC.SAVE", { item: this.activeProject, features: this.features, ctrl: this }); return ctrl._projectManager.saveFeatures(ctrl.formProject || ctrl.activeProject, ctrl.features) .then(state.completed) .catch(function (error) { state.error(error); G.handleError(error); }); } }, cancel: { value: function () { var ctrl = this; var state = ctrl.stateManager.addState("loading"); var currentProject = ctrl.activeProject; ctrl.showfilter = false; ctrl.showscalebar = false; ctrl._projectManager.canChangeActiveItem = true; // clear activeItem first so all references are also renewed return ctrl._projectManager.setActiveItem(null) .then(function () { // make sure to get the server version of the project return ctrl._projectManager.details(currentProject.id); }) .then(function (project) { return ctrl._projectManager.setActiveItem(project); }) .then(state.completed) .catch(function (error) { state.error(error); G.handleError(error); }); } }, newFeature: { value: function (geom, sourceFeature, extra) { var ctrl = this; extra = extra || {}; if (geom == null) { return Promise.resolve(null); } var promise = Promise.resolve(); switch (geom.type) { case "Point": case "MultiPoint": var pointOptions = { isLabel: extra.isLabel, scale: ctrl._gisViewer.scale, upp: ctrl._gisViewer.unitsPerPixel, height: extra.isLabel ? 1 : null, isImage: extra.isImage, transparency: extra.transparency }; promise = ctrl._featureManager.getNewPoint(pointOptions, geom.geoJson); //promise = ctrl._featureManager.getNewLabel({ scale: ctrl._gisViewer.scale }, geom.geoJson); break; case "LineString": case "MultiLineString": var lineOptions = { measure: extra.isMeasure ? 1 : 0, arrowLocation: extra.arrowLocation, labelLocation: extra.labelLocation, transparency: extra.transparency }; promise = ctrl._featureManager.getNewLineString(lineOptions, geom.geoJson); break; case "Polygon": case "MultiPolygon": promise = ctrl._featureManager.getNewPolygon({ transparency: extra.transparency }, geom.geoJson); break; } return promise .then(function (item) { if (item == null) { return null; } if (sourceFeature != null && sourceFeature.type === "Feature") { //console.log("SC.SRC_FEATURE", { sourceFeature: sourceFeature }); var sourceStyle = ctrl._featureHelper.getStyle(sourceFeature); $.extend(true, ctrl._featureHelper.getStyle(item), sourceStyle); } return ctrl._featureManager.save(item) .then(function (items) { //console.log("SC.SAVED_FEATURE", { features: items, ctrl: ctrl }); if (items.length === 1) { var saved = items.first(); if (!ctrl._featureHelper.isImage(saved)) { return ctrl.loadFeatures(saved); } } return items; }); }); } }, saveFeature: { value: function (feature) { return this._featureManager.save(feature); } }, addImageFeature: { // url: url to the actual picture (real size) // size: the size in which the picture thumbnail is added // pixel: destination of the picture in the map-container value: function (item, url, size, pixel) { var ctrl = this; return ctrl._gisViewer.getCoordinateFromPixel(pixel) .then(function (coordinate) { return ctrl._imageHelper.getImageFromUrl(url) .then(function (img) { // bereken de verhouding van de ware grootte van het symbool (img) met die van de thumbnail (size parameter) var factor = size[0] / img.width; return ctrl._featureManager.getNewImage({ url: url, width: item.resizeByScale ? item.width : img.width, height: item.resizeByScale ? item.height : img.height, scale: item.defaultScale || (ctrl._gisViewer.scale * factor), resizeByScale: item.resizeByScale }, { type: "Point", coordinates: coordinate }); }); }) .then(function (item) { //var style = item.properties.style; //console.log('NEW.FEATURE.STYLE', 'mapScale', ctrl._gisViewer.scale, 'width', style.width, 'height', style.height, 'imgWidth', style.image.width, 'imgHeight', style.image.height, 'imgScale', style.image.scale); return ctrl._featureManager.save(item); }); } }, toggleFabricmode: { value: function (enabled) { var modes = enabled ? ["style", "fabric"] : ["style", "gis", "html"]; return this._featureManager.setModes(modes); } }, exportGeoJson: { value: function () { var ctrl = this; var features = ctrl.features; if (ctrl._featureManager.selectedItems.length) { features = ctrl._featureManager.selectedItems; } var project = $.extend(true, {}, ctrl.activeProject); project.geoJson.features = features; var geoJson = JSON.stringify(project.geoJson, null, 2); //console.log("SC.GEOJSON", { project: project, json: geoJson }); return ctrl._fileHelper.writeAllText(geoJson, "application/geojson", project.layerName + ".geojson") .then(function (blob) { return ctrl._fileHelper.forceDownload(blob); }); } }, importGeoJson: { value: function (includeProperties) { var ctrl = this; return ctrl._fileHelper.browse({ accept: ".geojson" }) .then(function (files) { var promises = files.select(function (file) { return ctrl._fileHelper.readAllText(file) .then(function (content) { var geoJson = JSON.parse(content); console.log("SC.IMPORT", { project: ctrl.activeProject, json: geoJson }); return ctrl._projectManager._service._processFeatures(geoJson.features); }) .then(function (features) { ctrl._featureManager.importItems(features); if (includeProperties) { //ctrl._service._geoJsonProperties.forEach(function (key) { // if (typeof (geoJson.properties[key]) !== "undefined") { // project.geoJson.properties = geoJson.properties[key]; // project[key] = geoJson.properties[key]; // } //}); } }); }); return Promise.all(promises); }); } }, exportReport: { value: function (exportType) { var ctrl = this; var state = ctrl.stateManager.addState("loading"); return this._projectManager.getReport(exportType) .then(state.completed) .catch(function (error) { state.error(error); throw error; }); } }, backup: { value: function () { this._backupManager.backup(this.activeProject.geoJson.features); } }, undo: { value: function () { return this._backupManager.undo(); } }, redo: { value: function () { return this._backupManager.redo(); } }, submitProject: { value: function () { if (!confirm('Ben je zeker dat het evacuatieplan volledig is en ingediend mag worden?')) { return Promise.reject(); } var ctrl = this; var state = ctrl.stateManager.addState("loading"); return G.ajax({ controller: 'Evacuatie', action: 'SubmitProject', data: { projectCode: ctrl.activeProject.code, submitProjectUrl: ctrl.evacuatieConfig.submitProjectUrl }, type: "POST", success: function (response) { if (response.message) { alert(response.message); } if (response.redirectUrl) { window.location.href = response.redirectUrl; } else { window.close(); } }, error: function (error) { state.error(error); G.handleError(error); } }); } } }); return EvacuatieController; })("evacuatie"); var evacuatie = evacuatie || {}; evacuatie.EvacuatieDirective = (function (moduleName) { function EvacuatieDirective(config) { return { restrict: "EA", template: '
' }; } return EvacuatieDirective; })("evacuatie"); var evacuatie = evacuatie || {}; evacuatie.projectButtonsComponent = (function () { "use strict"; function ProjectButtonsViewModel() { Object.defineProperties(this, { showFilter: { writable: true }, showZoom: { writable: true }, display: { writable: true }, isLocked: { writable: true }, canCreate: { writable: true }, canEdit: { writable: true }, onAddItem: { writable: true }, onChangeFilterDisplay: { writable: true }, onExport: { writable: true }, onChangeDisplay: { writable: true }, onSave: { writable: true }, onRemove: { writable: true }, onReset: { writable: true }, onZoom: { writable: true } }); } Object.defineProperties(ProjectButtonsViewModel.prototype, { handleAddItem: { value: function (e) { return this.onAddItem({ event: e }); } }, toggleFilter: { value: function (e) { return this.onChangeFilterDisplay({ event: e, visible: !this.showFilter }); } }, handleExport: { value: function (e) { return this.onExport({ event: e }); } }, setDisplay: { value: function (e, display) { return this.onChangeDisplay({ event: e, display: display }); } }, handleSave: { value: function (e) { return this.onSave({ event: e }); } }, handleRemove: { value: function (e) { return this.onRemove({ event: e }); } }, handleReset: { value: function (e) { return this.onReset({ event: e }); } }, handleZoom: { value: function (e) { return this.onZoom({ event: e }); } } }); function projectButtonsComponent(templateUrl) { return { controller: ProjectButtonsViewModel, bindings: { showFilter: "<", showZoom: "<", display: "<", isLocked: "<", canCreate: "<", canEdit: "<", onRemove: "&", onAddItem: "&", onChangeFilterDisplay: "&", onExport: "&", onChangeDisplay: "&", onSave: "&", onReset: "&", onZoom: "&" }, templateUrl: ["config", function (config) { return config.baseUrl + "/" + templateUrl + "?v=" + config.version; }] }; } return projectButtonsComponent; })(); var evacuatie = evacuatie || {}; evacuatie.ProjectController = (function (moduleName) { "use strict"; function ProjectController(config, manager, securityManager, fileHelper, $timeout, $translate) { var ctrl = this; projects.ProjectController.call(ctrl, manager, $timeout, $translate); Object.defineProperties(ctrl, { _fileHelper: { value: fileHelper }, _securityManager: { value: securityManager }, isAdministrator: { get: function () { return securityManager.isAdministrator(); }, enumerable: true }, isProjectLeider: { get: function () { return securityManager.isProjectLeider(); }, enumerable: true }, security: { value: Object.create(null, { getUsers: { value: function () { return this.projectUsers.select(function (pUser) { return pUser.user; }); } }, project: { get: function () { return securityManager.loadedProject; }, enumerable: true }, projectUsers: { get: function () { return securityManager.loadedProjectUsers; }, enumerable: true }, canEditModuleTitleTranslationKey: { get: function () { return 'evacuatie.CanEditEvacuatie'; }, enumerable: true }, canEditModuleProperty: { get: function () { return 'editEvacuatie'; }, enumerable: true }, isAdministrator: { get: function () { return securityManager.isAdministrator(); }, enumerable: true }, isProjectLeider: { get: function () { return securityManager.isProjectLeider(); }, enumerable: true }, canCreate: { value: function () { return securityManager.canCreate(); } }, canRead: { value: function (project) { return securityManager.canRead(project); } }, canEdit: { value: function (project) { return securityManager.canEdit(project); } }, addUsers: { value: function (users) { console.log("ADD_USERS", { users: _.array(users) }); return securityManager.addLoadedUsers(users); } }, removeUsers: { value: function (users) { console.log("REMOVE_USERS", { users: _.array(users) }); return securityManager.removeLoadedUsers(users); } }, listProjectUsers: { value: function () { return securityManager.loadProjectAndUsers(this.project); } }, saveProjectUsers: { // { project, projectUsers } value: function () { return securityManager.saveProjectUsers(this.project, this.projectUsers); } }, modifyProjectUser: { value: function (projectUser, prop, value) { return securityManager.modifyProjectUser(projectUser, prop, value); } } }) } }); ctrl.tabs = [{ code: 'general', displayTranslation: 'global.General' }, { code: 'admin', displayTranslation: 'global.Configuration' }, { code: 'security', displayTranslation: 'global.Security', show: function() { return ctrl.security.canEdit(ctrl.item); } }, { code: 'documents', displayTranslation: 'global.Documents', show: function () { return ctrl.item && ctrl.item.id > 0; } }]; ctrl.tabs.forEach(function(tab) { tab.src = tab.src || 'Content/modules/' + moduleName + '/project/tabs/' + tab.code + '.html?v=' + config.version; }); } ProjectController.prototype = Object.create(projects.ProjectController.prototype, { constructor: { value: ProjectController }, gisDocumentsLayerName: { value: 'evacuatie_projecten' }, categories: { get: function () { return this._manager.categories; }, enumerable: true }, onChangeDisplay: { value: function (o) { var ctrl = this; if (o.newValue === 'form') { ctrl.selectedTab = ctrl.tabs.first(); ctrl.security.showUserSelector = false; } } }, setItem: { value: function (item, display) { projects.ProjectController.prototype.setItem.call(this, item, display); item.documents = item.documents || []; }, configurable: true }, save: { value: function (project, projectUsers, display) { var ctrl = this; var state = ctrl.stateManager.addState("loading"); var isNew = !project.id || project.id <= 0; //console.log("SAVING_PROJECT", { project: project, projectUsers: projectUsers }); return ctrl._manager.save(project, display) .then(function (savedProject) { if (savedProject == null) { return false; } return Promise.resolve() .then(function () { if (!isNew) { return ctrl._securityManager.saveProjectUsers(savedProject, projectUsers); } return false; }) .then(function () { return ctrl._securityManager.loadProjectAndUsers(savedProject); }) .then(function (loadedProjectUsers) { project.id = savedProject.id; return ctrl._manager.setActiveItem(savedProject) .then(function () { return loadedProjectUsers; }); }); }) .then(ctrl._timeout) .then(state.completed) .catch(function (error) { state.error(error); G.handleError(error); }); } }, remove: { value: function () { return projects.ProjectController.prototype.remove.apply(this, arguments) .catch(function(error) { G.handleError(error); }); } }, // import/export importGeoJson: { value: function (includeProperties) { var ctrl = this; return ctrl._fileHelper.browse({ accept: ".geojson" }) .then(function (files) { return files.select(function (file) { return ctrl._fileHelper.readAllText(file); }); }) .then(function (geoJsonList) { return ctrl._manager.importGeoJson(ctrl.item, geoJsonList, includeProperties); //.then(ctrl._timeout); }) .then(function () { return ctrl.item; }); } }, exportGeoJson: { value: function () { var ctrl = this; return ctrl._manager.exportGeoJson(ctrl.item) .then(function (geoJson) { return ctrl._fileHelper.writeAllText(geoJson, "application/geojson", ctrl.item.layerName + ".geojson"); }) .then(function (blob) { return ctrl._fileHelper.forceDownload(blob); }); } }, exportExcel: { value: function (/*items*/) { //var items = ctrl.items; //ToDo: implement! alert("ToDo: export Excel"); } } }); return ProjectController; })("evacuatie"); var evacuatie = evacuatie || {}; evacuatie.projectFilterComponent = (function () { "use strict"; function ProjectFilterViewModel() { Object.defineProperties(this, { filter: { writable: true }, categories: { writable: true }, onChange: { writable: true }, onConfirm: { writable: true }, onReset: { writable: true } }); } Object.defineProperties(ProjectFilterViewModel.prototype, { handleChange: { value: function (e, prop) { return this.onChange({ event: e, prop: prop, filter: this.filter }); } }, handleConfirm: { value: function (e) { return this.onConfirm({ event: e, filter: this.filter }); } }, handleReset: { value: function (e) { return this.onReset({ event: e, filter: this.filter }); } } }); function projectFilterComponent(templateUrl) { return { controller: ProjectFilterViewModel, bindings: { filter: "<", categories: "<", onChange: "&", onConfirm: "&", onReset: "&" }, templateUrl: ["config", function (config) { return config.baseUrl + "/" + templateUrl + "?v=" + config.version; }] }; } return projectFilterComponent; })(); var evacuatie = evacuatie || {}; evacuatie.projectFormComponent = (function () { "use strict"; function ProjectFormViewModel($translate) { common.EntityFormViewModel.call(this); Object.defineProperties(this, { _translate: { value: $translate }, categories: { writable: true } }); } ProjectFormViewModel.prototype = Object.create(common.EntityFormViewModel.prototype, { constructor: { value: ProjectFormViewModel }, lang: { get: function () { return this._translate.use().toUpperCase(); }, enumerable: true } }); function projectFormComponent(templateUrl) { var component = common.entityFormComponent(templateUrl); $.extend(component, { controller: ["$translate", ProjectFormViewModel] }); $.extend(component.bindings, { isAdmin: "<", categories: "<", customFormUrl: "<" }); return component; } return projectFormComponent; })(); var evacuatie = evacuatie || {}; evacuatie.ProjectGisManager = (function () { "use strict"; function ProjectGisManager(config, gisViewer, gisVectorManager, geoHelper) { Object.defineProperties(this, { _config: { value: config }, _layers: { value: [] }, _viewer: { value: gisViewer }, _layerManager: { value: gisVectorManager.layer }, _featureManager: { value: gisVectorManager.feature }, _geoHelper: { value: geoHelper } }); } Object.defineProperties(ProjectGisManager.prototype, { getLayer: { value: function (item) { if (item == null) { return Promise.resolve(null); } return this._layerManager.createIfNotExists({ Code: item.layerName, Title: item.title, Transparency: 0, group: this._config.group }); } }, addItemToMap: { value: function (item) { var mgr = this; return mgr.getLayer(item) .then(function (layer) { var features = item.geoJson.features; return mgr._featureManager.add({ layer: layer, features: features }); }); } }, removeItemFromMap: { value: function (item) { var mgr = this; return mgr.getLayer(item) .then(function (layer) { return mgr._layerManager.remove({ layerName: layer.Code }); }); } }, getExtent: { value: function (items) { var mgr = this; var features = items.selectMany(function (item) { return item.geoJson.features; }); var bounds = !features.length ? null : mgr._geoHelper.getBounds(features); return Promise.resolve(bounds); } }, zoom: { value: function (items, minScale) { var mgr = this; return mgr.getExtent(items) .then(function (extent) { if (extent == null) { return false; } return mgr._viewer.zoomToExtent({ extent: extent, minScale: minScale }); }); } } }); return ProjectGisManager; })("evacuatie"); var evacuatie = evacuatie || {}; evacuatie.ProjectManager = (function () { "use strict"; function ProjectManager(service, gisdocumentConfig) { projects.ProjectManager.call(this, service); Object.defineProperties(this, { categories: { value: [], enumerable: true }, _gisdocumentConfig: { value: gisdocumentConfig } }); //console.log("SP.MGR", { mgr: this }); } ProjectManager.prototype = Object.create(projects.ProjectManager.prototype, { constructor: { value: ProjectManager }, canEditDocuments: { get: function() { return this._gisdocumentConfig.canEdit; } }, //init init: { value: function (o) { o = o || {}; var categories = o.categories || []; this.categories.clear().addRange(categories); return projects.ProjectManager.prototype.init.call(this, o); } }, save: { value: function(item, display) { var mgr = this; if (mgr.canEditDocuments) { item.documents = (item.documents || []).where(function (x) { return !x.removed; }); } return projects.ProjectManager.prototype.save.call(mgr, item, display); } }, // validation validate: { value: function (item) { var mgr = this; //console.log("SPM.VALIDATING", { item: item, mgr: mgr }); return projects.ProjectManager.prototype.validate.call(mgr, item) .then(function () { if (!item.category && !item.categoryId) { mgr.errors.push("CategoryMissing"); } return !mgr.errors.length; }); } }, saveFeatures: { value: function (item, features) { var mgr = this; //console.log("SPM.SAVE", { item: $.extend(true, {}, item), features: features }); var original = $.extend(true, {}, item); return Promise.resolve(item) .then(function () { if (features) { //cleanup geometries features.forEach(function(feature) { if (feature.geometry.type === "LineString") { //remove duplicate coordinates var coordinates = []; feature.geometry.coordinates.forEach(function(coordinate) { if (!coordinates.length) { coordinates.push(coordinate); return; } var lastCoordinate = coordinates.last(); if (lastCoordinate[0] !== coordinate[0] || lastCoordinate[1] !== coordinate[1]) { coordinates.push(coordinate); } }); if (feature.geometry.coordinates.length !== coordinates.length) { feature.geometry.coordinates = coordinates; console.log('Removed duplicate coordinates', feature); } } }); item.geoJson.features = features; original.geoJson.features = features.select(); } return item; }) .then(function (item) { return projects.ProjectManager.prototype.save.call(mgr, item); }) .then(function (saved) { var arg = { original: original, item: item, saved: saved, features: features }; return mgr.trigger("save-features", arg) .then(function () { return arg; }); }); } } }); return ProjectManager; })(); var evacuatie = evacuatie || {}; evacuatie.ProjectService = (function (moduleName) { "use strict"; function ProjectService(config, imageHelper, featureHelper, $http, $translate) { var sv = this; projects.ProjectService.call(sv, { niscode: config.niscode, url: config.url }, $http); Object.defineProperties(sv, { //_config: { value: config }, _baseUrl: { value: config.baseUrl }, _imageHelper: { value: imageHelper }, _featureHelper: { value: featureHelper }, _translate: { value: $translate } }); //console.debug("PROJECT_SERVICE", { sv: this }); } ProjectService.prototype = Object.create(projects.ProjectService.prototype, { constructor: { value: ProjectService }, _emptyGeoJson: { get: function () { return { type: "FeatureCollection", properties: {}, features: [], crs: { type: "name", properties: { name: "EPSG:XXXX" } } }; }, enumerable: true }, save: { value: function (item) { var sv = this; //console.log("SPS.SAVE", { saving: $.extend(true, {}, item), item: item, geoJson: item.geoJson }); if (item.geoJson) { if (item.geoJson.features && item.geoJson.features.length) { item.geoJson.features.forEach(function (feature) { if ("$$hashKey" in feature) { delete feature.$$hashKey; } var imgStyle = feature.properties.style.image; if (imgStyle) { if (imgStyle._base64) { delete imgStyle._base64; } if (imgStyle.resizedUrl) { delete imgStyle.resizedUrl; } if (imgStyle.transformedIconUrl) { delete imgStyle.transformedIconUrl; } if (imgStyle.scaleX != null) { delete imgStyle.scaleX; } if (imgStyle.scaleY != null) { delete imgStyle.scaleY; } if (imgStyle._imgEl) { delete imgStyle._imgEl; } } }); } } return projects.ProjectService.prototype.save.call(sv, item) .then(function(result) { if (item.geoJson && item.geoJson.features && item.geoJson.features.length) { sv._processFeatures(item.geoJson.features); } return result; }); } }, _processFeatures: { value: function (features) { var sv = this; var id = 0; var promises = features .select(function (feature) { var featureProperties = feature.properties; id++; featureProperties.id = id; var featureStyle = featureProperties.style; return Promise.resolve() .then(function () { if (featureStyle && featureStyle.stroke) { if ("measure,distance".split(",").contains(featureStyle.stroke.type)) { featureStyle.stroke.measure = 1; if (featureStyle.stroke.type === "distance") { featureStyle.stroke.arrowLocation = "end"; featureStyle.stroke.labelLocation = "end"; } else { featureStyle.stroke.arrowLocation = "start end"; featureStyle.stroke.labelLocation = "center"; } featureStyle.stroke.type = "solid"; } } return false; }) .then(function () { // only process image-features if (feature.geometry.type === "Point" && featureStyle && featureStyle.image) { var imgStyle = featureStyle.image; // make iconUrl more generic var baseUrls = ["/touchviewer/", "/touchviewer-2018/", "/mobileviewer/", "/ol-viewer/"].concat([sv._baseUrl]); baseUrls.forEach(function (baseUrl) { if (imgStyle.iconUrl) { var iconUrl = imgStyle.iconUrl.replaceAll(',', ''); if (iconUrl.startsWith(baseUrl, true)) { iconUrl = iconUrl.substring(baseUrl.length).trimStart("/"); } // catch old iconUrls 'Handlers/SymbolHandler.aspx?img={foldername}/{filename}.png' if (iconUrl.contains('/SymbolHandler.aspx')) { var imgParams = (Q.queryUrl('img', iconUrl) || '').split('/'); if (imgParams.length === 2) { var folder = imgParams[0]; var img = sv._imageHelper.getFilenameWithoutExtension(imgParams[1]).replaceAll("_", " "); iconUrl = "Handlers/PictureHandler.aspx?type=picture&module=evacuatie&action=img&identifier=" + folder + "/" + img; } else { console.warn('Converting old iconUrl failed', { iconUrl: iconUrl }); } } imgStyle.iconUrl = iconUrl; } }); if (!imgStyle.scale && imgStyle.scaleY) { imgStyle.scale = imgStyle.scaleY; delete imgStyle.scaleY; } // process resized urls if (imgStyle.iconUrl && !imgStyle.iconUrl.contains("svg=1")) { var iconUrl = imgStyle.iconUrl; return sv._imageHelper.getImageFromUrl(iconUrl) .then(function (img) { Object.defineProperty(imgStyle, "_imgEl", { value: img, writable: true, configurable: true, enumerable: false }); var transformedSize = sv._featureHelper.calcTransformedIconSize(feature); if (transformedSize) { return sv._imageHelper.resizeFixed(img, transformedSize[0], transformedSize[1]) .then(function (resizedBlob) { imgStyle.transformedIconUrl = sv._imageHelper.createUrl(resizedBlob); return img; }); } imgStyle.transformedIconUrl = imgStyle.iconUrl; return img; }) .then(function (img) { if (feature.properties && feature.properties.resizeByScale) { imgStyle.resizedUrl = imgStyle.transformedIconUrl; } else if (img.width !== imgStyle.width || img.height !== imgStyle.height) { //console.debug("PS.RESIZING", { feature: feature, iconUrl: iconUrl }); var width = imgStyle.width > 1 ? imgStyle.width : 1; var height = imgStyle.height > 1 ? imgStyle.height : 1; return sv._imageHelper.resizeFixed(img, width, height) .then(function (resizedBlob) { imgStyle.resizedUrl = sv._imageHelper.createUrl(resizedBlob); }); } return false; }) .catch(function (error) { console.error("Could not process img", { error: error, iconUrl: imgStyle.iconUrl, feature: feature }); }); } } return false; }) .then(function () { return feature; }); }); return Promise.all(promises); } }, _processItem: { value: function (item) { var sv = this; item.layerName = item.layerName || 'evacuatie-project-' + item.id; var emptyGeoJson = sv._emptyGeoJson; return Promise.resolve() .then(function () { if (item) { if (item.geoJson == null) { item.geoJson = emptyGeoJson; } if (item.geoJson.type == null) { item.geoJson.type = emptyGeoJson.type; } return Promise.resolve() .then(function () { if (item.geoJson.features == null) { item.geoJson.features = emptyGeoJson.features; return false; } else { item.geoJson.features.forEach(function (feature) { if (feature.properties && feature.properties.style && feature.properties.style.image && feature.properties.style.image.transformedIconUrl) { delete feature.properties.style.image.transformedIconUrl; } }); return sv._processFeatures(item.geoJson.features); } }) .then(function () { if (item.category) { item.categoryId = item.category.id; if (!("titleNL" in item.category)) { item.category.titleNL = item.category.title; } if (!("titleFR" in item.category)) { item.category.titleFR = item.category.titleFR || item.category.title; } } Object.keys(item.geoJson.properties) .forEach(function (key) { if (!item.hasOwnProperty(key) && item.geoJson.properties.hasOwnProperty(key)) { Object.defineProperty(item, key, { get: function () { return item.geoJson.properties[key]; }, enumerable: true }); } }); return true; }); } return false; }) .then(function () { return projects.ProjectService.prototype._processItem.call(sv, item); }); } }, getReport: { value: function (item, exportType) { var sv = this; var report = item.geoJson.features .where(function (x) { return x.geometry.type === "Point" && x.properties.style.image; }) .groupBy(function (x) { return x.properties.style.image.iconUrl; }) .select(function (x) { var identifier = decodeURIComponent(x.key.split("=").last()); var category = identifier.split("/").first(); var relUrl = x.key; if (relUrl.startsWith(sv._baseUrl)) { relUrl = relUrl.substring(sv._baseUrl.length); } var absUrl = location.protocol + "//" + location.host + (sv._baseUrl || '').trimEnd('/') + "/" + relUrl.trimStart("/") + "&niscode=" + sv._niscode + "&lang=" + sv._translate.use();// + "&imagetype=jpg"; var title = x.values.select(function (v) { return v.properties.title; }).first(); var count = x.values.length; return { category: category, title: title, count: count, url: absUrl }; }) //ignore features that were dragged directly on map .where(function (x) { return x.category !== "_temp"; }); //console.log("SP.REPORT", { item: item, lang: sv._translate.use(), report: report, service: sv }); return sv._translate(["evacuatie.Signalling", "evacuatie.BillOfMaterials", "global.Category", "evacuatie.Piece", "global.Quantity", "global.Picture"]) .then(function (translations) { var arr = [[translations["global.Picture"], translations["global.Quantity"], translations["global.Category"], translations["evacuatie.Piece"]]] .concat(report.orderByDesc(function (x) { return x.count; }) .select(function (x) { return [x.url, x.count, x.category, x.title]; })); //console.log("REPORT", { item: item, report: report, arr: arr }); exportType = exportType || "pdf"; var query = { type: exportType, title: item.title + " (" + item.code + ")" }; var exportUrl = sv._baseUrl + "/Handlers/ExportHandler.aspx?" + Q.toQuery(query); var arg = { data: arr, code: item.code, title: item.title, category: item.category != null ? item.category.title : null, startDate: item.startDate, endDate: item.endDate, description: item.description }; return sv._http.post(exportUrl, arg) .then(function (response) { var query = Q.toQuery({ file: response.data.filename, clientfile: /*item.title + "-" +*/ item.code + "-" + translations["evacuatie.BillOfMaterials"] + "." + exportType //"delete": 1 }); window.open(sv._baseUrl + "/Handlers/FileHandler.aspx?" + query); }); }); } } }); return ProjectService; })("evacuatie"); var featureInfo = featureInfo || {}; featureInfo.FeatureInfoBag = (function () { "use strict"; function FeatureInfoBag(gisFeatureService) { var fb = this; Object.defineProperties(this, { _actions: { value: {} }, _disabled: { value: false, writable: true }, _isListening: { value: false, writable: true }, _gisFeatureService: { value: gisFeatureService } }); gisFeatureService.on("selection-change", function (e, arg) { //console.log("FB.SELECTION_CHANGE", { evt: e, arg: arg, isListening: fb.isListening, actions: fb.actions, initiator: arg.initiator }); if (fb.isListening && e.initiator === "user"/* && arg.featureCount*/) { return fb.execute({ selection: arg.selection }).catch(function (error) { fb.trigger("selection-change-error", error); }); } return undefined; }); } EventHandler.injectInto(FeatureInfoBag.prototype); Object.defineProperties(FeatureInfoBag.prototype, { disabled: { get: function () { return this._disabled; }, enumerable: true }, isListening: { get: function () { return this._isListening; }, enumerable: true }, isActive: { get: function () { return !this._disabled && this._isListening; }, enumerable: true }, actions: { get: function () { return this._actions; }, enumerable: true }, registerAction: { value: function (o) { var fb = this; var layerNames = _.array(o.layerName || o.layerNames); var action = o.action; layerNames.forEach(function (key) { //console.log("FB.REGISTERING", { key: key, o: o }); if (!(key in fb.actions)) { fb.actions[key] = []; } fb.actions[key].push(action); }); } }, unregisterAction: { value: function (layerName, action) { var fb = this; _.array(layerName).forEach(function (key) { if (key in fb.actions) { if (typeof (action) !== "undefined") { fb.actions[key].remove(action); } else { delete fb.actions[key]; } } else { console.warn("Cannot unregister action for layerName '" + key + "': not found"); } }); } }, hasAction: { value: function (selection) { var fb = this; return (selection ? Promise.resolve(selection) : fb._gisFeatureService.getSelection()) .then(function (selection) { return Object.keys(selection).any(function (key) { return key in fb.actions; }); }); } }, execute: { value: function (o) { var fb = this; if (!fb.isActive) { return Promise.resolve({ selection: {}, layerNames: [], results: {}, count: 0 }); } o = o || {}; var selection = o.selection || fb._gisFeatureService.selection; var layerNames = o.layerName ? _.array(o.layerName || o.layerNames) : null; var totalFeatureCount = _.toArray(selection).sum(function (x) { return x.value.count(); }); //console.log("FB.EXECUTING", { o: o, isActive: fb.isActive, layerNames: layerNames, selection: selection, actions: fb.actions }); return ((selection && _.toArray(selection).all(function (x) { return _.isArray(x.value); })) ? Promise.resolve(selection) : fb._gisFeatureService.getSelection(layerNames)) .then(function (selection) { if (layerNames == null) { //alle geselecteerde lagen layerNames = Object.keys(selection); } return Promise.all( Object.keys(selection).innerJoin(layerNames).select(function (key) { var actionResult = { layerName: key, success: false }; if (key in fb.actions) { return Promise.all( fb.actions[key].select(function (action) { //console.log("FB.EXECUTE", { layerName: key, selection: selection[key], action: action, totalFeatureCount: totalFeatureCount }); var arg = { layerName: key, featureIds: selection[key], totalFeatureCount: totalFeatureCount }; return Promise.resolve(action(arg)) .then(function () { return fb._triggerExecute(arg); }) .then(function () { return arg; }); })) .then(function () { actionResult.success = true; return actionResult; }); //.catch(function (error) { // console.error("ERROR EXECUTING ACTION", { error: error, layerName: key, selection: selection[key] }); //}); } return actionResult; })); }) .then(function (results) { //console.log("FB.EXECUTED", { results: results, selection: selection }); return fb._triggerAfterExecute({ selection: selection, layerNames: layerNames, results: results.aggregate(function (r, x) { r[x.layerName] = x.success; return r; }, {}), count: results.count(function (x) { return x.success; }) }); }) .catch(function (error) { console.error("ERROR EXECUTING ACTIONS", { error: error, selection: selection }); }); } }, disable: { value: function () { return this.setDisabled(true); } }, enable: { value: function () { return this.setDisabled(false); } }, startListening: { value: function () { return this.setListening(true); } }, stopListening: { value: function () { return this.setListening(false); } }, setDisabled: { value: function (value) { var fb = this; if (!!value !== fb._disabled) { //console.log("FB.DISABLED:", value, this.actions); return fb._triggerChange({ disabled: value }) .then(function (arg) { if (!arg.canceled) { fb._disabled = value; } return arg; }); } return Promise.resolve(this._getChangeArg({ disabled: value })); } }, setListening: { value: function (value) { var fb = this; if (value !== fb._isListening) { //console.log("FB.LISTENING", value, this.actions); return fb._triggerChange({ isListening: value }) .then(function (arg) { if (!arg.canceled) { fb._isListening = value; } return arg; }); } return Promise.resolve(this._getChangeArg({ isListening: value })); } }, _getChangeArg: { value: function (o) { var fb = this; var disabled = ("disabled" in o) ? o.disabled : fb._disabled; var isListening = ("isListening" in o) ? o.isListening : fb._isListening; return { disabled: disabled, isListening: isListening, isActive: !disabled && isListening }; } }, _triggerChange: { value: function (o) { var fb = this; var arg = angular.extend(this._getChangeArg(o), { cancel: function () { o.canceled = true; } }); return fb.trigger(new Event("change"), arg); } }, _triggerExecute: { value: function (o) { return this.trigger(new Event("execute"), o); } }, _triggerAfterExecute: { value: function (o) { return this.trigger(new Event("after-execute"), o); } } }); //FeatureInfoBag.$inject = ["gisFeatureService"]; return FeatureInfoBag; })("featureInfo"); /* var featureInfo = featureInfo || {}; featureInfo.FeatureInfoBootstrapper = (function () { "use strict"; function FeatureInfoBootstrapper(config, featureInfoManager) { var bs = this; this.initCommands = function (commandBag, $translate) { commandBag.add([{ name: "featureinfo.ShowSelection", content: '', title: function () { return $translate("global.ShowInfo"); }, active: false }]); return Promise.resolve(bs); }; this.initFeatureInfoGis = function (featureInfoGisManager) { featureInfoManager // zoom .on("focus", function (e, arg) { return featureInfoGisManager.zoom({ items: arg.items }, arg.minScale); }); featureInfoGisManager .on("change-items", function (e, arg) { console.debug("FB.CHANGE_ITEMS", { evt: e, arg: arg }); // ToDo }); return Promise.resolve(bs); }; this.initElements = function (commandBag) { var pm = new PanelManager($(".content-container")); var moduleContainer = $("#FeatureInfoContainer"); console.log("FI.INIT_ELEMENTS", { cmdBag: commandBag, pm: pm, moduleContainer: moduleContainer }); commandBag .on("execute", moduleName + ".ShowSelection", function () { console.log("FID.SHOW", { disabled: featureInfoManager.disabled, listening: featureInfoManager.isListening }); // ignore when manager is disabled if (!featureInfoManager.disabled) { return (featureInfoManager.isListening ? featureInfoManager.stopListening() : featureInfoManager.startListening()) .then(function () { return featureInfoManager.execute(); }); } // ignore when featureInfoManager is disabled if (!featureInfoManager.disabled) { // toggle isListening return (featureInfoManager.isListening ? featureInfoManager.stopListening() : featureInfoManager.startListening()) .then(function () { //call all registered actions in featureBag for current selection return featureInfoManager.execute(); }); } return Promise.resolve(false); }); pm.container.on("closed", function (e, arg) { if (arg.element.get(0) === moduleContainer.get(0)) { featureInfoManager.loadItem(null, "list"); } }); return Promise.resolve(bs); }; this.initCss = function () { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); return Promise.resolve(bs); }; this.initData = function () { return featureInfoManager.load() .then(bs); }; } return FeatureInfoBootstrapper; })("featureinfo"); */ var featureInfo = featureInfo || {}; featureInfo.FeatureInfoController = (function () { "use strict"; function FeatureInfoController(layerTree, gisFeatureService, featureInfoBag, $timeout, $translate) { Object.defineProperties(this, { _layerTree: { value: layerTree }, _gisFeatureService: { value: gisFeatureService }, _featureInfoBag: { value: featureInfoBag }, _timeout: { value: $timeout }, _translate: { value: $translate }, _metaData: { value: {} }, totalCount: { value: 0, writable: true, enumerable: true }, errorMessage: { value: null, writable: true, enumerable: true }, items: { value: {}, writable: true, enumerable: true }, feature: { value: null, writable: true, enumerable: true }, featureId: { writable: true, enumerable: true }, documentKey: { writable: true, enumerable: true }, layer: { value: {}, writable: true, enumerable: true }, filter: { value: {}, enumerable: true }, layers: { value: [], enumerable: true }, features: { value: [], enumerable: true } }); //console.debug("FIC", { ctrl: this }); } Object.defineProperties(FeatureInfoController.prototype, { isListening: { get: function () { return this._featureInfoBag.isListening; }, enumerable: true }, enableDocuments: { get: function () { var vm = this; if (!vm.feature || !vm.layer) { return false; } return vm.layer.MetaData.DocumentKey != null; }, enumerable: true }, featureKey: { get: function () { var vm = this; if (!vm.feature || !vm.layer) { return null; } var prop = vm.layer.MetaData.DocumentKey || Object.keys(vm.layer.MetaData.Keys).first(); if (!prop) { return null; } return vm.feature[prop]; }, enumerable: true }, _reset: { value: function () { var vm = this; //console.log("FIC.INITIALIZING", { items: items, ctrl: vm }); vm.totalCount = 0; vm.feature = null; vm.featureId = null; vm.documentKey = null; vm.layer = null; vm.filter.layerName = null; } }, init: { value: function (items) { var vm = this; //console.log("FIC.INITIALIZING", { items: items, ctrl: vm }); vm._reset(); vm.items = items || {}; return vm._setLayers(items) .then(function () { return vm.load(); }); } }, handleError: { value: function (error) { var vm = this; if (error.validationMessage) { vm._timeout(function () { vm._reset(); vm.errorMessage = error.validationMessage; }); } else if (error.validationMessageTranslationKey) { vm._translate(error.validationMessageTranslationKey) .then(function (msg) { vm._timeout(function () { vm._reset(); vm.errorMessage = msg; }); }); } else { G.handleError(error); } } }, load: { value: function (filter) { var vm = this; filter = filter || vm.filter; var featureIds = vm.items[filter.layerName] || []; vm.errorMessage = null; //console.log("FIC.LOADING", { items: vm.items, filter: filter, layerName: filter.layerName, featureIds: featureIds }); return (featureIds.any() ? vm._gisFeatureService.getFeatureList({ layerName: filter.layerName, filter: "{id} IN (" + featureIds.join(",") + ")" }) : Promise.resolve([])) .then(function (features) { return features.where(function (f) { return !filter.q || _.toArray(f).any(function (x) { return x.value.toString().contains(filter.q, true); }) }); }) .then(function (features) { return vm._timeout(function () { vm.totalCount = (vm.layer && vm.layer.Code in vm.items ? vm.items[vm.layer.Code] : []).length; return vm._setFeatures(features) .catch(vm.handleError); }); }) .then(function (features) { console.log("FIC.SHOWING", { totalCount: vm.totalCount, features: features, items: vm.items, display: vm.display, ctrl: vm }); if (vm.totalCount === 0) { return vm._translate('featureinfo.MakeSelection').then(function (msg) { vm.errorMessage = msg; return features; }); } else if (vm.totalCount === 1) { return vm.show(0, "details"); } else if (vm.totalCount > 1) { return vm.show(0, "list"); } return features; }); } }, _setFeatures: { value: function (features) { Array.prototype.splice.apply(this.features, [0, this.features.length].concat(features)); return Promise.resolve(this.features); } }, _setLayers: { value: function (items) { var layerNames = Object.keys(items); var layers = this._layerTree.getSelectable().where(function (x) { return layerNames.contains(x.Code); }); Array.prototype.splice.apply(this.layers, [0, this.layers.length].concat(layers)); if (layers.length) { this.layer = layers.first(); this.filter.layerName = this.layer.Code; } return Promise.resolve(this.layers); } }, show: { value: function (index, display) { var vm = this; vm.featureId = vm.items[vm.layer.Code][index]; //console.log("FIC.SHOWING", { ctrl: vm, index: index, display: display, id: vm.featureId }); return vm._gisFeatureService.getFeatureDetails({ layerName: vm.layer.Code, filter: "{id} = " + vm.featureId }) .then(function (items) { vm.display = display || ("details"); vm.feature = items.first(); if (vm.layer) { var geom = vm.feature[vm.layer.MetaData.Geom]; delete vm.feature[vm.layer.MetaData.Geom]; vm.feature[vm.layer.MetaData.Geom] = geom; if (vm.layer.MetaData.DocumentKey) { vm.documentKey = vm.feature[vm.layer.MetaData.DocumentKey]; } else { vm.documentKey = vm.featureId; } } return vm.feature; }) .then(function (feature) { return vm._timeout() .then(function () { return feature; }); }); } }, getGeom: { value: function (features) { var vm = this; //console.log("FIC.GETTING_GEOM", { items: vm.items, features: vm.features, requested: features, display: vm.display }); if (vm.display === "details") { var geomName = vm.layer.MetaData.Geom; return Promise.resolve(vm.feature[geomName]); } features = features || vm.items[vm.layer.Code]; if (vm.display === "list") { var ids = _.array(features).select(function (x) { var index = vm.features.indexOf(x); //console.log("FIC.INDEX", { index: index, features: vm.features, items: vm.items, layerName: vm.layer.Code }); return vm.items[vm.layer.Code][index]; }); return vm._gisFeatureService.getFeatureGeoms({ layerName: vm.layer.Code, filter: "{id} IN (" + ids.join(",") + ")" }) .then(function (items) { var geoms = items.selectMany(function (x) { return _.toArray(x) }).select(function (x) { return x.value; }); //console.log("FIC.GET_GEOM", items, geoms); return geoms; }); } return Promise.resolve(); } }, isPkProperty: { value: function (columnName) { if (this.layer) { return Object.keys(this.layer.MetaData.Keys).contains(columnName); } return false; } }, isGeomProperty: { value: function (columnName) { if (this.layer) { return this.layer.MetaData.Geom === columnName; } return false; } } }); FeatureInfoController.$inject = ["layerTree", "gisFeatureService", "featureInfoBag", "$timeout", "$translate"]; return FeatureInfoController; })("featureInfo"); var featureInfo = featureInfo || {}; featureInfo.FeatureInfoDirective = (function () { "use strict"; function FeatureInfoDirective(layerTree, featureInfoBag, $timeout) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, controller: featureInfo.FeatureInfoController, controllerAs: "ctrl", scope: {}, link: function ($scope, $el, $attr, $ctrl) { //console.log("FEATUREINFO_DIRECTIVE", this, { scope: $.extend(true, {}, $scope), ctrl: $ctrl, el: $el }); var oldScope = $scope; while (!oldScope.modules && oldScope !== oldScope.$parent) { oldScope = oldScope.$parent; } //Start or stop listening and enable or disable commands function onFeatureInfoBagChange(e, arg) { //console.log("FID.STATUS_CHANGE", { evt: e, arg: arg }); if (arg.disabled) { //ToDo: decouple from scope and move to module oldScope.panels.freezePanel($(".panels-container .panel-active")); } else { //ToDo: decouple from scope and move to module oldScope.panels.unfreezePanel($(".panels-container .panel-active")); } } //Check if featureBag is active and no action has been done so far -> show default feature info function onAfterExecute(e, arg) { //console.log("FID.AFTER_EXECUTE", { arg: arg, selection: arg.selection, ctrl: $ctrl, isActive: featureInfoBag.isActive }); //if featureBag is active and not disabled if (featureInfoBag.isActive) { //if selection didn't trigger any registered action if (arg.count === 0) { //execute default featureinfo action (show feature details) var mgSelection = _.toArray(arg.selection) .where(function (x) { return layerTree.findLayer(x.key).Type === "L"; }) .toDictionary(function (x) { return x.key; }, function (x) { return x.value; }); return $timeout( function () { return $ctrl.init(mgSelection); }) .then(function (result) { if (Object.keys(mgSelection)) { $scope.showPanel(); } return result; }).catch($ctrl.handleError); } } return null; } var onSelectionChangeError = function (e, arg) { $ctrl.handleError(arg); $scope.showPanel(); }; oldScope.panels.container.on("closed", function (/*e, arg*/) { //console.log("FID.HIDE", arg); featureInfoBag.stopListening(); }); //showPanel $scope.showPanel = function () { if (!$el.is(":visible")) { oldScope.panels.show($el, "bottom", "half"); } }; //getGeom - make reference in directive so 'this'-scope inside $ctrl.getGeom does not point to $scope $scope.getGeom = function (item) { //console.log("FID.GET_GEOM", item); return $ctrl.getGeom(item || $ctrl.features); }; //Status-change (start/stop listening or disabled) featureInfoBag .on("change", onFeatureInfoBagChange) //After-execute (triggers when all registered actions have finished executing) .on("after-execute", onAfterExecute) .on("selection-change-error", onSelectionChangeError); //Deconstruct $scope.$on("$destroy", function () { featureInfoBag.off("change", onFeatureInfoBagChange); featureInfoBag.off("after-execute", onAfterExecute); featureInfoBag.off("selection-change-error", onSelectionChangeError); }); } } }; FeatureInfoDirective.$inject = ["layerTree", "featureInfoBag", "$timeout"]; return FeatureInfoDirective; })("featureinfo"); /* var featureinfo = featureinfo || {}; featureinfo.FeatureInfoManager = (function () { "use strict"; function FeatureInfoManager(gisFeatureService) { var fm = this; Object.defineProperties(this, { _actions: { value: [] }, _disabled: { value: false, writable: true }, _isListening: { value: false, writable: true }, _gisFeatureService: { value: gisFeatureService } }); gisFeatureService.on("selection-change", function (e, arg) { if (fm.isListening && e.initiator === "user") { console.log("FM.SELECTION_CHANGE", { e: e, arg: arg, fm: fm }); return fm .execute({ selection: arg.selection, deselected: arg.deselected }) .catch(function (error) { fm.trigger("selection-change-error", error); }); } return false; }); //console.log("FIM", { mgr: fm }); } EventHandler.injectInto(FeatureInfoManager.prototype); Object.defineProperties(FeatureInfoManager.prototype, { disabled: { get: function () { return this._disabled; }, enumerable: true }, isListening: { get: function () { return this._isListening; }, enumerable: true }, isActive: { get: function () { return !this._disabled && this._isListening; }, enumerable: true }, actions: { get: function () { return this._actions; }, enumerable: true }, findActions: { value: function (layerNames) { layerNames = _.array(layerNames); return this.actions.innerJoin(layerNames, function (a) { return a.key; }, function (l) { return l; }, function (a) { return a; }); } }, findSelectedLayers: { value: function (action) { return this.actions.where(function (a) { return _.isArray(a.onSelected) && a.onSelected.contains(action); }); } }, findDeselectedLayers: { value: function (action) { return this.actions.where(function (a) { return _.isArray(a.onDeselected) && a.onDeselected.contains(action); }); } }, registerAction: { value: function (o) { var fm = this; _.array(o.layerName || o.layerNames) .forEach(function (layerName) { var action = fm.actions.first(function (a) { return a.key === layerName; }); if (action == null) { action = { key: layerName }; fm.actions.push(action); } if (typeof (o.onSelected) === "function") { if (!_.isArray(action.onSelected)) { action.onSelected = []; } if (action.onSelected.contains(o.onSelected)) { // remove action to add to end of queue action.onSelected.remove(o.onSelected); } action.onSelected.push(o.onSelected); } if (typeof (o.onDeselected) === "function") { if (!_.isArray(action.onDeselected)) { action.onDeselected = []; } if (action.onDeselected.contains(o.onDeselected)) { // remove action to add to end of queue action.onDeselected.remove(o.onDeselected); } action.onDeselected.push(o.onDeselected); } }); } }, unregisterAction: { value: function (layerName, action) { var fm = this; var layerNames = _.array(layerName); var actionsToRemove = []; if (typeof (action) !== "function") { actionsToRemove = fm.findActions(layerNames); } else { fm.findActions(layerNames) .forEach(function (a) { if (_.isArray(a.onSelected)) { a.onSelected.remove(action); } if (_.isArray(a.onDeselected)) { a.onDeselected.remove(action); } if ((_.isArray(a.onSelected) && !a.onSelected.length) && (_.isArray(a.onDeselected) && !a.onDeselected.length)) { actionsToRemove.push(a); } }); } fm.actions.remove(actionsToRemove); } }, hasSelectedAction: { value: function (selection) { var fm = this; return (selection != null ? Promise.resolve(selection) : fm._gisFeatureService.getSelection()) .then(function (selection) { return fm.findActions(Object.keys(selection)).any(function (a) { return _.isArray(a.onSelected) && a.onSelected.length; }); }); } }, hasDeselectedAction: { value: function (selection) { var fm = this; return (selection != null ? Promise.resolve(selection) : fm._gisFeatureService.getSelection()) .then(function (selection) { return fm.findActions(Object.keys(selection)).any(function (a) { return _.isArray(a.onDeselected) && a.onDeselected.length; }); }); } }, handleOldSelectionActions: { value: function (oldSelection) { var fm = this; var layerNames = Object.keys(oldSelection); var actions = fm.findActions(layerNames) .where(function (a) { return _.isArray(a.onDeselected); }) .selectMany(function (a) { return a.onDeselected; }) .distinct(); var arg = { layerNames: layerNames, oldSelection: oldSelection, findFeatureIds: function (layerName) { return oldSelection[layerName]; } }; return Promise .enqueue(actions.select(function (a) { return a(arg) .then(function (result) { return fm._triggerExecute(arg) .then(function () { return { result: result, action: a }; }); }); })) .then(function (results) { return results.selectMany(function (r) { var layers = fm.findDeselectedLayers(r.action); return layers.select(function (l) { return { layerName: l, success: !!r.result }; }); }); }); } }, handleNewSelectionActions: { value: function (newSelection, oldSelection) { var fm = this; var layerNames = Object.keys(newSelection); var actions = fm.findActions(layerNames) .where(function (a) { return _.isArray(a.onSelected); }) .selectMany(function (a) { return a.onSelected; }) .distinct(); var arg = { layerNames: layerNames, oldSelection: oldSelection, selection: newSelection, totalFeatureCount: _.toArray(newSelection).sum(function (x) { return x.value.count(); }), getFeatureIds: function (layerNames) { layerNames = _.array(layerNames || []); return _.toArray(newSelection) .where(function (x) { return !layerNames.length || layerNames.contains(x.key); }) .select(function (x) { return x.value; }); } }; return Promise .enqueue(actions.select(function (a) { return a(arg) .then(function (result) { return fm._triggerExecute(arg) .then(function () { return { result: result, action: a }; }); }); })) .then(function (results) { return results.selectMany(function (r) { var layers = fm.findSelectedLayers(r.action); return layers.select(function (l) { return { layerName: l, success: !!r.result }; }); }); }); } }, execute: { value: function (o) { var fm = this; if (!fm.isActive) { return Promise.resolve({ selection: {}, oldSelection: {}, layerNames: [], results: {}, count: 0 }); } o = o || {}; var oldSelection = o.deselected || {}; var selection = o.selection || fm._gisFeatureService.selection; var layerNames = o.layerName ? _.array(o.layerName || o.layerNames) : null; return fm.handleOldSelectionActions(oldSelection) .then(function () { return fm.handleNewSelectionActions(selection, oldSelection); }) .then(function (results) { return fm._triggerAfterExecute({ selection: selection, oldSelection: oldSelection, layerNames: layerNames, results: results.aggregate(function (r, x) { r[x.layerName] = x.success; return r; }, {}), count: results.count(function (x) { return x.success; }) }); }) .catch(function (error) { console.error("Executing actions failed", { error: error, selection: selection, oldSelection: oldSelection }); }); } }, disable: { value: function () { return this.setDisabled(true); } }, enable: { value: function () { return this.setDisabled(false); } }, startListening: { value: function () { return this.setListening(true); } }, stopListening: { value: function () { return this.setListening(false); } }, setDisabled: { value: function (value) { var fm = this; if (!!value !== fm._disabled) { return fm._triggerChange({ disabled: value }) .then(function (arg) { //if (!arg.canceled) { fm._disabled = value; //} return arg; }); } return Promise.resolve(this._getChangeArg({ disabled: value })); } }, setListening: { value: function (value) { var fm = this; if (value !== fm._isListening) { return fm._triggerChange({ isListening: value }) .then(function (arg) { //if (!arg.canceled) { fm._isListening = value; //} return arg; }); } return Promise.resolve(this._getChangeArg({ isListening: value })); } }, _getChangeArg: { value: function (o) { var fm = this; var disabled = ("disabled" in o) ? o.disabled : fm._disabled; var isListening = ("isListening" in o) ? o.isListening : fm._isListening; return { disabled: disabled, isListening: isListening, isActive: !disabled && isListening }; } }, _triggerChange: { value: function (o) { var fm = this; var arg = angular.extend(this._getChangeArg(o), { cancel: function () { o.canceled = true; } }); return fm.trigger(new Event("change"), arg); } }, _triggerExecute: { value: function (o) { return this.trigger(new Event("execute"), o); } }, _triggerAfterExecute: { value: function (o) { return this.trigger(new Event("after-execute"), o); } } }); return FeatureInfoManager; })("featureinfo"); */ var files = files || {}; files.FileController = (function () { "use strict"; function FileController(config, upload, imageHelper) { //console.log("FILE_CONTROLLER", { ctrl: this, upload: upload, imageHelper: imageHelper }); var vm = this; Object.defineProperties(vm, { progress: { value: 0, writable: true, enumerable: true }, saveUrl: { value: config.defaultUploadUrl, writable: true, enumerable: true }, autoSave: { value: false, writable: true, enumerable: true }, data: { value: { files: this.files }, writable: true, enumerable: true }, onAdd: { writable: true }, onChange: { writable: true }, onRemove: { writable: true }, fileOptions: { value: { maxWidth: 1024, maxHeight: 1024 } }, _processing: { value: [] }, _upload: { value: upload }, _imageHelper: { value: imageHelper } }); } FileController.$inject = ["filesConfig", "Upload", "imageHelper"]; EventHandler.injectInto(FileController.prototype); Object.defineProperties(FileController.prototype, { files: { get: function () { return this._files; }, set: function (values) { Array.prototype.splice.apply(this._files, [0, this._files.length].concat(values)); }, enumerable: true }, processing: { get: function () { return this._processing; }, set: function (values) { Array.prototype.splice.apply(this._processing, [0, this._processing.length].concat(values)); }, enumerable: true }, init: { value: function (o) { var vm = this; var files = o.files; //console.log("FC.INIT", { ctrl: vm, files: files.select(), o: o }); if (o.saveUrl) { vm.saveUrl = o.saveUrl; } vm.autoSave = !!o.autoSave; vm.data = o.data || { files: this.files }; this.onAdd = o.onAdd; this.onChange = o.onChange; this.onRemove = o.onRemove; this.onProgress = o.onProgress; //make sure that _files is a pointer to the parent object if ("_files" in vm) { delete vm._files; } //recreate _files Object.defineProperty(vm, "_files", { value: files, configurable: true }); return Promise.resolve(vm.files); } }, addFiles: { value: function (files) { var vm = this; //console.log("FC.ADD_FILES", files); return vm.processFiles(files) .then(function (processedFiles) { vm.files.addRange(processedFiles); return processedFiles; }) .then(function (files) { return vm._onAdd({ files: files }); }) .catch(function () { console.error("FC.ERROR", { action: "addFiles", ctrl: vm, arg: arguments }); }); } }, processFiles: { value: function (files) { var vm = this; files = _.array(files); //console.log("FC.PROCESS_FILES", files); return Promise.all( files.select(function (file) { //unique filename return vm.makeFilenameUnique(file); })) .then(function (files) { //set processing files vm.processing = files; return files; }) .then(function (files) { return Promise.all( files.select(function (file) { //resize if image if (file.type.startsWith("image/", true)) { var rotateRight = false; //iPhone bug: keep orientation return vm._imageHelper.getMetaData(file) .then(function (metaData) { //console.log("FC.METADATA", { file: file, metaData: metaData }); if (metaData && metaData.Exif && metaData.Exif.Orientation) { //rotate 90° right if (metaData.Exif.Orientation === 6) { rotateRight = true; } } return file; }) .then(function (file) { //console.log("FC.RESIZING", { name: file.name, size: file.size, file: file }); return vm._imageHelper.resize(file, { maxWidth: vm.fileOptions.maxWidth, maxHeight: vm.fileOptions.maxHeight }) .then(function (resized) { if (rotateRight) { return vm._imageHelper.rotate(resized, 1); } return resized; }) .then(function (resized) { return { original: file, processed: resized }; }); }) .catch(function (err) { console.error("Resizing failed", { error: err, file: file }); return { original: file, processed: file }; }); } return { original: file }; })) .then(function (processedResults) { //console.log("RESIZED", processedResults); var files = processedResults.select(function (x) { return x.processed || x.original; }); //autoSave? if (vm.autoSave) { return vm._save(vm.saveUrl, angular.extend({}, vm.data || {}, { files: files })) .then(function ( /*savedFiles*/) { //console.log("FC.AUTO_SAVED", { files: savedFiles }); return files; }); } return files; }) .then(function (files) { //clear processing vm.processing = []; return files; }); }) .catch(function () { console.error("FC.ERROR", { action: "processFiles", ctrl: vm, arg: arguments }); }); } }, makeFilenameUnique: { value: function (file) { var vm = this; //console.log("FC.MAKING_UNIQUE", { file: file, name: file.name }); if (!vm.exists(file)) { return Promise.resolve(file); } //convert to blob to make name property writable return vm._forceBlob(file) .then(function (blob) { function removeIndexFromName(name) { var segments = name.split(" "); if (segments.length <= 1 || !parseInt(segments.last().trim("()"))) { return name; } return segments.take(segments.length - 1).join(" "); } var name = removeIndexFromName(vm._imageHelper.getFilenameWithoutExtension(blob.name)); var extension = vm._imageHelper.getExtension(blob.name); var index = 2; do { blob.name = name + " (" + index++ + ")" + extension; } while (vm.exists(blob)); return vm._copyMeta(file, blob); }) .catch(function () { console.error("FC.ERROR", { action: "makeFilenameUnique", ctrl: vm, arg: arguments }); }); } }, toggleRemoved: { value: function (file) { var vm = this; file.removed = !(!!file.removed); var index = vm.files.indexOf(file); return vm._onChange({ action: "remove", original: file, file: file, index: index }); } }, remove: { value: function (file) { var vm = this; var index = vm.files.indexOf(file); var removed = vm.files.splice(index, 1).first(); //console.log("FC.REMOVE", { index: index, removed: removed, file: file, ctrl: vm }); return vm._onRemove({ original: file, file: removed, index: index }) .then(function () { return removed; }) .catch(function () { console.error("FC.ERROR", { action: "remove", ctrl: vm, arg: arguments }); }); } }, exists: { value: function (file) { return this.files.any(function (x) { return x !== file && x.name.toLowerCase() === file.name.toLowerCase(); }); } }, rotate: { value: function (file, direction) { var vm = this; var index = vm.files.indexOf(file); return vm._forceBlob(file, file.type, file.name) .then(function (blob) { //console.log("FC.ROTATING", { file: file, blob: blob }); //rotate return vm._imageHelper.rotate(blob, direction) .then(function (rotated) { return vm._copyMeta(file, rotated); }); }) .then(function (rotated) { //console.log("FC.ROTATED", { file: file, rotated: rotated }); vm.files.splice(index, 1, rotated); //unique filename return vm.makeFilenameUnique(rotated); }) .then(function (rotated) { if (vm.autoSave) { //autoSave return vm._save(vm.saveUrl, angular.extend({}, vm.data || {}, { file: rotated })) .then(function () { return rotated; }); } return rotated; }) .then(function (rotated) { return vm._onChange({ action: "rotate", original: file, file: rotated, direction: direction, index: index }); }) .catch(function () { console.error("FC.ERROR", { action: "rotate", ctrl: vm, arg: arguments }); }); } }, _save: { value: function (url, data) { var vm = this; vm.progress = 0; console.log("FC.SAVING", { files: data.files || vm.files, ctrl: vm }); return vm._upload .upload({ url: url || vm.saveUrl, data: data }) .then(function (response) { //console.log("FC.UPLOADED_SUCCESS", response.data); return response.data; }, function (response) { console.error("FC.UPLOADED_ERROR", response); throw Error(response); }, function (evt) { var arg = { loaded: evt.loaded, total: evt.total, progress: parseInt(100.0 * evt.loaded / evt.total), data: evt.config.data }; vm.progress = arg.progress; console.log("UPLOAD_PROGRESS", arg); if (vm.onProgress) { vm.onProgress(arg); } }) .catch(function (error) { console.error("FC.ERROR", { error: error, data: data }); throw Error(error); }); } }, save: { value: function (url, o) { var vm = this; vm.saving = true; var data = o || angular.extend({}, vm.data); if (_.isArray(data)) { data = { files: data }; } console.log("FC.SAVING", { data: data, o: o }); data.files = data.files.where(function (x) { return !x.removed; }); return vm._save(url, data) .then(function (files) { console.log("FC.SAVED", { files: files }); vm.saving = false; vm.data.files = files; return files; }) .catch(function () { console.error("FC.ERROR", { action: "save", ctrl: vm, arg: arguments }); }); } }, url: { value: function (item) { if (!item.src) { item.src = this._imageHelper.createUrl(item); } return item.src; } }, _copyMeta: { value: function (source, target) { var vm = this; if ("meta" in source) { return vm._forceBlob(target) .then(function (blob) { blob.meta = source.meta; return blob; }); } return Promise.resolve(target); //ToDo: restore Exif data? //.then(function (target) { // return vm._imageHelper.restoreExif(source, target); //}); } }, _getBlob: { value: function (file) { if (this._imageHelper.isFile(file)) { return Promise.resolve(file); } else if (file.src) { return this._imageHelper.getBlobFromUrl(file.src, file.type, file.name); } else { return this._imageHelper.getBlob(file, file.type, file.name); } } }, _forceBlob: { value: function (file) { var vm = this; var promise; if (file instanceof File) { promise = vm._imageHelper.getBlobFromFile(file); } else if (file instanceof Blob) { promise = Promise.resolve(file); } else { promise = vm._getBlob(file); } return promise; } }, _onAdd: { //{ files } value: function (o) { var vm = this; var files = o.files; var promise; if (typeof (vm.onAdd) === "function") { promise = Promise.resolve(vm.onAdd(files)).then(function () { return files; }); //promise = Promise.all( // files.select(function (file) { return vm.onAdd(file); }) //); } else { promise = Promise.resolve(files); } return promise .then(function () { return vm.trigger(new Event("add", o)); }) .then(function () { return files; }); } }, _onChange: { //{ action, file, original, index } value: function (o) { var vm = this; var original = o.original; var file = o.file; //console.log("FC.ON_CHANGE", { o: o, original: original, file: file }); var promise; if (typeof (vm.onChange) === "function") { promise = Promise.resolve(vm.onChange(o)) .then(function () { return file; }); } else { promise = Promise.resolve(file); } var evt = new Event("change"); evt.action = o.action; return vm._copyMeta(original, file) .then(promise) .then(function () { return vm.trigger(evt, o); }) .then(function () { return file; }); } }, _onRemove: { //{ file, original, index } value: function (o) { var vm = this; var promise; if (typeof (vm.onRemove) === "function") { promise = Promise.resolve(vm.onRemove(o)); } else { promise = Promise.resolve(o.file); } return promise.then(function () { return vm.trigger(new Event("remove"), o); }); } } }); return FileController; })("files"); var files = files || {}; files.FilesDirective = (function (/*moduleName*/) { "use strict"; function FilesDirective(config, $timeout) { return { restrict: "EA", scope: { display: "@", format: "@", saveUrl: "@", accept: "@",//'image/*' autoSave: "=", files: "=", //addFiles: "=", downloadFiles: "=", downloadFilename: "@", onAdd: "=", onRotate: "=", onChange: "=", onRemove: "=", onProgress: "=" }, controller: files.FileController, controllerAs: "ctrl", templateUrl: function ($el, $attr) { //console.log("FD.TEMPLATE", { attr: $attr, arg: arguments }); return $attr.src || (config.baseUrl + "/content/modules/files/files.html"); }, link: function ($scope, $el, $attr, $ctrl) { //console.log(moduleName.toUpperCase() + "_DIRECTIVE", { scope: $scope, el: $el, attr: $attr, ctrl: $ctrl }); $scope.init = function (files) { //console.log("FD.INIT", { files: files.select(), scope: $scope, ctrl: $ctrl }); return $timeout() .then(function () { return $ctrl .init({ files: files, saveUrl: $scope.saveUrl, autoSave: $scope.autoSave, onAdd: $scope.onAdd, onChange: $scope.onChange, onRotate: $scope.onRotate, onRemove: $scope.onRemove, onProgress: $scope.onProgress }); }) .then(function () { return $timeout(); }) .then(function () { return files; }); } $scope.sortableOptions = { //disabled: $scope.display !== "form" }; $scope.$watch(function () { return $scope.files; }, function (newVal, oldVal) { if (newVal !== oldVal || (newVal && oldVal && !newVal.innerJoin(oldVal).length === newVal.length)) { //console.log("FD.WATCH_FILES", { newVal: newVal, oldVal: oldVal, ctrlFiles: $ctrl.files }); $scope.init(newVal); } }); if ($scope.files) { $scope.init($scope.files); } $scope.addFiles = function (files) { if ($scope.display !== 'form' || !files || !files.length) { return Promise.resolve([]); } return $ctrl.addFiles(files); }; $el.addClass("files-container"); //$scope.$on("$destroy", function () { // console.log("FD.DESTROY", { scope: $scope, args: arguments }); //}); } } } FilesDirective.$inject = ["config", "$timeout"]; return FilesDirective; })("files"); var gipod = gipod || {}; gipod.GipodDirective = (function(moduleName) { function GipodDirective(config) { return { restrict: "EA", templateUrl: function (el, attr) { return _.toArray(attr).where(function (x) { return x.key.endsWith("Directive") }).select(function (x) { return x.value; }).first() || attr.src; }, link: function ($scope, $el, $attr, $ctrl) { //console.log(moduleName.toUpperCase(), moduleName, $.extend(true, {}, $scope), $attr); var moduleScope = {}; var viewer = $scope.gis.viewer; function defaultFilter(callback) { var begin = moment().format('YYYY-MM-DD'); var end = moment().format('YYYY-MM-DD'); //var end = moment().add(2, 'months').format('YYYY-MM-DD'); var overlay = $el.spinnerOverlay(); //initial filter G.ajax({ url: config.gipodApiBaseUrl + '/georest/handhaving/FindGlobalInnameIdsByCriteria', data: { Van: begin, Tot: end, ZoekGrondWerken: true, ZoekWerken: true, ZoekEvenementInname: true, ZoekEvenementen: true, SubManifestatieType: 0, SubWerkOpdrachtAard: 0, ToonAlleInnameStatussen: true, InnameStatus: 0, Niscode: config.niscode }, success: function (o) { var defaultFilterCallback = function () { if (callback) callback(); }; var innameIds = o.Data; if (innameIds.length > 0) { $('#Info').html('Filter actief (' + innameIds.length + ' inname(s) gefilterd)'); viewer.gisviewer("filter", { filter: { "Hinder": "hoofd_inname_id in ('" + innameIds.join("', '") + "')", "Werken": "inname_id in ('" + innameIds.join("', '") + "')", "Grondwerken": "inname_id in ('" + innameIds.join("', '") + "')", "EvenementInname": "inname_id in ('" + innameIds.join("', '") + "')", "omleidingen_": "hoofd_inname_id in ('" + innameIds.join("', '") + "')" } }, defaultFilterCallback); } else { viewer.gisviewer("filter", { filter: { "Hinder": "hoofd_inname_id in ('0')", "Werken": "inname_id in ('0')", "Grondwerken": "inname_id in ('0')", "EvenementInname": "inname_id in ('0')", "omleidingen_": "hoofd_inname_id in ('0')" } }, defaultFilterCallback); } }, type: "POST", always: function () { overlay.hide(); } }); } $scope.modules[moduleName] = $scope.modules[moduleName] || {}; $scope.modules[moduleName].root = $.extend(moduleScope, { defaultFilter: function (callback) { defaultFilter(callback); }, css: $.loadCss("Content/modules/gipod/gipod.css") }); } } } GipodDirective.$inject = ["config"]; return GipodDirective; })("gipod"); var gipod = gipod || {}; gipod.GipodDocumentenDirective = (function (moduleName) { function GipodDocumentenDirective(config, $http) { return { restrict: "EA", templateUrl: function (el, attr) { return _.toArray(attr).where(function (x) { return x.key.endsWith("Directive") }).select(function (x) { return x.value; }).first() || attr.src; }, link: function ($scope, $el, $attr) { //console.log(moduleName.toUpperCase(), moduleName, $.extend(true, {}, $scope), $attr); var moduleScope = {}; $scope.modules[moduleName].GipodDocumenten = $.extend(moduleScope, { documenten: [], innameId: 0, css: $.loadCss("Content/modules/gipod/gipod.css"), loadDocumentenForInname: function (innameId) { var me = this; me.innameId = innameId; return Promise.resolve() .then(function () { if (innameId) { var overlay = $el.spinnerOverlay(); return new Promise(function (resolve) { G.ajax({ action: 'FindAllDocumentenForInname', data: { innameId: innameId, niscode: config.niscode }, controller: moduleName, success: function (o) { resolve((o || []).select(function (document) { return { name: document.DocumentName, src: config.baseUrl + "/Handlers/GipodBijlageHandler.ashx?id=" + document.HandelingBijlageId + "&preview=false", document: document }; })); }, always: function () { overlay.hide(); }, type: "GET" }); }); } return null; }) .then(function (documenten) { me.documenten = documenten || []; return documenten; }); }, onAdd(files) { }, onChange(o) { if (o.action === 'remove') { $scope.modules[moduleName].GipodDocumenten.documenten.remove(o.file); } }, onRemove(o) { } }); } } } GipodDocumentenDirective.$inject = ["config", "$http"]; return GipodDocumentenDirective; })("gipod"); var gipod = gipod || {}; gipod.GipodFilterDirective = (function (moduleName) { function GipodFilterDirective(config, signalisatieConfig, commandBag, $translate) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, link: function ($scope, $el, $attr) { //console.log(moduleName.toUpperCase(), moduleName, $.extend(true, {}, $scope), $attr); var moduleScope = {}; var overlay = null; var viewer = $scope.gis.viewer; var overlayFunc = function () { $scope.panels.setMode('right', 'half'); overlay.hide(); }; moment.locale("nl-be"); //Value: A valid full-date as defined in [RFC 3339], with the additional qualification that the year component is four or more digits representing a number greater than 0. $('#Van').val(moment().tz("Europe/Brussels").format('YYYY-MM-DD')); $('#Tot').val(moment().tz("Europe/Brussels").format('YYYY-MM-DD')); //$('#Tot').val(moment().add(2, 'months').format('YYYY-MM-DD')); $('#Van').change(function () { $('#Tot').val($('#Van').val()); }); $('#btnVandaag').on('click', function () { $('#Van').val(moment().tz("Europe/Brussels").format('YYYY-MM-DD')); $('#Tot').val(moment().tz("Europe/Brussels").format('YYYY-MM-DD')); }); $('#btnWeek').on('click', function () { var begin = moment().tz("Europe/Brussels").startOf('week').add(1, 'days').format('YYYY-MM-DD'); var end = moment().tz("Europe/Brussels").startOf('week').add(5, 'days').format('YYYY-MM-DD'); // $('#Van').val(begin); $('#Tot').val(end); }); $('#btnMaand').on('click', function () { var begin = moment().tz("Europe/Brussels").format("YYYY-MM-01"); var end = moment().tz("Europe/Brussels").format("YYYY-MM-") + moment().daysInMonth(); $('#Van').val(begin); $('#Tot').val(end); }); $scope.modules[moduleName].filter = $.extend(moduleScope, { config: { layers: { hinder: signalisatieConfig.layers.HINDER, werken: signalisatieConfig.layers.WERKEN, grondwerken: signalisatieConfig.layers.GRONDWERKEN, evenementInname: signalisatieConfig.layers.EVENEMENT_INNAME, omleidingen_: signalisatieConfig.layers.OMLEIDINGEN } }, clearFilter: function () { overlay = $el.spinnerOverlay(); if (config.application === "raadplegen") { $scope.modules[moduleName].root.defaultFilter(overlayFunc); } else { viewer.gisviewer("filter", { filter: { [signalisatieConfig.layers.HINDER]: "", [signalisatieConfig.layers.WERKEN]: "", [signalisatieConfig.layers.GRONDWERKEN]: "", [signalisatieConfig.layers.EVENEMENT_INNAME]: "", [signalisatieConfig.layers.OMLEIDINGEN]: "", "Evenementen": "" } }, overlayFunc); } $('#Info').html('Filter inactief'); }, filter: function (o) { overlay = $el.spinnerOverlay(); var dtVan = moment($('#Van').val(), 'YYYY-MM-DD'); var dtTot = moment($('#Tot').val(), 'YYYY-MM-DD'); var isNeteland = config.netelandNiscodes.contains(config.niscode); let data = { Van: dtVan.format("YYYY-MM-DD"), Tot: dtTot.format("YYYY-MM-DD"), ZoekEvenementen: $('#cbEvenementen').is(':checked'), ZoekGrondWerken: $('#cbGrondwerk').is(':checked'), ZoekWerken: $('#cbWerk').is(':checked'), ZoekEvenementInname: $('#cbEvenementInnames').is(':checked'), SubManifestatieType: 0, SubWerkOpdrachtAard: 0, ToonAlleInnameStatussen: ($('input[name="innamestatus"]:checked')[0])?.value, InnameStatus: 0, Niscode: config.niscode, Niscodes: isNeteland ? config.netelandNiscodes : [config.niscode], } G.ajax({ url: config.gipodApiBaseUrl + '/georest/handhaving/FindGlobalInnameIdsByCriteria', data: data, success: function (o) { viewer.gisviewer("clearSelection"); if (o.Data.length > 0) { $scope.modules[moduleName].filter.data = o.Data; $('#Info').html('Filter actief (' + o.Data.length + ' inname(s) gefilterd)'); viewer.gisviewer("filter", { filter: { [signalisatieConfig.layers.HINDER]: "hoofd_inname_id in ('" + o.Data.join("', '") + "')", [signalisatieConfig.layers.WERKEN]: "inname_id in ('" + o.Data.join("', '") + "')", [signalisatieConfig.layers.GRONDWERKEN]: "inname_id in ('" + o.Data.join("', '") + "')", [signalisatieConfig.layers.EVENEMENT_INNAME]: "inname_id in ('" + o.Data.join("', '") + "')", [signalisatieConfig.layers.OMLEIDINGEN]: "hoofd_inname_id in ('" + o.Data.join("', '") + "')" } }, overlayFunc); } else { $('#Info').html('Filter actief (' + o.Data.length + ' inname(s) gefilterd)'); viewer.gisviewer("filter", { filter: { "Hinder": "hoofd_inname_id in ('0')", "Werken": "inname_id in ('0')", "Grondwerken": "inname_id in ('0')", "EvenementInname": "inname_id in ('0')", "omleidingen_": "hoofd_inname_id in ('0')" } }, overlayFunc); } if (data.ZoekEvenementen) { G.ajax({ url: config.gipodApiBaseUrl + '/georest/evenement/GetEvenementen', data: data, success: function (o) { if (o.Data.length) { viewer.gisviewer("filter", { filter: { ["Evenementen"]: "evenement_id in ('" + o.Data.map(x => x.Id).join("', '") + "')" } }, overlayFunc); } else { viewer.gisviewer("filter", { filter: { "Evenementen": "evenement_id in ('0')", } }, overlayFunc); } }, type: "POST" }); } else { viewer.gisviewer("filter", { filter: { "Evenementen": "evenement_id in ('0')", } }, overlayFunc); } }, type: "POST", afterError: overlayFunc }); } }); //command commandBag.on("execute", "ToggleGipodFilter", function () { $scope.panels.show($el, 'right'); }); signalisatieConfig.on("gipodLoad", function (e, args) { $('#Status').append($('
' + header + ''; $compile(html)($scope).appendTo($el); } } ThSort.$inject = ["$compile"]; return ThSort; })(); var golfgis = golfgis || {}; golfgis.GolfGisDirective = (function (moduleName) { function GolfGisDirective(config) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, link: function ($scope, $el, $attr) { console.log(moduleName.toUpperCase(), $.extend(true, {}, $scope), $el, $attr); $("body").addClass("golfgis"); var viewer = $scope.gis.viewer; var handler = new window.EntityHandlers.GolfGis.EmsMapping((config.baseUrl ? (config.baseUrl + "/") : "") + "GolfGis"); function getLayerFilters(emsIds, callback) { handler.List({ EmsIds: emsIds }, function (items) { callback( items .groupBy(function (x) { return x.Laagnaam; }) .select(function (x) { return x.key + ":" + x.values.select(function (y) { return y.ObjectId; }).join(","); }) .join("|") ); }); } function toQuery(v, filter) { return _.toArray(v) .select(function (x) { switch (x.key) { case "ggselect": return { key: "select", value: filter }; case "ggfilter": return { key: "filter", value: filter }; default: return x; } }) .aggregate(function (r, x) { return r + (r ? "&" : "") + x.key + "=" + encodeURIComponent(x.value); }, ""); } var infoEl = $el.find(".ems-info"); var golfScope = { config: { emsUrl: config.emsUrl//"https://api.emsgolf.eu/golfgis/object.php?niscode={niscode}&gis_identifier={id}" }, //css: $.loadCss(["Content/modules/golfgis/golfgis.css", "Handlers/CustomLoader.aspx?file=golfgis/golfgis.css"]), hashChangeEvents: { "ggselect": [ function (v, callback) { var ids = v["ggselect"].split(","); //console.log("GG.SELECT", ids); getLayerFilters(ids, function (filter) { var newQuery = toQuery(v, filter); console.log("GG.SELECT", filter); location.href = "#" + newQuery; if (callback) callback(); }); } ], "ggfilter": [ function (v, callback) { var ids = v["ggfilter"].split(","); getLayerFilters(ids, function (filter) { var newQuery = toQuery(v, filter); console.log("GG.FILTER", filter); location.href = "#" + newQuery; if (callback) callback(); }); } ] }, showSelectionData: function () { viewer.gisviewer("getSelectedItems", { propertiesBitmask: 1 }, function (selection) { var layers = $scope.gis.layers.getSelectable() .where(function (x) { return x.IsVisible && x.Type === "L"; }) .select(function (x) { return x.Code; }); var ids = _.toArray(selection) .where(function (x) { return layers.contains(x.key); }) .selectMany(function (x) { return x.value; }) .selectMany(function (x) { return _.toArray(x).select(function (x) { return x.value; }) }); console.log("GG.SELECTION", selection, ids); var iframe = infoEl.find(".content iframe:first"); if (ids.any()) { var url = golfScope.config.emsUrl .replace("{niscode}", config.niscode) .replace("{id}", ids.join()); iframe.attr("src", url); $scope.panels.show(infoEl, "bottom", "half"); //$http.get("Handlers/Proxy.aspx?u=" + encodeURIComponent(golfScope.config.emsUrl // .replace("{niscode}", config.niscode) // .replace("{id}", ids.join())) + "&ct=" + encodeURIComponent("text/html")) // .then(function (response) { // console.log("RESPONSE", response); // if (response.data) { // infoEl.find(".content:first").html(response.data); // $scope.panels.show(infoEl, "bottom", "half"); // } // }); } else { $scope.modules.featureinfo.showSelectionData(); } }); }, gisEvents: { mapload: function () { //viewer.gisviewer("showLayer", { layerName: "bingmaps.Aerial" }, function () { viewer.gisviewer("expandGroup", { groupName: "basegroup" }, function () { //viewer.gisviewer("refreshLegend"); }); //}); }, selectionchanged: function () { return;//ShowGGSelection is tijdelijk afgezet /* if (infoEl.is(":visible")) { $.delay("GET_EMS_INFO", function () { golfScope.showSelectionData(); }, 250); } */ } } }; $scope.modules["golfgis"] = golfScope; $scope .addHashchangeEvents(golfScope.hashChangeEvents) .gis .addEvents(golfScope.gisEvents); } } } GolfGisDirective.$inject = ["config"]; return GolfGisDirective; })("golfgis"); var home = home || {}; home.Bootstrapper = (function (moduleName) { "use strict"; function Bootstrapper(config, homeManager) { var bs = this; this.initData = function (roles) { //console.log("HOME.INIT_DATA", { roles: roles, mgr: homeManager }); function getNiscodeItems() { var niscodeItems = roles .where(function (x) { return x.roleName.startsWith("niscode_"); }) .orderBy(function (x) { return x.display || x.roleName.substr(8); }); niscodeItems.each(function (niscodeItem) { var niscode = niscodeItem.roleName.substr(8); niscodeItem.display = niscodeItem.displayName || niscode; niscodeItem.niscode = niscode; }); return niscodeItems; } function getModuleItems(/*niscodeItem*/) { var moduleItems = roles .where(function (x) { return x.roleName.startsWith("module_") && x.roleName !== 'module_global'; }); moduleItems.each(function (moduleItem) { var application = moduleItem.roleName.substr(7); moduleItem.application = application; }); return moduleItems; } return Promise.resolve() .then(function () { var niscodeItems = getNiscodeItems(); return homeManager.setNiscodeItems(niscodeItems); }) .then(function () { var niscodeItem = homeManager.niscodeItems.where(function (x) { return x.niscode === config.niscode; }).first() || homeManager.niscodeItems.first(); return homeManager.setNiscodeItem(niscodeItem) .then(function () { var moduleItems = getModuleItems(niscodeItem); return homeManager.setModuleItems(moduleItems); }); }) .then(function () { homeManager .on("change-niscode-items", function (e, arg) { var niscodeItem = arg.items.where(function (x) { return x.niscode === config.niscode; }).first() || arg.items.first(); homeManager.setNiscodeItem(niscodeItem); }) .on("change-niscode-item", function (e, arg) { if (config.application === "home") { var query = Q.query(); query["niscode"] = arg.item.niscode; var url = location.pathname + "?" + Q.toQuery(query); //console.log("change-niscode", { evt: e, arg: arg, url: url }); location.href = url; } }) .on("change-module-item", function (e, arg) { if (config.application === "home") { var query = Q.query(); query["app"] = arg.item.application; var url = location.pathname + "?" + Q.toQuery(query); //console.log("change-niscode", { evt: e, arg: arg, url: url }); location.href = url; } }); return bs; }); }; this.initCommands = function (commandBag, securityManager, $translate) { if (securityManager.hasMultipleModules) { commandBag.add({ name: "Home", title: function () { return $translate("home.Home"); }, content: '', callback: function () { var url = config.baseUrl + "?app=home"; var niscode = Q.query("niscode"); if (niscode && niscode !== "undefined" && niscode !== "null") { url += "&niscode=" + niscode; } window.location.href = url; } }); } return Promise.resolve(bs); }; this.initCss = function () { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); return Promise.resolve(bs); }; this.initPanels = function (niscode, $translate) { var panelManager = new PanelManager($(".content-container")); panelManager.container .on("shown", function (/*e, arg*/) { //console.log("SHOW_HOME", { evt: e, arg: arg }); if (!niscode) { $translate("home.NoNiscodeSelected") .then(function (msg) { homeManager.errorMessage = msg; }); } else if (homeManager.niscodeItems.length === 0) { $translate("home.NoAccessToAnyNiscode") .then(function (msg) { homeManager.errorMessage = msg; }); } else if (homeManager.moduleItems.length === 0) { $translate("home.NoAccessToAnyModule") .then(function (msg) { homeManager.errorMessage = msg; }); } else if (config.errorMessage) { homeManager.errorMessage = config.errorMessage; } }); return Promise.resolve(bs); }; this.initElements = function () { if (config.application === moduleName) { var pm = new PanelManager($(".content-container")); var moduleContainer = $("#HomeContainer"); pm.show(moduleContainer, "bottom", "full"); } }; this.initToolbar = function (toolbarService) { if (config.application === moduleName) { toolbarService.buildTree([ "security.User" ]); } return Promise.resolve(bs); }; } return Bootstrapper; })("home"); var home = home || {}; home.HomeController = (function (/*moduleName*/) { "use strict"; function HomeController(config, manager) { Object.defineProperties(this, { _manager: { value: manager }, version: { value: config.version, enumerable: true }, config: { value: config } }); } Object.defineProperties(HomeController.prototype, { errorMessage: { get: function () { return this._manager.errorMessage; }, enumerable: true }, niscodeItem: { get: function () { return this._manager.niscodeItem; }, set: function (value) { this._manager._niscodeItem = value; }, enumerable: true }, niscodeItems: { get: function () { return this._manager.niscodeItems; }, enumerable: true }, moduleItems: { get: function () { var ctrl = this; return ctrl._manager.moduleItems .map(function (item) { item.href = item.application != 'Gipod' ? '?app=' + (item.application + (ctrl.niscodeItem ? '&niscode=' + ctrl.niscodeItem.niscode : '')) : ctrl.config.gipodApiBaseUrl + '/index.aspx'; item.click = function ($event) { if (item.application != 'Gipod') { $event.preventDefault(); ctrl.setModuleItem(item); } } return item; }); }, enumerable: true }, setNiscodeItem: { value: function (niscodeItem) { return this._manager.setNiscodeItem(niscodeItem); } }, setModuleItem: { value: function (moduleItem) { return this._manager.setModuleItem(moduleItem); } } }); return HomeController; })("home"); var home = home || {}; home.HomeDirective = (function (moduleName) { function HomeDirective(config) { return { restrict: "EA", template: '
', link: function ($scope) { $scope.version = config.version; } }; } return HomeDirective; })("home"); var home = home || {}; home.HomeManager = (function (/*moduleName*/) { "use strict"; function HomeManager() { Object.defineProperties(this, { _errorMessage: { value: null, writable: true }, _niscodeItem: { value: null, writable: true }, _niscodeItems: { value: [], writable: true }, _moduleItems: { value: [], writable: true } }); //console.log("HOME_MANAGER", { mgr: this }); } EventHandler.injectInto(HomeManager.prototype); Object.defineProperties(HomeManager.prototype, { errorMessage: { get: function () { return this._errorMessage; }, set: function (value) { this._errorMessage = value; }, enumerable: true }, niscodeItem: { get: function () { return this._niscodeItem; }, enumerable: true }, niscodeItems: { get: function () { return this._niscodeItems; }, enumerable: true }, moduleItems: { get: function () { return this._moduleItems; }, enumerable: true }, setNiscodeItem: { value: function (niscodeItem) { var oldItem = this._niscodeItem; this._niscodeItem = niscodeItem; var arg = { oldItem: oldItem, item: niscodeItem }; return this.trigger("change-niscode-item", arg) .then(function () { return arg; }); } }, setNiscodeItems: { value: function (niscodeItems) { var oldItems = this._niscodeItems; this._niscodeItems = niscodeItems; var arg = { oldItems: oldItems, items: niscodeItems }; return this.trigger("change-niscode-items", arg) .then(function () { return arg; }); } }, setModuleItem: { value: function (moduleItem) { var arg = { item: moduleItem }; return this.trigger("change-module-item", arg) .then(function () { return arg; }); } }, setModuleItems: { value: function (moduleItems) { var oldItems = this._moduleItems; this._moduleItems = moduleItems; var arg = { oldItems: oldItems, items: moduleItems }; return this.trigger("change-module-items", arg) .then(function () { return arg; }); } } }); return HomeManager; })("home"); var icons = icons || {}; icons.IconsDirective = (function (moduleName) { "use strict"; function IconsDirective($timeout) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, scope: {}, link: function ($scope, $el) { Object.defineProperties($scope, { data: { value: { items: null, filteredItems: null, filter: null } }, filterItems: { value: function () { $scope.data.filteredItems = $scope.data.items.where(function (x) { return !$scope.data.filter || x.toLowerCase().contains($scope.data.filter.toLowerCase()); }); } }, resetFilter: { value: function () { $scope.data.filter = null; $scope.filterItems(); } } }); $scope.$parent.panels.show($el, "bottom", "full"); var overlay = $el.spinnerOverlay(); G.get({ controller: "Index", action: "GetAllGlyphiconClassNames", success: function (items) { $timeout(function () { $scope.data.items = items; $scope.filterItems(); }); }, always: function () { overlay.hide(); } }); } } } IconsDirective.$inject = ["$timeout"]; return IconsDirective; })("icons"); var languages = languages || {}; languages.LanguageDirective = (function (moduleName) { function LanguageDirective(config, commandBag) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, link: function ($scope, $el) { //console.log(moduleName.toUpperCase(), this, $.extend(true, {}, $scope)); $scope.modules[moduleName] = { list: { items: [ { code: "nl" }, { code: "fr" } ] }, el: $el, show: function () { $scope.panels.show($el, "left"); }, hide: function () { $scope.panels.hide($el); }, change: function (lang) { //$scope.lang.change(lang); //$scope.panels.hide($el); var queryParameters = Q.query(); queryParameters["lang"] = lang; window.location = config.baseUrl + "?" + _.toArray(queryParameters).select(function (x) { return x.key + "=" + encodeURIComponent(x.value); }).join("&"); } }; //command commandBag.on("execute", "ChooseLanguage", function () { $scope.modules[moduleName].show(); }); } } } LanguageDirective.$inject = ["config", "commandBag"]; return LanguageDirective; })("languages"); //var loadend = loadend || {}; //loadend.LoadendDirective = (function (moduleName) { // "use strict"; // function LoadendDirective(config) { // return { // restrict: "EA", // templateUrl: ModuleManager.templateUrl, // link: function ($scope) { // if (config.application !== "home") { // var finalFunc = function () { // console.log("LOAD ENDED"); // G.setup.async = null; // $scope.$root.$emit("application.loadend"); // }; // if (config.sessionId) { // $scope.gis.addEvents({ // mapload: function () { // setTimeout(finalFunc, 500); // } // }, moduleName); // } else { // setTimeout(finalFunc, 500); // } // } // } // } // } // LoadendDirective.$inject = ["config"]; // return LoadendDirective; //})("loadend"); var logon = logon || {}; logon.LogonController = (function (moduleName) { "use strict"; function LogonController() { this.username = null; this.password = null; } Object.defineProperties(LogonController.prototype, { login: { value: function () { } }, logout: { value: function () { } } }); return LogonController; })("logon"); var logon = logon || {}; logon.LogonDirective = (function (moduleName) { "use strict"; function LogonDirective(config, $translate, panelHelper, commandBag) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, scope: {}, link: function ($scope, $el) { Object.defineProperties($scope, { version: { value: config.version }, data: { value: { Username: null, Password: null, StayLoggedIn: null, Message: null } }, resetUsername: { value: function () { $scope.data.Username = ""; } }, resetPassword: { value: function () { $scope.data.Password = ""; } }, login: { value: function () { if (!$scope.data.Username) { $translate('global.UsernameIsRequired').then(function (msg) { $scope.data.Message = msg; }); $el.find(".username").focus(); return; } if (!$scope.data.Password) { $translate('global.PasswordIsRequired').then(function (msg) { $scope.data.Message = msg; }); $el.find(".password").focus(); return; } var overlay = $el.spinnerOverlay(); G.post({ controller: "Logon", action: "Login", parameters: $scope.data, success: function (arg) { if (arg.success) { location.reload(); } else { $scope.$apply(function () { $scope.data.Message = arg.message; }); overlay.hide(); } }, afterError: function () { overlay.hide(); } }); } }, logout: { value: function () { var overlay = $el.spinnerOverlay(); G.post({ controller: "Logon", action: "Logout", success: function () { var uri = parseUri(window.location.href); var url = uri.protocol + "://" + uri.authority + uri.directory; if (uri.queryKey) { delete uri.queryKey.niscode; delete uri.queryKey.app; var queryParams = __objectextensions.toArray(uri.queryKey); if (queryParams.length) { url += "?" + queryParams.select(function(x) { return x.key + '=' + x.value; }).join("&"); } } window.location = url; //location.reload(); }, always: function () { overlay.hide(); } }); } } }); if (config.application === moduleName) { $scope.errorMessage = config.errorMessage; panelHelper.show({ el: $el, panel: "bottom", mode: "full" }); $el.find(".username").focus(); } else { //command commandBag.on("execute", "Logout", function () { $scope.logout(); }); } } } } LogonDirective.$inject = ["config", "$translate", "panelHelper", "commandBag"]; return LogonDirective; })("logon"); var manuals = manuals || {}; manuals.ManualController = (function (/*moduleName*/) { "use strict"; function ManualController(manager) { Object.defineProperties(this, { items: { get: function () { return manager.items; }, enumerable: true } }); this.getUrl = function getUrl(item) { return manager.getUrl(item.filename); }; } return ManualController; })("manuals"); var manuals = manuals || {}; manuals.ManualManager = (function (/*moduleName*/) { "use strict"; function ManualManager(service) { var mgr = this; mgr.items = []; mgr.list = function (modules, lang) { return service.list(modules, lang) .then(function (items) { mgr.items = items; return items; }); } mgr.getUrl = function (filename) { return service.getUrl(filename); }; } return ManualManager; })("manuals"); var manuals = manuals || {}; manuals.ManualService = (function (/*moduleName*/) { "use strict"; function ManualService(config, $http) { this.list = function (modules, lang) { var url = new URL(config.listUrl, location.origin); url.searchParams.set("modules", modules.join(',')); url.searchParams.set("lang", lang || ""); return $http.get(url.toString()) .then(function (response) { return response.data; }); } this.getUrl = function (filename) { var url = new URL(config.detailsUrl, location.origin); url.searchParams.set("file", filename); return url.toString(); }; } return ManualService; })("manuals"); var measure = measure || {}; measure.measureComponent = (function () { function MeasureViewModel() { Object.defineProperties(this, { items: { value: [], writable: true }, onAddDistance: { writable: true }, onAddArea: { writable: true }, onReset: { writable: true } }); } Object.defineProperties(MeasureViewModel.prototype, { handleAddItem: { value: function (e) { return this.onAddItem({ event: e }); } }, handleReset: { value: function (e) { return this.onReset({ event: e }); } } }); function measureComponent(templateUrl) { return { controller: MeasureViewModel, bindings: { items: "<", onAddDistance: "&", onAddArea: "&", onCopy: "&", onReset: "&" }, templateUrl: ["config", function (config) { return config.baseUrl + "/" + templateUrl + "?v=" + config.version; }] }; } return measureComponent; })("measure"); var measure = measure || {}; measure.MeasureController = (function () { var _viewer; function MeasureController(gisViewer) { _viewer = gisViewer; } Object.defineProperties(MeasureController.prototype, { }); return MeasureController; })(); var measure = measure || {}; measure.MeasureDirective = (function (moduleName) { function MeasureDirective(commandBag, gisViewer, geoHelper, panelHelper) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, link: function ($scope, $el) { //console.log(moduleName.toUpperCase() + "_MEASURE", $.extend(true, {}, $scope)); var viewer = $scope.gis.viewer; $scope.modules["measure"] = { el: $el, featureStyle: { color: "#1e73be", fillColor: "#1e90ff", stroke: { width: 5 }, label: { color: "#333333", fontSize: "20px", baseline: "bottom" } } }; var moduleScope = $scope.modules.measure; $scope.gis .createVectorScope({ layer: { Code: "measure", Title: $scope.lang.translate("Measure", moduleName), ParentCode: null, position: 0, ShowInLegend: false }, featureStyle: moduleScope.featureStyle, target: $scope.modules.measure }); var vectorScope = moduleScope.vector; function formatNumber(n) { return (Math.round(n * 100) / 100).toLocaleString("en-US", { minimumFractionDigits: 2 }); } var tempFeatures = null; var measuring = Promise.debounce(function (e, arg) { if (!$el.is(":visible") || !$el.hasClass("panel-active")) { return; } vectorScope.feature.remove(tempFeatures, function () { viewer.gisviewer("getScale", function (scale) { var geometry = arg.geom.geoJson; var label = ""; if (arg.area != null) { geometry = { type: "Point", coordinates: geoHelper.getCenter(arg.geom.geoJson) }; label = moduleScope.getAreaText(arg.area); } else if (arg.length != null) { label = moduleScope.getDistanceText(arg.length); } tempFeatures = [{ geometry: geometry, properties: { style: { label: { text: label, fontSize: scale / 100 } } } }]; vectorScope.feature.add({ features: tempFeatures }); }); }); }, 50); var onAddVertex = Promise.debounce(function (e, arg) { //console.log("MD.ADD_VERTEX", { el: $el, scope: $scope }); if (!$el.is(":visible") || !$el.hasClass("panel-active")) { return; } if (arg.type === "LineString" && arg.coordinates.length >= 2) { gisViewer.finishDigitizing(); } }, 250); gisViewer .on("digitizing", measuring) .on("add-vertex", onAddVertex); //command var lastMode = "full"; //window.innerWidth < 1280 ? "half" : "full"; commandBag.on("execute", "measure.Measure", function () { return panelHelper .show({ el: $el, panel: "right", mode: lastMode }); }); panelHelper.on("resize", function (e, arg) { if (arg && arg.panel === "right" && $el.is(":visible")) { lastMode = arg.mode; } }); $.extend(true, moduleScope, { gisEvents: { selectionchanged: function (e, arg) { if ($scope.modules.vectorfeatures && $scope.modules.vectorfeatures.styling && vectorScope.layer.item) { arg.getSelectedItems({ layer: vectorScope.layer.item }, function (selection) { if (selection[vectorScope.layer.item.Code]) { moduleScope.openStyling(selection[vectorScope.layer.item.Code]); } }); } } }, getDistanceText: function (number) { var km = 1000, cm = 0.01; var s = formatNumber(number) + "m"; if (number < 1) { s = formatNumber(number / cm) + "cm"; } else if (number > 1000) { s = formatNumber(number / km) + "km"; } //console.log("M.DISTANCE", number, s); return "" + s; }, getAreaText: function (number) { var sqKm = 1000000, ha = 10000; //, a = 100; var s = formatNumber(number) + "m²"; if (number >= 10000000) { s = formatNumber(number / sqKm) + "km²"; } else if (number >= 100000) { s = formatNumber(number / ha) + "ha"; //} else if (number >= 1000) { // s = formatNumber(number / a) + "a"; } return "" + s; } }); $scope.gis.addEvents(moduleScope.gisEvents, moduleName); function getSingleGeoJson(geom, callback) { $scope.gis.helpers.geoHelper.getWKT(geom, function (wkt) { $scope.gis.helpers.geoHandler.getSingle(wkt, function (wkt) { $scope.gis.helpers.geoHelper.getGeometryObject(wkt, function (geom) { callback(geom); }); }); }); } $.extend(true, moduleScope, { setColor: function (o, callback) { if (o.color) moduleScope.featureStyle.color = o.color; if (o.fillColor) moduleScope.featureStyle.fillColor = o.fillColor; moduleScope.update(callback); }, update: function (callback) { if (vectorScope.feature.list.items.any()) { vectorScope.feature.list.items.each(function (x) { $.extend(true, x.properties.style, moduleScope.featureStyle); }); vectorScope.feature.update({ features: vectorScope.feature.list.items }, function () { viewer.gisviewer("refreshMap", callback); }); } }, measureDistance: function (geom, callback) { $scope.gis.helpers.geoHandler.getLength(geom.wkt, function (length) { var arg = { geom: geom, distance: length }; if (callback) callback(arg); }); }, addDistance: function (o, callback) { var length = o.distance; getSingleGeoJson(o.geom, function (geom) { viewer.gisviewer("getScale", function (scale) { var feature = { geometry: geom, properties: { style: { label: { text: moduleScope.getDistanceText(length), /*scale: scale * 1*/ fontSize: scale / 100 } } } }; vectorScope.feature.remove(tempFeatures, function () { vectorScope.feature.add({ features: [feature] }, function () { vectorScope.feature.remove(tempFeatures, callback); }); }); }); }); }, measureArea: function (geom, callback) { $scope.gis.helpers.geoHandler.getArea(geom.wkt, function (area) { var arg = { geom: geom, area: area }; if (callback) callback(arg); }); }, addArea: function (o, callback) { var area = o.area; getSingleGeoJson(o.geom, function (geom) { viewer.gisviewer("getScale", function (scale) { var feature = { geometry: geom, properties: { style: { label: { text: moduleScope.getAreaText(area), /*scale: scale * 1*/ fontSize: scale / 100 } } } }; vectorScope.feature.add({ features: [feature] }, function () { vectorScope.feature.remove(tempFeatures, callback); }); }); }); }, openStyling: function (features) { if (!features) { features = vectorScope.feature.list.selected; if (!features.any()) { features = vectorScope.feature.list.items; } } $scope.modules.vectorfeatures.styling.form.load({ features: features, confirm: function (features) { vectorScope.feature.update(features); } }); } }); $el .on("click", ".remove-all", function (e) { e.preventDefault(); vectorScope.feature.remove(vectorScope.feature.list.items); }) .on("click", ".measure-distance", function (e) { e.preventDefault(); $scope.gis.digitize.line(function (geom) { if (!geom) { return; } moduleScope.measureDistance(geom, function (arg) { moduleScope.addDistance({ geom: arg.geom.geoJson, distance: arg.distance }); }); }); }) .on("click", ".measure-area", function (e) { e.preventDefault(); $scope.gis.digitize.polygon(function (geom) { if (!geom) { return; } moduleScope.measureArea(geom, function (arg) { moduleScope.addArea({ geom: arg.geom.geoJson, area: arg.area }); }); }); }) .on("click", ".copy-geometry", function (e) { e.preventDefault(); $scope.gis.digitize.copy(function (geom) { if (!geom) return; viewer.gisviewer("clearSelection", function () { var type = geom.geoJson.type; if (type.endsWith("LineString")) { moduleScope.measureDistance(geom, function (arg) { moduleScope.addDistance({ geom: arg.geom.geoJson, distance: arg.distance }); }); } else if (type.endsWith("Polygon")) { moduleScope.measureArea(geom, function (arg) { moduleScope.addArea({ geom: arg.geom.geoJson, area: arg.area }); }); } }); }); }); } } } MeasureDirective.$inject = ["commandBag", "gisViewerManager", "geoHelper", "panelHelper"]; return MeasureDirective; })("measure"); var menu = menu || {}; menu.Bootstrapper = (function () { function Bootstrapper(config, panelHelper) { var bs = this; this.initHashEvents = function (locationHashHelper) { var hashEvents = (function () { return { hideMenu: [function () { return panelHelper.hideMenu(); }], showMenu: [function () { return panelHelper.showMenu(); }], collapseMenu: [function () { return panelHelper.collapseMenu(); }], expandMenu: [function () { return panelHelper.expandMenu(); }] }; })(); locationHashHelper.addHashchangeEvents(hashEvents); return Promise.resolve(bs); }; } return Bootstrapper; })("menu"); var messages = messages || {}; messages.infoContainerComponent = (function () { "use strict"; function InfoContainerViewModel($timeout) { Object.defineProperties(this, { info: { writable: true }, text: { writable: true }, extra: { writable: true }, submitEnabled: { writable: true }, onSubmit: { writable: true }, onCancel: { writable: true }, _timeout: { value: $timeout } }); } Object.defineProperties(InfoContainerViewModel.prototype, { handleSubmit: { value: function (e) { return Promise.resolve(this.onSubmit({ event: e })) .then(this._timeout); } }, handleCancel: { value: function (e) { return Promise.resolve(this.onCancel({ event: e })) .then(this._timeout); } } }); function infoContainerComponent(templateUrl) { return { controller: ["$timeout", InfoContainerViewModel], bindings: { info: "<", text: "<", extra: "<", submitEnabled: "<", onSubmit: "&", onCancel: "&" }, templateUrl: ["config", function (config) { return config.baseUrl + "/" + templateUrl + "?v=" + config.version; }] }; } return infoContainerComponent; })("messages"); var messages = messages || {}; messages.InfoController = (function () { "use strict"; function InfoController(manager, $timeout) { Object.defineProperties(this, { _manager: { value: manager }, _timeout: { value: $timeout } }); } Object.defineProperties(InfoController.prototype, { message: { get: function () { return this._manager.message; }, enumerable: true }, canSubmit: { get: function () { return this.message != null && typeof (this.message.submit) === "function"; }, enumerable: true }, canCancel: { get: function () { return this.message != null && typeof (this.message.cancel) === "function"; }, enumerable: true }, push: { // { info: String, submit: Function, cancel: Function } value: function (msg) { var ctrl = this; return ctrl.cancel() .then(function() { return ctrl._manager.push(msg); }) .then(ctrl._timeout); } }, submit: { value: function () { return this._manager.submit() .then(this._timeout); } }, cancel: { value: function () { return this._manager.cancel() .then(this._timeout); } } }); return InfoController; })("messages"); var messages = messages || {}; (function (factory) { if (typeof exports === "object" && typeof module !== "undefined") { module.exports = factory(); } else if (typeof define === "function" && define.amd) { define(factory()); } else { messages.InfoManager = factory(); } })(function () { "use strict"; function InfoManager() { Object.defineProperties(this, { messages: { value: [], enumerable: true }, message: { value: null, enumerable: true, writable: true } }); } Object.defineProperties(InfoManager.prototype, { refreshMessage: { value: function() { this.message = this.messages.last(); console.log('InfoManager.message', this.message); } }, push: { // { info: String, submit: Function, cancel: Function } value: function (o) { var mgr = this; var msg = { info: o.info || (o.text ? null : o), text: o.text, extra: o.extra || {} }; EventHandler.injectInto(msg); mgr.messages.push(msg); mgr.refreshMessage(); if (typeof (o.submit) === "function") { msg.submit = o.submit; } msg.cancel = function () { mgr.messages.remove(msg); mgr.refreshMessage(); return Promise.resolve() .then(function () { if (typeof (o.cancel) === "function") { return o.cancel(); } return true; }); } return Promise.resolve(msg); } }, submit: { value: function () { var mgr = this; return Promise.resolve() .then(function () { var message = mgr.messages.shift(); message.trigger("closing"); mgr.refreshMessage(); if (message != null && typeof (message.submit) === "function") { return message.submit(); } return true; }) .catch(function (error) { console.error("Submit failed", { error: error, mgr: mgr }); }); } }, cancel: { value: function () { var mgr = this; return Promise.resolve() .then(function () { var message = mgr.messages.shift(); message.trigger("closing"); mgr.refreshMessage(); if (message != null && typeof (message.cancel) === "function") { return message.cancel(); } return true; }) .catch(function (error) { console.error("Cancel failed", { error: error, mgr: mgr }); }); } }, clear: { value: function () { var mgr = this; return mgr.cancel() .then(function () { if (mgr.messages.any()) { return mgr.clear(); } mgr.refreshMessage(); return true; }); } } }); return InfoManager; }); var mylocation = mylocation || {}; mylocation.MyLocationDirective = (function (moduleName) { "use strict"; function MyLocationDirective(config, commandBag) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, link: function ($scope) { //console.log(moduleName.toUpperCase(), this, $.extend(true, {}, $scope)); var viewer = $scope.gis.viewer; var locationScope = {}; $scope.gis.createVectorScope({ target: locationScope, layer: { Code: "mylocation", ShowInLegend: false }, featureStyle: { image: { iconUrl: config.baseUrl + "/Content/images/location.png", position: "center top", height: 32, width: 32 } } }); $scope.modules = $scope.modules || {}; $scope.modules[moduleName] = locationScope; function resetTempLayer(callback) { locationScope.vector.feature.remove({ features: locationScope.vector.feature.list.items }, callback); } var watchId; commandBag.on("execute", "TrackMyLocation", function (e, arg) { //console.log("MYLOCATION.EXECUTING", { args: arguments }); if (!arg.cmd.active) { //console.log("MYLOCATION.STOPPING"); $scope.gis.position.stopTracking(); resetTempLayer(); watchId = null; return; } watchId = $scope.gis.position.track({ maximumAge: 2500 }, function (position) { //console.log("MYLOCATION.TRACKING", { position: position, watchId: watchId }); if (!locationScope.vector.feature.list.items.length) { //console.log("ADDING"); locationScope.vector.feature.addGeometry({ geom: position.geom.wkt }, function () { viewer.gisviewer("zoom", { center: position.coordinate, scale: 500 }, function (/*arg*/) { //console.log("ZOOMED", arg); }); }); } else { //console.log("MYLOCATION.UPDATING", { feature: locationScope.vector.feature.list.items.first(), geoJson: position.geom.geoJson }); locationScope.vector.feature.list.items.first().geometry = position.geom.geoJson; locationScope.vector.feature.update({ features: locationScope.vector.feature.list.items }, function () { viewer.gisviewer("getExtent", function (extent) { extent.contains([position.coordinate], function (isInside) { //console.log("MYLOCATION.EXTENT", { extent: extent, coordinate: position.coordinate, isInside: isInside }); if (!isInside) { $(viewer).gisviewer("zoom", { center: position.coordinate }, function (/*arg*/) { //console.log("MYLOCATION.ZOOMED", arg); }); } }); }); }); } }); }); } }; } MyLocationDirective.$inject = ["config", "commandBag"]; return MyLocationDirective; })("mylocation"); var notities = notities || {}; notities.CategoryService = (function () { function CategoryService(config, $http) { EntityServiceBase.call(this, { niscode: config.niscode, url: config.categoryUrl }, $http); } CategoryService.$inject = ["notitiesConfig", "$http"]; CategoryService.prototype = Object.create(EntityServiceBase.prototype, { constructor: { value: CategoryService } }); return CategoryService; })("notities"); var notities = notities || {}; notities.NotitieGisManager = (function () { "use strict"; function NotitieGisManager(config, gisViewer, layerTree, geoHelper, geoHandler) { Object.defineProperties(this, { itemLayer: { writable: true, enumerable: true }, tempLayer: { value: { Code: "__notities_temp__", ShowInLegend: false }, writable: true, enumerable: true }, _selectedItems: { value: [] }, _config: { value: config }, _layers: { writable: true }, _viewer: { value: gisViewer }, _layerTree: { value: layerTree }, _geoHelper: { value: geoHelper }, _geoHandler: { value: geoHandler } }); } EventHandler.injectInto(NotitieGisManager.prototype); Object.defineProperties(NotitieGisManager.prototype, { getLayer: { value: function (item) { var mgr = this; return mgr._viewer.getFeatureLayerName({ filter: "{id} = " + item.id, layerNameTerm: mgr._config.layerName }) .then(function (itemLayerName) { //console.log("NGM.LAYER_NAME", { item: item, layerName: itemLayerName, mgr: mgr }); return mgr.getLayers() .then(function (layers) { return layers.first(function (x) { return x.Code === itemLayerName; }); }); }); } }, getLayers: { value: function () { var mgr = this; if (mgr._layers == null) { return new Promise( function (resolve) { return mgr._viewer.on("map-load", resolve); }) .then(function () { return mgr._layerTree.getAll(); }) .then(function (layers) { var layerNameTerms = _.array(mgr._config.layerName || mgr._config.layerNames); mgr._layers = layers .where(function (x) { return layerNameTerms.any(function (layerNameTerm) { if (layerNameTerm.startsWith("*") && layerNameTerm.endsWith("*")) { return x.Code.contains(layerNameTerm.trim("*")); } else if (layerNameTerm.endsWith("*")) { return x.Code.startsWith(layerNameTerm.trim("*")); } else if (layerNameTerm.startsWith("*")) { return x.Code.endsWith(layerNameTerm.trim("*")); } else { return x.Code === layerNameTerm; } }); }); return mgr._layers; }); } else { return Promise.resolve(mgr._layers); } } }, getExtent: { value: function (o) { var mgr = this; o = o || {}; o.projectIdOnly = true; var filter = mgr._getFilter(o); return mgr.getLayers() .then(function (layers) { return Promise.enqueue(layers.select(function(l) { return function() { return mgr._viewer.getFeaturesExtent({ layerName: l.Code, filter: filter }); }; })); }) .then(function (extents) { return [ extents.min(function (x) { return x[0] }), extents.min(function (x) { return x[1] }), extents.max(function (x) { return x[2] }), extents.max(function (x) { return x[3] }) ]; }); } }, setSelection: { value: function (items, minScale, zoomToSelection) { var mgr = this; //console.log("NGM.SET_SELECTION", { items: items, mgr: mgr }); if (!items || !items.length) { return mgr._viewer.clearSelection() .then(function () { return mgr._setSelectedItems([]); }); } return mgr.getGisFilter({ items: items }) .then(function (gisFilter) { return mgr._viewer.setSelectedFeatures({ filter: gisFilter, multi: true, initiator: "system", zoomToSelection: zoomToSelection, minScale: minScale }); }) .then(function (arg) { return mgr._setSelectedItems(items) .then(function () { return arg; }); }); } }, clearSelection: { value: function () { var mgr = this; return mgr._viewer.clearSelection() .then(function () { return mgr.refreshMap(); }); } }, setFeatureEditMode: { value: function (item) { var mgr = this; console.log("NGM.SET_EDITMODE", { item: item, mgr: mgr }); var modifiable = item != null; this._viewer.setFeaturesEditMode(modifiable); if (item != null) { var geom = mgr._geoHelper.getGeom(item.wkt); var transformable = !(geom.type || "").contains("Point", true); this._viewer.setFeaturesTransformMode(!!transformable); } } }, zoom: { value: function (o, minScale) { var mgr = this; return mgr.getExtent(o) .then(function (extent) { return mgr._viewer.zoomToExtent({ extent: extent, minScale: minScale }); }); } }, filterItems: { value: function (o) { var mgr = this; return mgr.getGisFilter(o) .then(function (filter) { return mgr._viewer.filter({ filter: filter }); }); } }, getGisFilter: { value: function (o) { var mgr = this; var filter = mgr._getFilter(o); return mgr.getLayers() .then(function (layers) { return layers.toDictionary(function (x) { return x.Code; }, function () { return filter; }); }); } }, refreshMap: { value: function () { return this._viewer.refreshMap(); } }, _getFilter: { value: function (o) { var conditions = o.filter ? [o.filter] : []; if (o.items && o.items.any(function (x) { return x; })) { var ids = o.items.select(function (x) { return x.id; }); conditions.push("{id} IN (" + ids.join(",") + ")"); } if ("projectId" in o) { if (o.projectId == null) { conditions.push("project_id NULL"); } else { conditions.push((!o.projectIdOnly ? "project_id NULL OR " : "") + "project_id IN (" + _.array(o.projectId).join(",") + ")"); } } var filter = conditions.aggregate(function (f, c) { return (f ? " AND " : "") + (f + "(" + c + ")"); }, ""); //console.log("NGM.FILTER", { filter: filter, o: o, mgr: this }); return filter; } }, setGeometry: { value: function (item, geom) { var mgr = this; //console.log("NGM.SET_GEOM", { item: item, geom: geom }); if (geom == null) { return Promise.resolve({ item: item, geom: null }); } return new Promise( function (resolve) { mgr._geoHandler.getMulti(geom.wkt, resolve); }) .then(function (wkt) { item.wkt = wkt; return mgr.trigger("change-geometry", { item: item, geom: geom }); }); } }, _setSelectedItems: { value: function (items) { var mgr = this; var oldValue = mgr._selectedItems.select(); var added = items.except(oldValue); var modified = oldValue.innerJoin(items); var removed = oldValue.except(items); Array.prototype.splice.apply(oldValue, [0, oldValue.length].concat(items)); var arg = { oldValue: oldValue, added: added, modified: modified, removed: removed, items: items }; return this.trigger("change-items", arg) .then(function () { return arg; }); } } }); return NotitieGisManager; })("notities"); var notities = notities || {}; notities.NotitieController = (function (moduleName) { "use strict"; function NotitieController(config, manager, notitieGisManager, projectManager, $timeout, $translate) { var ctrl = this; common.EntityController.call(ctrl, manager, $timeout); Object.defineProperties(ctrl, { _notitieGisManager: { value: notitieGisManager }, _projectManager: { value: projectManager }, _translate: { value: $translate }, hideButtons: { value: false, writable: true }, projectsEnabled: { value: config.enableProjects !== false } }); //console.log("NOTITIE_CTRL", { ctrl: ctrl }); } NotitieController.prototype = Object.create(common.EntityController.prototype, { constructor: { value: NotitieController }, project: { get: function () { return this._projectManager.activeItem; }, enumerable: true }, canEdit: { get: function () { return this._entityManager.canEdit; }, enumerable: true }, categories: { get: function () { return this._entityManager.categories; }, enumerable: true }, layer: { get: function () { return this._notitieGisManager.itemLayer; }, enumerable: true }, tempLayer: { get: function () { return this._notitieGisManager.tempLayer; }, enumerable: true }, item: { get: function () { return this._entityManager.item; }, set: function (value) { this._entityManager.item = value; }, enumerable: true }, itemFiles: { get: function () { return this._entityManager.itemFiles; }, enumerable: true }, selectedItems: { get: function () { return this._entityManager.selectedItems; }, enumerable: true }, display: { get: function () { return this._entityManager.display; }, set: function (value) { this._entityManager.display = value; }, enumerable: true }, errors: { get: function () { return this._entityManager.errors; }, enumerable: true }, // init init: { value: function () { return common.EntityController.prototype.list.call(this); } }, resetFilter: { value: function () { var me = this; return me._entityManager.resetFilter() .then(function (response) { return me._timeout() .then(function () { return response; }); }); } }, // CRUD showItem: { value: function (item, display) { var ctrl = this; return ctrl._entityManager.loadItem(item, display) .then(function (arg) { return ctrl._timeout() .then(function () { return arg; }); }); //var ctrl = this; //var promise; //if (item == null || item.id <= 0) { // promise = ctrl._entityManager.getNewItem(); //} else { // promise = ctrl._entityManager.details(item.id); //} //return promise // .then(function (details) { // return ctrl._entityManager.requestLoadItem(details, display); // }); } }, onChangeItem: { value: function (item, prop, value) { var ctrl = this; //console.log("NC.CHANGE_ITEM", { item: item, prop: prop, value: value, ctrl: this }); return Promise.resolve() .then(function () { if (prop === "geom") { return ctrl._notitieGisManager.setGeometry(item, value); } if (prop === "categoryId" || prop === "category") { } return false; }) .then(function () { ctrl._entityManager.validate(item) .then(function () { return ctrl._timeout(); }); }); } }, save: { value: function (display) { var ctrl = this; var item = ctrl.item; var state = ctrl.stateManager.addState("loading"); return ctrl._entityManager.save(item, display) .then(function (saved) { //console.log("NC.SAVED", { saved: saved, errors: ctrl.errors, mgr: ctrl._entityManager }); // ToDo: modify files-control so we can use a pointer instead of reassigning the list if (saved != null) { item.files = saved.files; } return ctrl._timeout() .then(function () { return saved; }); }) .then(state.completed) .catch(function (error) { state.error(error); G.handleError(error); }); } }, remove: { value: function (display) { var ctrl = this; return ctrl._translate("global.ConfirmDeleteItem") .then(function(translation) { return confirm(translation); }) .then(function(confirmed) { if (!confirmed) { return false; } var state = ctrl.stateManager.addState("loading"); return common.EntityController.prototype.remove.call(ctrl, display) .then(state.completed) .catch(function (error) { state.error(error); G.handleError(error); }); }); } } }); return NotitieController; })("notities"); var notities = notities || {}; notities.notitieFilterComponent = (function () { "use strict"; function NotitieFilterViewModel() { Object.defineProperties(this, { categories: { writable: true } }); } NotitieFilterViewModel.prototype = Object.create(common.EntityFilterViewModel.prototype, { constructor: { value: NotitieFilterViewModel } }); function notitieFilterComponent(templateUrl) { var component = common.entityFilterComponent(templateUrl); $.extend(component, { controller: NotitieFilterViewModel }); $.extend(component.bindings, { categories: "<" }); return component; } return notitieFilterComponent; })(); var notities = notities || {}; notities.notitieFormComponent = (function () { "use strict"; function NotitieFormViewModel() { common.EntityFormViewModel.call(this); Object.defineProperties(this, { categories: { writable: true }, itemFiles: { writable: true }, canEdit: { writable: true }, layer: { writable: true }, tempLayer: { writable: true }, onDetailDisplayChange: { writable: true } }); } NotitieFormViewModel.prototype = Object.create(common.EntityFormViewModel.prototype, { constructor: { value: NotitieFormViewModel }, saveDetail: { value: function (detail) { //console.log("NFC.SAVE_DETAIL", { detail: detail, vm: this }); if (detail.id <= 0) { this.item.details.push(detail); } } }, handleChangeDetailDisplay: { value: function (e, display) { this.onDetailDisplayChange({ event: e, display: display }); } } }); function notitieFormComponent(templateUrl) { var component = common.entityFormComponent(templateUrl); $.extend(component, { controller: NotitieFormViewModel }); $.extend(component.bindings, { categories: "<", itemFiles: "<", canEdit: "<", layer: "<", tempLayer: "<", onDetailDisplayChange: "&" }); return component; } return notitieFormComponent; })(); var notities = notities || {}; notities.notitieListComponent = (function () { "use strict"; function NotitieListViewModel() { common.EntityListViewModel.call(this); } NotitieListViewModel.prototype = Object.create(common.EntityListViewModel.prototype, { constructor: { value: NotitieListViewModel }, isSelected: { value: function (item) { return (this.selectedItems || []).any(function (x) { return x.id === item.id; }); } } }); function notitieListComponent(templateUrl) { var component = common.entityListComponent(templateUrl); $.extend(component, { controller: NotitieListViewModel }); return component; } return notitieListComponent; })(); var notities = notities || {}; notities.NotitieManager = (function () { "use strict"; function NotitieManager(service) { common.EntityManager.call(this, service); Object.defineProperties(this, { enabled: { value: true, writable: true }, categories: { value: [], enumerable: true, configurable: true }, errors: { value: [], enumerable: true }, _project: { writable: true }, _display: { value: "list", writable: true }, _item: { writable: true }, _itemFiles: { writable: true, value: [] } }); } NotitieManager.prototype = Object.create(common.EntityManager.prototype, { constructor: { value: NotitieManager }, project: { get: function () { return this._project; }, enumerable: true }, display: { get: function () { return this._display; }, set: function (value) { this.setDisplay(value); } }, item: { get: function () { return this._item; }, set: function (value) { this.setItem(value); }, enumerable: true }, itemFiles: { get: function () { return this._itemFiles; }, enumerable: true }, selectedItems: { get: function () { return this._selected; }, set: function (value) { this.setSelectedIds(value); }, enumerable: true }, // init init: { value: function (o) { o = o || {}; //console.log("NM.INIT", { o: o, mgr: this }); if ("canEdit" in o) { this.canEdit = !!o.canEdit; } if ("categories" in o) { Object.defineProperty(this, "categories", { value: o.categories, enumerable: true, configurable: true }); } return common.EntityManager.prototype.init.call(this, o); } }, getNewItem: { value: function () { var mgr = this; return common.EntityManager.prototype.getNewItem.call(this) .then(function (item) { item.files = []; item.details = []; item.categoryId = mgr.categories.select(function (x) { return x.id; }).first(); Object.defineProperty(item, "projectId", { get: function () { return mgr.project != null ? mgr.project.id : null; }, enumerable: true }); return item; }); } }, // filter resetFilter: { value: function () { this.filter = {}; if (this.project != null) { this.filter.projectId = this.project.id; } else { this.filter.projectId = "NULL"; } return this.list(); } }, // item loadItem: { value: function (item, display) { var mgr = this; return Promise.resolve() .then(function () { mgr.errors.clear(); }) .then(function () { if (item == null || item.id <= 0) { return mgr.getNewItem(); } return mgr.details(item.id); }) .then(function (details) { return mgr.setItem(details, display) .then(function () { return details; }); }); } }, setItem: { value: function (item, display) { var mgr = this; var oldItem = mgr._item; //console.log("NM.SET_ITEM", { item: item, oldItem: oldItem, display: display, mgr: this }); var arg = { item: item, oldItem: oldItem, display: display }; return Promise.resolve() .then(function () { if (oldItem !== item) { mgr._item = item; return Promise.resolve() .then(function () { return mgr._setItemFiles(item); }) .then(function () { if (typeof (display) === "string") { return mgr.setDisplay(display); } return null; }) .then(function () { return mgr.trigger("change-item", arg); }); } return null; }) .then(function () { return arg; }); } }, // itemFiles _setItemFiles: { value: function (item) { var mgr = this; var itemFiles = []; if (item != null) { itemFiles = item.files.select(function (document) { return { name: document.document, type: document.contentType, size: document.filesize, src: mgr._service.getFileUrl(document) }; }); } mgr._itemFiles = itemFiles; return Promise.resolve(itemFiles); } }, // display setDisplay: { value: function (display) { var oldDisplay = this.display; var arg = { display: display, oldDisplay: oldDisplay }; var promise = Promise.resolve(); if (display !== oldDisplay) { this._display = display; promise = this.trigger("change-display", arg); } return promise .then(function () { return arg; }); } }, // CRUD save: { value: function (item, display) { var mgr = this; return mgr.validate(item) .then(function (isValid) { if (!isValid) { console.warn("NM.INVALID", { item: item, errors: mgr.errors }); return null; } item.files.remove(function (x) { return x.removed; }); item.details.remove(function (x) { return x.removed; }); return common.EntityManager.prototype.save.call(mgr, item) .then(function (saved) { if (_.isArray(item.files)) { item.files.clear().addRange(saved.files); } if (_.isArray(item.details)) { item.details.clear().addRange(saved.details); } //console.log("NM.SAVED", { item: item, saved: saved, mgr: mgr }); if (typeof (display) === "string") { return mgr.setDisplay(display || "list") .then(function () { return saved; }); } return saved; }) .catch(function (error) { console.error("SAVE", { error: error, item: item, mgr: mgr }); mgr.errors.push("ServerError"); }); }); } }, // validation validate: { value: function (item) { var mgr = this; mgr.errors.clear(); return Promise.resolve() .then(function () { //if (!item.title) { // mgr.errors.push("TitleMissing"); //} if (!item.category && !item.categoryId) { mgr.errors.push("CategoryMissing"); } if (!item.wkt) { mgr.errors.push("GeomMissing"); } }) .then(function () { return !mgr.errors.length; }); } }, setProject: { value: function (project) { //console.log("NM.SET_PROJECT", { project: project, mgr: this }); this._project = project; if (project != null) { this.filter.projectId = project.id; } else { this.filter.projectId = "NULL"; } return Promise.resolve(project); } } }); return NotitieManager; })("notities"); var notities = notities || {}; notities.NotitieService = (function () { function NotitieService(config, $http) { EntityServiceBase.call(this, { niscode: config.niscode, url: config.notitieUrl }, $http); Object.defineProperties(this, { _config: { value: config } }); } NotitieService.prototype = Object.create(EntityServiceBase.prototype, { constructor: { value: NotitieService }, _getDefaultParams: { value: function () { return angular.extend(EntityServiceBase.prototype._getDefaultParams.call(this), { map: this._config.mapName, session: this._config.sessionId, resourceId: this._config.mapResourceId }); } }, _processItem: { value: function (item) { if (typeof (item.created) !== "undefined") { item.created = new Date(item.created); } return item; } }, getFileUrl: { value: function (document) { return this._config.documentUrl .replace("{id}", document.id) .replace("{rnd}", Math.random()) .replace("{niscode}", document.niscode); } }, details: { value: function () { //console.log("N.DETAILS"); return EntityServiceBase.prototype.details.apply(this, arguments); } } }); return NotitieService; })("notities"); var notities = notities || {}; notities.NotitieDetailController = (function () { "use strict"; function NotitieDetailController($timeout) { Object.defineProperties(this, { _serial: { value: -1, writable: true, enumerable: true }, display: { value: "list", writable: true, enumerable: true }, _original: { writable: true }, item: { writable: true, enumerable: true }, items: { value: [], writable: true, enumerable: true }, _timeout: { value: $timeout } }); //console.log("ND_CTRL", { items: this.items, ctrl: this }); } Object.defineProperties(NotitieDetailController.prototype, { init: { value: function (o) { if ("items" in o) { this.items = o.items; } if ("display" in o) { this.display = o.display; } //console.log("NDC.INIT", { o: o, ctrl: this }); } }, showItem: { value: function (item, display) { var ctrl = this; return Promise.resolve(item != null ? item : { id: ctrl._serial-- }) .then(function (item) { ctrl._original = $.extend(true, {}, item); ctrl.item = item; ctrl.display = display; return ctrl.item; }); } }, cancel: { value: function (display) { this.item = $.extend(true, {}, this._original); if (display) { this.display = display; } return Promise.resolve(this.item); } }, save: { value: function (display) { //console.log("NDC.SAVE", { item: this.item, ctrl: this }); if (!this.items.contains(this.item)) { this.items.push(this.item); } this._original = null; this.item = null; if (display) { this.display = display; } return Promise.resolve(this.item); } }, remove: { value: function (item, display) { this.items.remove(item); if (item === this.item) { this.item = null; } this.display = display || "list"; return Promise.resolve(item); } }, isUrl: { value: function (value) { function isValidUrl(val) { var urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/; return val && val.startsWith("http") && urlregex.test(val); } return isValidUrl(value); } }, setFrameSrc: { value: function (el, url) { $(el).prop("src", url); } } }); return NotitieDetailController; })(); var notities = notities || {}; notities.NotitieDocumentViewModel = (function () { "use strict"; var _imageHelper; function NotitieDocumentViewModel(imageHelper) { _imageHelper = imageHelper; Object.defineProperties(this, { loading: { writable: true }, readOnly: { writable: true }, items: { writable: true }, selectedItems: { writable: true }, onSelect: { writable: true }, onShow: { writable: true }, onFocus: { writable: true }, onBrowse: { writable: true }, onRemove: { writable: true } }); } Object.defineProperties(NotitieDocumentViewModel.prototype, { handleSelect: { value: function (e, item) { return this.onSelect({ event: e, item: item }); } }, handleShow: { value: function (e, item, display) { return this.onShow({ event: e, item: item, display: display }); } }, handleFocus: { value: function (e, item) { return this.onFocus({ event: e, item: item }); } }, handleBrowse: { value: function (e) { var vm = this; _imageHelper.browse() .then(function (files) { return vm.onBrowse({ event: e, files: files }); }); } }, handleRemove: { value: function (e, item) { return this.onRemove({ event: e, item: item }); } }, isSelected: { value: function (item) { return (this.selectedItems || []).contains(item); } } }); return NotitieDocumentViewModel; })(); notities.entityListComponent = (function () { "use strict"; function entityListComponent(templateUrl) { return { controller: ["imageHelper", notities.NotitieDocumentViewModel], bindings: { loading: "<", readOnly: "<", items: "<", selectedItems: "<", onSelect: "&", onShow: "&", onFocus: "&", onBrowse: "&", onRemove: "&" }, templateUrl: ["config", function (config) { return config.baseUrl + "/" + templateUrl + "?v=" + config.version; }], transclude: { loading: "?loading" } }; } return entityListComponent; })(); var notities = notities || {}; notities.Bootstrapper = (function (moduleName) { "use strict"; function Bootstrapper(config, categoryService, notitieManager, $translate, $timeout) { var bs = this; this.initCommands = function (commandBag, gisViewer) { var commands = [{ name: moduleName + ".Open", title: function () { return $translate(moduleName + ".Notes"); }, content: '' }, { name: moduleName + ".AddNotitie", title: function () { return $translate(moduleName + ".Note"); }, content: '' }, { name: moduleName + ".AddGpsNotitie", title: function () { return $translate(moduleName + ".GpsNote"); }, content: '', callback: function () { gisViewer.getClientPosition() .then(function (arg) { //console.log("NB.POSITION", { arg: arg }); return gisViewer.zoom({ center: arg.coordinate, scale: 500 }) .then(function () { return notitieManager.getNewItem(); }) .then(function (item) { item.wkt = "MULTIPOINT((" + arg.coordinate[0] + " " + arg.coordinate[1] + "))"; return notitieManager.setItem(item, "form"); }); }) .then(function () { commandBag.execute(moduleName + ".Open"); }); } }]; commandBag.add(commands); return Promise.resolve(bs); }; this.initCategories = function () { //console.log("NBS.LOAD"); return categoryService .list() .then(function (categories) { return notitieManager .init({ canEdit: config.canEdit, categories: categories }); }) .then(function () { return bs; }); }; this.initNotities = function () { notitieManager .on("save-item remove-item", $timeout); }; this.loadProject = function(project) { return Promise.resolve() .then(function() { return notitieManager.setProject(project); }) .then(function(result) { notitieManager.load(); //parallel return result; }); }; this.initProjects = function (projectManager, notitieGisManager) { projectManager .on("change-active-item", function (e, arg) { //console.log("NB.CHANGE_ACTIVE_PROJECT", { evt: e, arg: arg }); return bs.loadProject(arg.activated) .then(function () { if (arg.activated === null && arg.deactivated === null) { // initial load without active project return notitieGisManager.filterItems({ projectId: null }); } return null; }); }) .on("change-loaded-items", function (e, arg) { //console.log("NB.CHANGE_LOADED_PROJECTS", { evt: e, arg: arg }); var t0 = performance.now(); var projectIds = arg.items.select(function (x) { return x.id; }); return notitieGisManager.filterItems({ projectId: projectIds.length ? projectIds : null }) .then(function (result) { var t1 = performance.now(); //console.log("PERFORMANCE", Math.round(t1 - t0), "ProjectManager[change-loaded-items].Notities[NotitieGisManager.filter]"); return result; }); }); return Promise.resolve(bs); }; this.initNotitieGis = function (notitieGisManager, gisFeatureService, projectManager) { var ignoreSetGisSelection = false; notitieManager // zoom to notitie(s) .on("focus", function (e, arg) { //return notitieManager.setSelectedItems(arg.items) //.then(function () { return notitieGisManager.zoom({ items: arg.items }, arg.minScale); //}); }) .on("save-item remove-item", function (e, arg) { // update layer since it depends on the item's properties return notitieGisManager.getLayer(arg.saved || arg.removed) .then(function (layer) { notitieGisManager.itemLayer = layer; return notitieGisManager.refreshMap(); }); }) .on("change-item", function (e, arg) { //console.log("NB.CHANGE_ITEM", { evt: e, arg: arg, mgr: notitieManager, gisMgr: notitieGisManager }); return (arg.item != null && arg.item.id > 0 ? notitieGisManager.getLayer(arg.item) : Promise.resolve(null)) .then(function (layer) { notitieGisManager.itemLayer = layer; return $timeout(); }); }) .on("change-selected-items", function (e, arg) { //console.log("NB.SELECTION", { evt: e, arg: arg, notitieManager: notitieManager, gisFeatureService: gisFeatureService }); if (!arg.added && !arg.removed) { return false; } //if (arg.selectedItems.length === 0) { // return notitieGisManager.clearSelection(); //} if (!ignoreSetGisSelection) { return notitieGisManager.setSelection(arg.selectedItems, 500, false); } ignoreSetGisSelection = false; return false; }); notitieGisManager .on("change-geometry", function (/*e, arg*/) { //console.log("NMS.GEOM_CHANGED", { evt: e, arg: arg }); // update value geom-selector ans show geometry on map return $timeout(); }) .on("change-items", function (/*e, arg*/) { //console.log("NMS.CHANGE_ITEMS", { evt: e, arg: arg }); }); gisFeatureService // selection on map changed .on("selection-change", function (e, arg) { // ignore when event is not triggered by a user-action on the map if (arg.initiator !== "user") { return null; } //console.log("NB.GIS_SELECTION", { evt: e, arg: arg }); if (arg.featureCount === 0) { return notitieManager.setSelectedItems([]) .then(function () { return $timeout(); }); } return notitieGisManager.getLayers() .then(function (layers) { var ids = layers .selectMany(function (l) { if (l.Code in arg.selection) { return arg.selection[l.Code].select(function (f) { return parseInt(f, 10); }); } return []; }) .distinct(); ignoreSetGisSelection = true; if (ids.length === 0) { return notitieManager.setSelectedItems([]); } return notitieManager.setSelectedIds(ids); }); }); projectManager .on("request-extents", function (e, arg) { var projects = arg.items; var projectIds = projects.select(function (x) { return x.id; }); return notitieGisManager.getExtent({ projectId: projectIds }) .then(function (extent) { arg.addExtent(extent); return extent; }); }); return Promise.resolve(bs); }; this.initElements = function (commandBag) { var pm = new PanelManager($(".content-container")); var moduleContainer = $("#NotitiesContainer"); commandBag .on("execute", moduleName + ".Open", function () { //$(".panel-bottom > *").hide(); pm.show(moduleContainer, "bottom"); }) .on("execute", moduleName + ".Close", function () { pm.hide(moduleContainer, "bottom"); }); pm.container.on("closed", function (e, arg) { if (arg.element.get(0) === moduleContainer.get(0)) { notitieManager.loadItem(null, "list"); } }); return Promise.resolve(bs); }; this.initCss = function () { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); return Promise.resolve(bs); }; this.initFeatureInfo = function (projectManager, notitieGisManager, featureInfoBag, commandBag) { notitieGisManager.getLayers() .then(function (layers) { featureInfoBag.registerAction({ layerNames: layers.select(function (x) { return x.Code; }).concat([notitieGisManager.tempLayer.Code]), action: function (arg) { console.log("NBD.ACTION", { arg: arg, layerName: arg.layerName, featureIds: arg.featureIds }); var ids = arg.featureIds.select(parseInt); if (ids.length === 0) { return notitieManager.loadItem(null, "list") .then($timeout); } return Promise.resolve() .then(function () { if (arg.totalFeatureCount === ids.length) { return notitieManager.details(ids.first()) .then(function (item) { var activeProject = projectManager.activeItem; if (activeProject == null || item.projectId == null || item.projectId === activeProject.id) { return item; } return null; }); } return null; }) .then(function (item) { if (item == null) { return false; } return notitieManager.setItem(item, config.canEdit ? "form" : "details") .then($timeout) .then(function () { commandBag.execute(moduleName + ".Open"); return true; }); }); } }); }); notitieManager .on("change-display", function (e, arg) { //console.log("NB.CHANGE_DISPLAY", { evt: e, arg: arg }); if (arg.display === "form") { featureInfoBag.setDisabled(true); } else if (arg.oldDisplay === "form") { featureInfoBag.setDisabled(false); } }); }; this.initPanels = function (panelManager, commandBag) { notitieManager .on("change-display", function (e, arg) { if (arg.display === "form") { panelManager.freezePanel($("#NotitiesContainer")); panelManager.disablePanel("right"); commandBag.disable(commandBag.items.where(function (x) { var toIgnore = "security.User,gislegend.Legend,TrackMyLocation,crab.SearchAddress,ZoomIn,ZoomOut,InitialExtent".split(","); return !toIgnore.contains(x.name); })); } else { panelManager.unfreezePanel($("#NotitiesContainer")); panelManager.enablePanel("right"); commandBag.enableAll(); } }); return Promise.resolve(bs); }; this.initData = function (o) { o = o || {}; var projectId = o.projectId; var categoryId = o.categoryId; if (projectId != null) { notitieManager.filter.projectId = projectId; } else { notitieManager.setProject(null); } if (categoryId != null) { notitieManager.filter.categoryId = categoryId; } return notitieManager.load() .then(function () { return bs; }); } } return Bootstrapper; })("notities"); var notities = notities || {}; notities.NotitiesDirective = (function (/*moduleName*/) { function NotitiesDirective() { return { restrict: "EA", template: '
'/*, templateUrl: ModuleManager.templateUrl, link: function ($scope, $el, $attr) { console.log(moduleName.toUpperCase(), moduleName, $.extend(true, {}, $scope), $attr); }*/ }; }; return NotitiesDirective; })("notities"); ; (function (global, factory) { if (typeof exports === "object" && typeof module !== "undefined") { module.exports = factory(global, { onLine: undefined }); } else if (typeof define === "function" && define.amd) { define(factory(global, navigator)); } else { global.OnlineStateService = factory(global, navigator); } })(this, function (global, browser) { "use strict"; function onChangeOnlineState(e) { var evt = new Event("change-online-state", e); var arg = { isOnline: this.isOnline }; console.log("CHANGE_ONLINE_STATE", { evt: evt, arg: arg, me: this }); return this.trigger(evt, arg) .then(function () { return arg; }); } function OnlineStateService() { Object.defineProperties(this, { _onChangeOnlineState: { value: onChangeOnlineState.bind(this) } }); this.init(); } global.EventHandler.injectInto(OnlineStateService.prototype); Object.defineProperties(OnlineStateService.prototype, { isOnline: { get: function () { return browser.onLine === true; } }, init: { value: function () { global.addEventListener("online", this._onChangeOnlineState); global.addEventListener("offline", this._onChangeOnlineState); } }, destroy: { value: function () { global.removeEventListener("online", this._onChangeOnlineState); global.removeEventListener("offline", this._onChangeOnlineState); } } }); return OnlineStateService; }); var panels = panels || {}; panels.PanelContainerDirective = (function () { function PanelContainerDirective() { return { controller: ["panelManager", function (panelManager) { Object.defineProperty(this, "panels", { get: function () { return panelManager.items; }, enumerable: true }); }], controllerAs: "ctrl" }; } return PanelContainerDirective; })("panels"); var panels = panels || {}; panels.PanelController = (function () { "use strict"; function PanelController(panelManager) { Object.defineProperties(this, { _pm: { value: panelManager } }); } Object.defineProperties(PanelController.prototype, { item: { get: function () { if (!this.panelName) { return null; } return this._pm.find(this.panelName); } }, init: { value: function (o) { var vm = this; return vm._pm.add(o) .then(function (panel) { Object.defineProperty(vm, "panelName", { value: panel.name, enumerable: true }); return panel; }); } } }); PanelController.$inject = ["panelManager"]; return PanelController; })("panels"); var panels = panels || {}; panels.PanelDirective = (function () { function PanelDirective($timeout) { return { restrict: "EA", scope: {}, controller: "panelController", controllerAs: "ctrl", link: function ($scope, $el, $attr, $ctrl) { $scope.evalVisibility = function (panel) { if (!panel) { return; } //console.log("EVAL_PANEL", { name: panel.name, panel: panel, visible: panel.visible }); if (panel.visible) { $(panel.element).show(); //console.log("SHOW", panel.name); } else { $(panel.element).hide(); //console.log("HIDE", panel.name); } $timeout(); }; $scope.panel = null; $ctrl.init({ name: $attr.panel, element: $el.get(0), visible: $attr.panelVisible !== "false", active: $attr.panelActive === "true", disabled: $attr.panelDisabled === "true" }) .then(function (panel) { $scope.panel = panel; //console.log("PANEL_DIRECTIVE", { scope: $scope, el: $el, ctrl: $ctrl, panel: panel, visible: panel.visible }); $scope.evalVisibility(panel); }); $scope.$watch(function () { return $scope.panel && $scope.panel.visible; }, function (/*newVal, oldVal*/) { //console.log("PANEL_WATCH", { scope: $scope, newVal: newVal, oldVal: oldVal }); $scope.evalVisibility($scope.panel); }); } } } PanelDirective.$inject = ["$timeout"]; return PanelDirective; })("panels"); var panels = panels || {}; panels.PanelManager = (function () { "use strict"; /* var panelDefinition = { name: { type: "string", required: true }, element: { type: "HTMLelement", required: true }, panelContentItems: { type: "array", required: true }, visible: "boolean", active: "boolean", disabled: "boolean" }; var panelContentDefinition = { name: { type: "string", required: true }, element: { type: "HTMLelement", required: true }, visible: "boolean" }; */ function PanelManager($rootScope) { var pm = this; //ToDo: remove $rootScope dependency //NOTE rik: hier is echt wel iets mis mee, ik heb waar nodig code moeten veranderen zodat deze niet wordt gebruikt // $rootScope.$$childTail.panels is leeg Object.defineProperty(this, "panels", { get: function () { return $rootScope.$$childTail.panels; } }); pm.halfLeft = function () { pm.panels.setMode("left", "half"); }; pm.halfRight = function () { pm.panels.setMode("right", "half"); }; pm.halfBottom = function () { pm.panels.setMode("bottom", "half"); }; pm.fullLeft = function () { pm.panels.setMode("left", "full"); }; pm.fullRight = function () { pm.panels.setMode("right", "full"); }; pm.isPanelVisible = function (panel) { return pm.panels.isPanelVisible(panel); }; } EventHandler.injectInto(PanelManager.prototype); Object.defineProperties(PanelManager.prototype, { items: { get: function () { if (!("_panels" in this)) { Object.defineProperty(this, "_panels", { value: {} }); } return this._panels; }, enumerable: true }, find: { value: function (o) { if (typeof (o) === "string") { return this.items[o]; } return o; } }, init: { value: function () { } }, add: { value: function (panel) { var pm = this; var unloaded = pm.items[panel.name]; pm.items[panel.name] = panel; return (unloaded ? pm._onUnload({ panel: unloaded }) : Promise.resolve()) .then(function () { return pm._onLoad({ panel: panel }); }) .then(function () { return panel; }); } }, load: { value: function (panelName, panelContent) { var panel = this.find(panelName); if (panel != null) { var index = panel.panelContentItems.indexOf(panelContent); if (index !== -1) { panel.panelContentItems.splice(index, 1); } panel.panelContentItems.unshift(panelContent); panelContent.visible = true; } } }, _onLoad: { //{ panel } value: function (arg) { return this.trigger("load", arg); } }, _onUnload: { //{ panel } value: function (arg) { return this.trigger("unload", arg); } }, _onOpen: { //{ panel } value: function (arg) { return this.trigger("open", arg); } }, _onClose: { //{ panel } value: function (arg) { return this.trigger("close", arg); } }, _onResize: { //{ panel } value: function (arg) { return this.trigger("resize", arg); } } }); PanelManager.$inject = ["$rootScope"]; return PanelManager; })("panels"); //var pictures = pictures || {}; //pictures.CategoryController = (function () { // "use strict"; // function CategoryController() { // Object.defineProperties(this, { // items: { value: [], writable: true, enumerable: true } // }); // } // Object.defineProperties(CategoryController.prototype, { // }); // return CategoryController; //})("pictures"); var pictures = pictures || {}; pictures.CategoryService = (function () { function CategoryService(config, $http) { EntityServiceBase.call(this, { niscode: config.niscode, url: config.categoryUrl, config }, $http); Object.defineProperties(this, { _config: { value: config } }); } CategoryService.prototype = Object.create(EntityServiceBase.prototype, { constructor: { value: CategoryService }, _processItem: { value: function (item) { if (!("titleNL" in item)) { item.titleNL = item.title; } if (!("titleFR" in item)) { item.titleFR = item.titleFR || item.title; } return item; } }, list: { value: function (o) { var sv = this; o = o || {}; if (!o.parentCode) { o.parentCode = sv._config.module.toUpperCase(); } return sv._get(angular.extend({}, o || {}, { action: "list" })) .then(function (response) { var itemPromises = response.data.select(function (x) { return sv._processItem(x); }); return Promise.all(itemPromises); }); } }, }); return CategoryService; })("pictures"); var pictures = pictures || {}; pictures.PictureController = (function () { "use strict"; function PictureController(manager, imageHelper) { Object.defineProperties(this, { _manager: { value: manager }, _imageHelper: { value: imageHelper } }); } Object.defineProperties(PictureController.prototype, { defaultHeight: { writable: true, enumerable: true }, canEdit: { get: function () { return this._manager.canEdit; }, enumerable: true }, categories: { get: function () { return this._manager.categories; }, enumerable: true }, items: { get: function () { return this._manager.items; }, enumerable: true }, groupedItems: { get: function () { return this._manager.groupedItems; }, enumerable: true }, browse: { value: function (category) { var vm = this; return vm._imageHelper.browse({ accept: "image/*" }) .then(function (files) { return Promise.all( files.select(function (f) { return vm._manager.createNew(f, category.id); }) ); }) .then(function (pictures) { return Promise.enqueue(pictures.select(function (p) { return function() { return vm._manager.save(p); }; })); }); }, enumerable: true }, save: { value: function (item, display) { var vm = this; return vm._manager.save(item, display) .then(function (saved) { vm.items.push(saved); return saved; }); } }, getUrl: { value: function (item, lang) { return this._manager.getUrl(item || this.item, lang); } } }); return PictureController; })("pictures"); var pictures = pictures || {}; pictures.pictureListComponent = (function () { "use strict"; function PictureListViewModel($translate) { Object.defineProperties(this, { _translate: { value: $translate }, browseEnabled: { writable: true }, category: { writable: true }, items: { writable: true }, onDragEnd: { writable: true }, onBrowse: { writable: true } }); } Object.defineProperties(PictureListViewModel.prototype, { lang: { get: function () { return this._translate.use().toUpperCase(); }, enumerable: true }, handleDragEnd: { value: function (e, item, pixel, size) { return this.onDragEnd({ event: e, item: item, pixel: pixel, size: size }); } }, handleBrowse: { value: function (e) { return this.onBrowse({ event: e, category: this.category }); } } }); function pictureListComponent(templateUrl) { return { controller: ["$translate", PictureListViewModel], bindings: { browseEnabled: "<", category: "<", items: "<", onDragEnd: "&", onBrowse: "&" }, templateUrl: ["config", function (config) { return config.baseUrl + "/" + templateUrl + "?v=" + config.version; }] }; } return pictureListComponent; })(); var pictures = pictures || {}; pictures.PictureManager = (function () { "use strict"; function PictureManager(service) { common.EntityManager.call(this, service); Object.defineProperties(this, { _serialId: { value: -1, writable: true }, canEdit: { writable: true, enumerable: true }, categories: { value: [], enumerable: true }, _icons: { value: [] } }); } PictureManager.prototype = Object.create(common.EntityManager.prototype, { constructor: { value: PictureManager }, //init init: { value: function (o) { o = o || {}; var canEdit = !!o.canEdit; var categories = o.categories || []; this.canEdit = canEdit; this.categories.clear().addRange(categories); return common.EntityManager.prototype.init.call(this, o); } }, setItems: { value: function (items) { var mgr = this; return common.EntityManager.prototype.setItems.call(mgr, items) .then(function () { mgr.groupedItems = items .groupBy(function (x) { return x.categoryId; }) .toDictionary(function (x) { return x.key; }, function (x) { return x.values; }); return items; }); } }, list: { value: function (/*arguments*/) { var mgr = this; return mgr._service.list(mgr.filter) .then(function (items) { return mgr._service.listIcons(mgr.filter) .then(function (icons) { return mgr._service.addIcons(items, icons); }); }) .then(function (items) { return mgr.setItems(items); }); } }, createNew: { value: function (file, categoryId) { var mgr = this; return mgr._service.createNew(file, categoryId) .then(function (picture) { picture.id = mgr._serialId--; return picture; }); } }, getUrl: { value: function (item, lang) { return this._service.getUrl(item, lang); } } }); return PictureManager; })(); var pictures = pictures || {}; pictures.Bootstrapper = (function (moduleName) { "use strict"; function Bootstrapper(config, categoryService, pictureManager) { var bs = this; this.initCategories = function () { //console.log("PBS.LOAD"); return categoryService .list() .then(function (categories) { return pictureManager.init({ canEdit: config.canEdit, categories: categories }); }) .then(function () { return bs; }); }; this.initPictureData = function () { return pictureManager.load() .then(function () { return bs; }); }; this.initCss = function () { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); return Promise.resolve(bs); }; } return Bootstrapper; })("pictures"); var pictures = pictures || {}; pictures.PictureService = (function () { function PictureService(config, categoryService, imageHelper, $http) { var sv = this; EntityServiceBase.call(sv, { niscode: config.niscode, url: config.pictureUrl }, $http); Object.defineProperties(sv, { _baseUrl: { value: config.baseUrl }, _imageHelper: { value: imageHelper }, _categories: { value: [] }, _categoryService: { value: categoryService } }); //console.log("PICTURE_SERVICE", { config: config, sv: sv }); sv.fillCategories(); } PictureService.prototype = Object.create(EntityServiceBase.prototype, { constructor: { value: PictureService }, listIcons: { value: function (o) { var mgr = this; return mgr._get(angular.extend({}, o || {}, { action: "icons" })) .then(function (response) { return response.data; }) .catch(function (error) { console.error("LIST_ICONS", { error: error, mgr: mgr }); }); } }, addIcons: { value: function (items, icons) { var sv = this; return Promise .all(items //.where(function(x) { return x.category.code !== "TEMP"; }) .select(function (item) { return Promise.resolve() .then(function() { try { var base64 = "data:" + item.contentType + ";base64," + icons[item.id]; return sv._imageHelper.getBlob(base64, item.contentType, item.filename); } catch (error) { return sv._imageHelper.getImageFromUrl(sv._baseUrl + "/content/images/broken-image.png") .then(function(img) { return sv._imageHelper.getBlob(img); }); } }) .then(function (blob) { item.blob = blob; item.url = sv._imageHelper.createUrl(blob); return item; }); })); //.then(function (items) { // return sv.testIcons(items) // .then(function () { // return items; // }); //}); } }, testIcons: { value: function (items) { var sv = this; console.log("TEST_ICONS", { items: items }); return Promise .all(items.select(function (pic) { return sv._imageHelper.getImageFromUrl(pic.url) .catch(function (error) { console.error("FAILED", { error: error, pic: pic }); }); })); } }, newItem: { get: function () { return { categoryId: null, src: null, file: null } } }, fillCategories: { value: function () { var sv = this; return sv._categoryService.list() .then(function (categories) { Array.prototype.splice.apply(sv._categories, [0, sv._categories.length].concat(categories)); }); } }, createNew: { value: function (file, categoryId) { var sv = this; return sv._imageHelper.getDataUrl(file) .then(function (dataUrl) { var item = sv.newItem; item.categoryId = categoryId || sv._categories .where(function (x) { return x.code === "TEMP"; }) .select(function (x) { return x.id; }) .first() || 0; item.filename = file.name; item.filesize = file.size; item.contentType = file.type; item.blob = file; item.url = sv._imageHelper.createUrl(file); item.base64 = dataUrl; return item; }); }, enumerable: true }, save: { value: function (item) { var sv = this; return EntityServiceBase.prototype.save.call(sv, item) .then(function (saved) { return sv.listIcons({ id: saved.id }) .then(function (icons) { return sv.addIcons([saved], icons) .then(function (items) { return items.first(); }); }); }); } }, getUrl: { value: function (item, lang) { var isSvg = (item.contentType === "image/svg+xml") ? 1 : 0; if (item.category) { var categoryTitle = item.category.title; if (lang != null) { categoryTitle = item.category["title" + lang.toUpperCase()] + "-" + lang; } return this._getUrl(null, { action: "img", identifier: categoryTitle + "/" + item.title, svg: isSvg }); } return this._getUrl(null, { action: "img", id: item.id, svg: isSvg }); } }, _processItem: { value: function (item) { item.titleNL = item.titleNL || item.title; item.titleFR = item.titleFR || item.title; item.category = this._categories.first(function (x) { return x.id === item.categoryId; }); return item; } } }); return PictureService; })("pictures"); (function (global, factory) { if (typeof exports === "object" && typeof module !== "undefined") { module.exports = factory(); } else if (typeof define === "function" && define.amd) { define(factory); } else { global.print = global.print || {}; global.print.PrintGenerator = factory(); } })(window, function () { function PdfGenerator() { } Object.defineProperties(PdfGenerator.prototype, { create: { value: function (img, options) { var pdf = new jsPDF('landscape', 'mm', options.paperSize); pdf.addImage(img, 'JPEG', 0, 0, options.size[0], options.size[1]); pdf.save('print.pdf'); } } }) return PdfGenerator; }); var print = print || {}; print.PrintDirective = (function (moduleName) { "use strict"; function PrintDirective(config, commandBag, $translate, printService, gisViewerManager) { return { restrict: "EA", templateUrl: function (el, attr) { return _.toArray(attr).where(function (x) { return x.key.endsWith("Directive") }).select(function (x) { return x.value; }).first() || attr.src; }, link: function ($scope, $el) { //console.log(moduleName.toUpperCase(), this, $.extend(true, {}, $scope)); //el.addClass("popup").css({ right: "0", top: "3em" }); var viewer = $scope.gis.viewer; $scope.modules[moduleName] = {}; var module = $scope.modules[moduleName]; var layerConfig = { Code: "print_layer", Title: "PRINT", ShowInLegend: false }; //print layer $scope.gis.createVectorScope({ layer: layerConfig, target: module }); var vectorScope = module.vector; $scope.handlers.PrintTemplates.PrintTemplate.prototype.Print = function (o) { return G.post(config.baseUrl + "/GeoRest/Print/PrintTemplate", o); }; function hidePrintLayer() { return new Promise(function (resolve) { viewer.gisviewer("hideLayer", { layerName: vectorScope.layer.item.Code }, function () { //console.log("PD.HIDE_LAYER", vectorScope.layer.item.Code); viewer.gisviewer("clearSelection", function () { viewer.gisviewer("setTransformRotate", { active: false }, resolve); }); }); }); } function showPrintLayer(callback) { //console.log("PD.SHOW_LAYER", vectorScope.layer.item.Code); viewer.gisviewer("showLayer", { layerName: vectorScope.layer.item.Code }, callback); } function enableTransformRotate(layer, callback) { viewer.gisviewer("setTransformRotate", { active: true, layer: vectorScope.layer.item, selectFeature: true, rotatestart: function () { module.root.item.OriginalRotate = module.root.item.Rotate; }, //rotateend: function() { // delete module.root.item.OriginalRotate; //}, rotating: function (e) { var rotate = module.root.item.OriginalRotate + (e.angle / (Math.PI / 180.0)); if (rotate < 0) { rotate += 360; } $scope.$apply(function () { module.root.item.Rotate = Math.round(rotate * 10) / 10; }); } }, callback); } function deletePrintFeature() { return hidePrintLayer(); } function rotatePrintFeature(rotate, callback) { var feature = vectorScope.feature.list.items.first(); viewer.gisviewer("rotateFeature", { layerName: vectorScope.layer.item.Code, feature: feature, rotate: rotate }, callback); } function createPrintFeature(o, callback) { var printLayer = $scope.gis.layers.getAll().find(function (x) { return x.Code === layerConfig.Code; }); if (!printLayer) { throw new Error('Print layer not found'); } var center = o.center; var rotate = o.rotate || module.root.item.Rotate * Math.PI / 180.0; var template = module.root.item.PrintTemplate; var printScale = parseFloat(module.root.item.PrintSchaal); if (!template || !printScale) { if (callback) { callback(); } return; } var widthM = template.MapWidth * printScale / 1000.0; var heightM = template.MapHeight * printScale / 1000.0; var centerX = center[0]; var centerY = center[1]; var minX = centerX - (widthM / 2); var maxX = centerX + (widthM / 2); var minY = centerY - (heightM / 2); var maxY = centerY + (heightM / 2); var coordinates = [[ [centerX, maxY], [maxX, maxY], [maxX, minY], [minX, minY], [minX, maxY], [centerX, maxY] ]]; $scope.gis.helpers.geoHelper.getGeometryObject(coordinates, function (geom) { showPrintLayer(); if (vectorScope.feature.list.items.any()) { var feature = vectorScope.feature.list.items.first(); feature.geometry = geom; vectorScope.feature.update({ feature: feature }, function () { rotatePrintFeature(rotate, function () { enableTransformRotate(vectorScope.layer.item, callback); }); }); } else { vectorScope.feature.add({ features: [{ geometry: geom, properties: { readonly: true, style: { color: "#7E7EFD", fillColor: "#7E7EFD", opacity: 0.7, stroke: { width: 1, type: "arrow", iconUrl: "Content/images/arrow.png", position: "1 0.5", relativeRotation: -90, forStartSegment: true } }, selectionStyle: { stroke: { width: 1, type: "arrow", iconUrl: "Content/images/arrow.png", position: "1 0.5", relativeRotation: -90, forStartSegment: true } } } }] }, function () { rotatePrintFeature(rotate, function () { enableTransformRotate(vectorScope.layer.item, callback); }); }); } }); } function executePrint(o) { var template = o.template; var download = o.download; var schaal = o.schaal; var dpi = o.dpi; var orientation = o.orientation; var mapUrl = o.mapUrl; var parameters = o.parameters || {}; var filename = o.filename || "print-" + moment().format("YYYYMMDDhhmmss") + ".pdf"; var xsltName = o.xsltName; var xmlPath = o.xmlPath; var bulk = o.bulk; var beforeprintArgs = { templateId: template.Id, template: template, schaal: schaal, dpi: dpi, orientation: orientation, mapUrl: mapUrl, parameters: _.toArray(parameters), cancel: false, clientFilename: filename, addParameter: function(key, value) { this.parameters.push({ key: key, value: value }); } }; console.log('print.document', beforeprintArgs); return printService.beforePrint(beforeprintArgs) .then(function () { if (beforeprintArgs.cancel) { console.log('print.cancelled'); return Promise.reject({ cancel: true }); } console.log('print.end'); return module.root.handlers.printTemplate .Print({ config: { printTemplateId: beforeprintArgs.templateId, printTemplate: beforeprintArgs.template, schaal: beforeprintArgs.schaal, dpi: beforeprintArgs.dpi, orientation: beforeprintArgs.orientation, parameters: beforeprintArgs.parameters, filename: beforeprintArgs.filename, xsltName: xsltName, xmlPath: xmlPath }, mapUrl: beforeprintArgs.mapUrl }) .then(function(result) { if (!bulk) { var url = config.baseUrl + "/Handlers/FileHandler.aspx?action=" + (download ? "download" : "preview") + "&file=" + encodeURIComponent(result.Filename) + "&delete=1&clientfile=" + encodeURIComponent(beforeprintArgs.clientFilename); if (!window.open(url, "_blank")) { $translate("global.PopupBlockedWarning").then(G.handleError); } if (download) { module.root.form.hide(); } } var afterprintArgs = beforeprintArgs; //console.log("print.afterprint", afterprintArgs); //module.root.form.trigger("afterprint", afterprintArgs); return printService.afterPrint(afterprintArgs) .then(function () { return { template: beforeprintArgs.template, filename: { internal: result.Filename, client: beforeprintArgs.clientFilename } }; }); }); }); } $el .on("shown", function () { module.root.taskpane.shown(); }) .on("hidden", function () { module.root.taskpane.hidden(); }); module.root = (function () { return { handlers: { printTemplate: new $scope.handlers.PrintTemplates.PrintTemplate(config.application) }, el: $el, config: { delay: 1000, templates: [], schalen: [100, 150, 200, 250, 500, 1000, 2500, 5000], dpis: [96, 150, 200] }, item: { PrintTemplate: null, PrintSchaal: null, PrintDpi: null, Rotate: 0 }, form: $el, gisEvents: { mapload: function (e, arg) { } }, taskpane: { expanded: function () { module.root.redrawPrintFeature(); }, collapsed: function () { return deletePrintFeature(); }, shown: function () { var overlay = $el.spinnerOverlay(); var errorHandler = function (xhr) { G.handleError(xhr); overlay.hide(); }; module.root.handlers.printTemplate.List({ applicationName: config.application }, function (list) { //scope.$apply(function () { // module.root.config.templates = items.where(function (x) { return x.MapWidth && x.MapHeight; }); //}); var items = list.where(function (x) { return !x.Niscode || x.Niscode === config.niscode; }); //console.log("PRINT.LIST", { list: list, items: items, scope: $scope, config: config }); viewer.gisviewer("getCenter", function (center) { var initializeArgs = { templates: items.where(function (x) { return x.MapWidth && x.MapHeight; }), coordinate: center, schaal: 250, dpi: 150, rotate: 0, supportDpi: true, supportRotate: false }; if (items.any()) { initializeArgs.templateId = items.where(function (x) { return x.Code === "A4_LANDSCAPE"; }).select(function (x) { return x.Id; }).first() || items[0].Id; } module.root.el.trigger("openprint", initializeArgs); //console.log("print.openprint", initializeArgs); printService.onLoad(initializeArgs) .then(function () { //console.log("PRINT.OPEN", { arg: initializeArgs, scope: $scope, item: module.root.item }); $scope.$apply(function () { module.root.config.templates = initializeArgs.templates; module.root.item.PrintTemplate = initializeArgs.templates.where(function (x) { return x.Id === initializeArgs.templateId }).first(); module.root.item.PrintSchaal = initializeArgs.schaal; module.root.item.PrintDpi = initializeArgs.dpi; module.root.item.Rotate = initializeArgs.rotate; module.root.item.SupportDpi = initializeArgs.supportDpi; module.root.item.SupportRotate = initializeArgs.supportRotate; }); createPrintFeature({ center: initializeArgs.coordinate }, function () { overlay.hide(); }); }); }); }).error(errorHandler); }, hidden: function () { return deletePrintFeature(); } }, redrawPrintFeature: function (o, callback) { if (!o) { o = {}; } if (o.keepprintcenter) { module.root.getPrintCenter() .then(function (center) { o.center = center; if (o.center) { createPrintFeature(o, callback); } else { o.keepprintcenter = false; module.root.redrawPrintFeature(o, callback); } }); return; } if (!o.center) { viewer.gisviewer("getCenter", function (center) { o.center = center; createPrintFeature(o, callback); }); return; } createPrintFeature(o, callback); }, templateChanged: function () { module.root.redrawPrintFeature({ keepprintcenter: true }); }, scaleChanged: function () { module.root.redrawPrintFeature({ keepprintcenter: true }); }, rotateChanged: function () { if (module.root.item.Rotate >= 360) { module.root.item.Rotate -= 360; } if (module.root.item.Rotate < 0) { module.root.item.Rotate += 360; } var rotate = module.root.item.Rotate * Math.PI / 180.0; if (!rotate && rotate !== 0) { return; } module.root.redrawPrintFeature({ keepprintcenter: true }); }, getPrintCenter: function () { var feature = vectorScope.feature.list.items.first(); return new Promise(function (resolve) { if (!feature) { resolve(null); return; } viewer.gisviewer("getFeatureExtentCenter", { feature: feature }, function (arg) { resolve(arg.center); }); }); }, printTemplate: function (o) { console.log('print.start', o); var template = o.template; var download = o.download; var printScale = o.scale; var printDpi = o.dpi || 96; var mapUrl = o.mapUrl; var parameters = o.parameters || {}; var filename = o.filename; var center = o.center; var orientation = o.orientation; if (template.MapHeight && template.MapWidth && !center) { console.log('print', 'no center found, get center from map and retry'); return module.root.getPrintCenter() .then(function (center) { o.center = center; return module.root.printTemplate(o); }); } //console.log("PRINTING", o); function getDummyOverlay() { return { remove: function() {} }; } var overlay = !o.bulk ? $("body").progressOverlay([$scope.lang.translate("BusyPrinting", moduleName) + "..."]) : getDummyOverlay(); return new Promise(function (mainResolve, mainReject) { var executePrintParameters = { template: template, download: download, schaal: printScale, dpi: printDpi, parameters: parameters, filename: filename, xsltName: o.xsltName, xmlPath: o.xmlPath, mapUrl: mapUrl, orientation: orientation, bulk: o.bulk }; if (!printScale) { throw $scope.lang.translate("ScaleIsRequired"); } if (!template.MapHeight || !template.MapWidth) { return executePrint(executePrintParameters) .then(function (result) { mainResolve(result); }).catch(function (error) { mainReject(error); }); } var restoreLayout; var gisMap = viewer.find(".gis-map"); //if (!executePrintParameters.mapUrl) { // gisMap.css("border", "solid 1px black"); // var panelsDisabled; // var modeBottom; // var overlay2; // var elementsTopOfMap; // if (!o.bulk) { // panelsDisabled = $scope.panels.disableAllPanels(); // modeBottom = $scope.panels.getMode($scope.panels.names.BOTTOM); // if (modeBottom === $scope.panels.modes.HALF) { // $scope.panels.setMode($scope.panels.names.BOTTOM, $scope.panels.modes.FULL); // } // overlay2 = $("
").appendTo(gisMap).css({ // position: "absolute", // width: "100%", // height: "100%", // top: 0, // left: 0 // }).show(); // elementsTopOfMap = viewer.children(":visible:not(.gis-map)"); // elementsTopOfMap.hide(); // } // restoreLayout = function () { // gisMap.css("border", "none"); // if (!o.bulk) { // panelsDisabled.enable(); // if (modeBottom === $scope.panels.modes.HALF) { // $scope.panels.setMode($scope.panels.names.BOTTOM, modeBottom); // } // overlay2.remove(); // elementsTopOfMap.show(); // } // }; //} return hidePrintLayer() .then(function () { var mapCenter = viewer.gisviewer("getCenter"); var mapScale = viewer.gisviewer("getScale"); var animationDuration = viewer.gisviewer("option", "animationDuration"); var displayDpi = viewer.gisviewer("option", "displayDpi"); //96 var currentMapWidth = gisMap.width(); var currentMapHeight = gisMap.height(); var displayDpmm = displayDpi / 25.4; // 3,779527559055118 var widthMm = template.MapWidth; //257mm var heightMm = template.MapHeight; //169mm var dpiRatio = printDpi / displayDpi; //150 / 96 var printWidthPx = (widthMm * displayDpmm * dpiRatio) / window.devicePixelRatio; var printHeightPx = (heightMm * displayDpmm * dpiRatio) / window.devicePixelRatio; var isLandscape = printWidthPx > printHeightPx; var printToScreenWidthRatio = printWidthPx / currentMapWidth; var printToScreenHeightRatio = printHeightPx / currentMapHeight; var wantedScale = 1; var printToScreenRatio = isLandscape ? printToScreenWidthRatio : printToScreenHeightRatio; var scale = wantedScale / printToScreenRatio; var scaleCssValue = 'scale(' + scale + ')'; var printWindowWidth, printWindowHeight; if (isLandscape) { printWindowWidth = currentMapWidth * wantedScale; var mapToPrintRatio = printWidthPx / printWindowWidth; printWindowHeight = printHeightPx / mapToPrintRatio; } else { printWindowHeight = currentMapHeight * wantedScale; var mapToPrintRatio = printHeightPx / printWindowHeight; printWindowWidth = printWidthPx / mapToPrintRatio; } var marginLeft = (currentMapWidth - printWindowWidth) / 2; var marginTop = (currentMapHeight - printWindowHeight) / 2; gisMap.css({ transform: scaleCssValue, '-moz-transform': scaleCssValue, '-o-transform': scaleCssValue, '-webkit-transform': scaleCssValue, transformOrigin: '0% 0%', width: printWidthPx + 'px', height: printHeightPx + 'px', left: marginLeft + 'px', top: marginTop + 'px', }); var rotate = orientation * Math.PI / 180.0; var restoreViewer = function () { gisMap.css({ width: "100%", height: "100%", top: 0, left: 0 }); gisMap.css({ transform: "", '-moz-transform': "", '-o-transform': "", '-webkit-transform': "" }); viewer .gisviewer("option", "animationDuration", animationDuration) .gisviewer("option", "displayDpi", displayDpi) .gisviewer("setRotate", 0, center) .gisviewer("updateSize"); if (!download && module.root.form.is(":visible")) { showPrintLayer(); enableTransformRotate(vectorScope.layer.item); } if (overlay) { overlay.remove(); } return gisViewerManager.zoom({ center: mapCenter, scale: mapScale }); }; console.log('print.viewer.setOptions', { printDpi, rotate, center, marginLeft, marginTop }); viewer .gisviewer("option", "animationDuration", 0) .gisviewer("option", "displayDpi", printDpi) .gisviewer("setRotate", rotate, center) .gisviewer("updateSize"); var cleanupPromise = function(result) { return Promise.resolve(result) .then(function (result) { if (restoreViewer) { return restoreViewer().then(function () { restoreViewer = null; return result; }); } return result; }) .then(function (result) { if (restoreLayout) { restoreLayout(); restoreLayout = null; } return result; }); } return Promise.resolve() .then(function () { console.log('print.viewer.zoom', { center: center, scale: printScale }); return gisViewerManager.zoom({ center: center, scale: printScale }); }) .then(function () { console.log('print.viewer.refreshMap'); return gisViewerManager.refreshMap(); }) .then(function () { return new Promise(function (resolve, reject) { viewer.one("gisviewermapcomposed", function () { if (executePrintParameters.mapUrl) { console.log('print.viewer.mapComposed'); return resolve(); } return gisViewerManager.getDataUrl({ dpi: module.root.item.PrintDpi, quality: 1, type: "image/png" }) .then(function (dataUrl) { if (!dataUrl) { throw Error("Could not generate image"); } executePrintParameters.mapUrl = dataUrl; console.log('print.viewer.mapComposed'); resolve(); }) .catch(reject); }); }); }) .then(function () { return executePrint(executePrintParameters); }) .then(function (result) { return cleanupPromise(result) .then(function (result) { mainResolve(result); }); }) .catch(function (error) { return cleanupPromise() .then(function () { mainReject(error); }); }); }); }) .then(function (result) { overlay.remove(); return result; }).catch(function (error) { console.error('PRINT failed', error); overlay.remove(); throw error; }); }, printPreview: function () { //console.log('module.root.item', module.root.item); return module.root.printTemplate({ template: module.root.item.PrintTemplate, scale: module.root.item.PrintSchaal, dpi: module.root.item.PrintDpi, orientation: module.root.item.Rotate, download: false }) .catch(function (error) { G.handleError($scope.lang.translate("PrintFailed", "print")); }); } }; })(); $scope.gis.addEvents(module.root.gisEvents, moduleName); //module.root.form.autocomplete = { // schaal: // { // source: function (request, response) { // var schalen = module.root.config.schalen.select(function(x) { return { label: "" + x, value: x }; }).where(function (x) { return x.label.startsWith((request.term || '').toLowerCase()); }).orderBy(function (x) { return x.value; }); // response(schalen); // } // }, // dpi: { // source: function (request, response) { // var dpis = module.root.config.dpis.select(function (x) { return { label: "" + x, value: x }; }).where(function (x) { return x.label.startsWith((request.term || '').toLowerCase()); }).orderBy(function (x) { return x.value; }); // response(dpis); // } // } //} //fix ie11 minLength 1 erna op 0 zetten module.root.form .find("#PrintSchaal").autocomplete({ appendTo: "parent", minLength: 1, autoFocus: false, source: function (request, response) { var schalen = module.root.config.schalen.orderBy(function (x) { return x; }).select(function (x) { return "" + x; }); response(schalen); }, select: function (e, arg) { if (arg.item) { $scope.$apply(function () { module.root.item.PrintSchaal = arg.item.value; module.root.scaleChanged(); }); } } }) .on("focus", function () { $(this).autocomplete("option", { minLength: 0 }); $(this).autocomplete("search"); }) .on("click", function () { $(this).autocomplete("search"); }); module.root.form.find("#PrintDpi") .autocomplete({ appendTo: "parent", minLength: 1, autoFocus: false, source: function (request, response) { var dpis = module.root.config.dpis.orderBy(function (x) { return x; }).select(function (x) { return "" + x; }); response(dpis); }, select: function (e, arg) { if (arg.item) { $scope.$apply(function () { module.root.item.PrintDpi = arg.item.value; }); } } }) .on("focus", function () { $(this).autocomplete("option", { minLength: 0 }); $(this).autocomplete("search"); }) .on("click", function () { $(this).autocomplete("search"); }); //command commandBag.on("execute", "Print", function () { $scope.panels.show($el, "right"); }); printService.on("print-template", function (e, arg) { return module.root.printTemplate(arg.template); }); } } } PrintDirective.$inject = ["config", "commandBag", "$translate", "printService", "gisViewerManager"]; return PrintDirective; })("print"); var print = print || {}; print.PrintManager = (function () { "use strict"; function PrintTemplate(sizeInMm, marginsInMm, orientation, dpi) { Object.defineProperties(this, { _size: { value: [257, 170], writable: true }, _orientation: { value: "LANDSCAPE", writable: true }, _margins: { value: [20, 20, 20, 20], writable: true }, _dpi: { value: 96, writable: true } }); this.size = sizeInMm; this.margins = marginsInMm; this.orientation = orientation; this.dpi = dpi; } Object.defineProperties(PrintTemplate.prototype, { size: { get: function () { return this._size; }, set: function (value) { this._size = value.select(m => parseInt(m, 10)); }, enumerable: true }, orientation: { get: function () { return this._orientation; }, set: function (value) { if (value.toUpperCase() === "LANDSCAPE") { this._orientation = "LANDSCAPE"; } else if (value.toUpperCase() === "PORTRAIT") { this._orientation = "PORTRAIT"; } else { throw Error("Unknown orientation (must be LANDSCAPE OR PORTRAIT)"); } }, enumerable: true }, margins: { get: function () { return this._margins; }, set: function (value) { this._margins = value.select(m => parseInt(m, 10)); }, enumerable: true }, dpi: { get: function () { return this._dpi; }, set: function (value) { this._dpi = parseInt(value, 10); }, enumerable: true } }); function PrintImageTemplate(img, sizeInMm, marginsInMm, orientation, dpi) { PrintTemplate.call(sizeInMm, marginsInMm, orientation, dpi); Object.defineProperties(this, { _img: { value: img, writable: true } }); } PrintImageTemplate.prototype = Object.create(PrintTemplate.prototype, { constructor: { value: PrintImageTemplate }, img: { get: function () { return this._img; }, set: function (value) { this._img = value; }, enumerable: true } }); function PrintHtmlTemplate(html, inputParameters, sizeInMm, marginsInMm, orientation, dpi) { PrintTemplate.call(sizeInMm, marginsInMm, orientation, dpi); Object.defineProperties(this, { _html: { value: html, writable: true }, _inputParameters: { value: inputParameters, writable: true } }); } PrintHtmlTemplate.prototype = Object.create(PrintTemplate.prototype, { constructor: { value: PrintHtmlTemplate }, html: { get: function () { return this._html; }, set: function (value) { this._html = value; }, enumerable: true } }); function PrintManager(imageHelper) { function printImage(printIamgeTemplate) { } function printHtml(printHtmlTemplate) { } function print(printTemplate) { } } EventHandler.injectInto(PrintManager.prototype); return PrintManager; })("print"); var print = print || {}; print.PrintService = (function (/*moduleName*/) { "use strict"; function PrintService(config, $translate, gisViewerManager) { var sv = this; Object.defineProperties(sv, { _config: { value: config }, _translate: { value: $translate }, _viewer: { value: gisViewerManager } }); } PrintService.$inject = ["config", "$translate", "gisViewerManager"]; EventHandler.injectInto(PrintService.prototype); Object.defineProperties(PrintService.prototype, { constructor: { value: PrintService }, onLoad: { value: function (o) { return this.trigger("load", o); } }, beforePrint: { value: function (o) { return this.trigger("before-print", o); } }, afterPrint: { value: function (o) { return this.trigger("after-print", o); } }, printTemplate: { value: function (o) { return this.trigger("print-template", { template: o }) .then(function(result) { //console.log('PrintTemplate.result', result); return result; }); } } }); return PrintService; })("print"); var print = print || {}; print.load = function (page, map, sb) { function debug() { var debugContainer = document.getElementById("Debug"); if (debugContainer) { if (!debugContainer.innerHTML) debugContainer.innerHTML = ""; for (var i = 0; i < arguments.length; i++) { if (i) debugContainer.innerHTML += ", "; debugContainer.innerHTML += arguments[i]; } debugContainer.innerHTML += "
"; } } var pageEl = document.getElementById(page || "Page"); var mapEl = document.getElementById(map || "PrintMap"); var sbEl = document.getElementById(sb || "ScaleBar"); var pageBounds = pageEl.getBoundingClientRect(); debug("page: " + pageBounds.width + " x " + pageBounds.height); var mapImg = new Image(); var sbImg = new Image(); mapImg.onload = function () { mapEl.src = mapImg.src; debug("img: " + mapImg.width + " x " + mapImg.height); }; sbImg.onload = function () { if (sbEl) sbEl.src = sbImg.src; }; window.setMap = function (url, width, height) { mapImg.src = url; if (width) pageEl.style.width = width + "mm"; if (height) pageEl.style.height = height + "mm"; }; window.setScaleBar = function (url) { debug("scalebar: " + url); sbImg.src = url; }; }; var raadplegen = raadplegen || {}; raadplegen.RaadplegenDirective = (function (/*moduleName*/) { function RaadplegenDirective(config) { return { restrict: "EA", template: '
' }; } //function RaadplegenDirective() { // return { // restrict: "EA", // templateUrl: ModuleManager.templateUrl, // link: function (/*$scope, $el, $attr*/) { // console.debug("RAADPLEGEN", { directive: this }); // //console.log(moduleName.toUpperCase(), $.extend(true, {}, $scope), $el, $attr); // } // }; //} return RaadplegenDirective; })("raadplegen"); window.mm.Register("redlining", function (moduleName) { return { BufferDirective: function (config) { return { restrict: "EA", scope: {}, templateUrl: ModuleManager.templateUrl, link: function (scope, el) { var globalScope = scope.$parent; var viewer = globalScope.gis.viewer; var controller = new RedliningController(); scope.Buffer = null; scope.validation = new ValidationHelper(el); scope.Cancel = function () { el.remove(); } scope.Save = function () { if (!scope.validation.validate()) { return; } var bufferValue = parseFloat(scope.Buffer.replace(',', '.')); if (!bufferValue) { scope.validation.showMessage('Buffer is geen geldig getal.'); return; } viewer.gisviewer("getSelectedItems", { propertiesBitmask: 2 }, function (result) { if (!result) { return; } var wkts = _.toArray(result).selectMany(function (x) { return x.value.selectMany(function (y) { return _.toArray(y).select(function (z) { return z.value; }) }) }); if (!wkts.any()) { return; } controller.BufferGeometries(wkts, bufferValue, function (wkt) { controller.InsertPolygons({ geometry: wkt }, function () { viewer.gisviewer("refreshMap"); el.remove(); }); }); }); } } } } } }); window.mm.Register("redlining", function(moduleName) { return { MarkerPointsCirclesDirective: function(config) { return { restrict: "EA", scope: {}, templateUrl: function(el, attr) { return _.toArray(attr).where(function(x) { return x.key.endsWith("Directive") }).select(function(x) { return x.value; }).first() || attr.src; }, link: function(scope, el) { var globalScope = scope.$parent; var viewer = globalScope.gis.viewer; //var module = globalScope.modules["redlining"]; var controller = new RedliningController(); scope.Point1 = null; scope.Point2 = null; scope.Radius1 = null; scope.Radius2 = null; scope.validation = new ValidationHelper(el); var tempPointLayer = "point_temp"; globalScope.gis.createVectorScope({ target: scope }); //scope.vector.layer.createIfNotExists({ Code: redliningMarkerClientLayer, ShowInLegend: false }, function (layer) { // scope.vector.feature.addGeometry({ // geom: "POINT (143932.434779185 190729.417885283)", // layer: layer, // style: { // color: _.color.hexToRgbString("#000000"), // fillColor: _.color.hexToRgbString("#000000"), // stroke: { width: 1 }, // radius: 10 // } // }); //}); scope.GetPoint1FromSelection = function() { viewer.gisviewer("getSelectedItems", { propertiesBitmask: 2 }, function(result) { if (!result) { return; } var wkts = _.toArray(result).selectMany(function(x) { return x.value.selectMany(function(y) { return _.toArray(y).select(function(z) { return z.value; }) }) }); var pointWkt = wkts.where(function(x) { return x.contains("POINT") }).first(); if (!pointWkt) { return; } scope.Point1Wkt = pointWkt; globalScope.gis.helpers.geoHelper.getFlatCoordinates(pointWkt, function(coordinates) { scope.$apply(function() { scope.Point1 = (Math.floor(coordinates[0][0] * 100) / 100) + ',' + (Math.floor(coordinates[0][1] * 100) / 100); }); }); }); } scope.GetPoint2FromSelection = function() { viewer.gisviewer("getSelectedItems", { propertiesBitmask: 2 }, function(result) { if (!result) { return; } var wkts = _.toArray(result).selectMany(function(x) { return x.value.selectMany(function(y) { return _.toArray(y).select(function(z) { return z.value; }) }) }); var pointWkt = wkts.where(function(x) { return x.contains("POINT") }).first(); if (!pointWkt) { return; } scope.Point2Wkt = pointWkt; globalScope.gis.helpers.geoHelper.getFlatCoordinates(pointWkt, function(coordinates) { scope.$apply(function() { scope.Point2 = (Math.floor(coordinates[0][0] * 100) / 100) + ',' + (Math.floor(coordinates[0][1] * 100) / 100); }); }); }); } scope.Cancel = function () { scope.vector.layer.remove({ layerName: tempPointLayer }); el.remove(); } scope.Save = function() { var customItems = []; if (!scope.Point1) { customItems.add({ message: 'Punt 1 is verplicht.' }); } if (!scope.Point2) { customItems.add({ message: 'Punt 2 is verplicht.' }); } if (!scope.validation.validate(customItems)) { return; } globalScope.gis.helpers.geoHelper.getFlatCoordinates(scope.Point1Wkt, function(coordinates1) { globalScope.gis.helpers.geoHelper.getFlatCoordinates(scope.Point2Wkt, function(coordinates2) { controller.GetGeometriesByIntersectingCircles({ x1: coordinates1[0][0], y1: coordinates1[0][1], radius1: scope.Radius1, x2: coordinates2[0][0], y2: coordinates2[0][1], radius2: scope.Radius2 }, function(wkts) { switch (wkts.length) { case 0: alert('Geen intersections gevonden.'); break; case 1: controller.InsertMarkers({ geometry: wkts[0] }, function () { viewer.gisviewer("refreshMap"); }); break; default: scope.vector.layer.createIfNotExists({ Code: tempPointLayer, ShowInLegend: false }, function(layer) { wkts.each(function(wkt) { scope.vector.feature.addGeometry({ geom: wkt, layer: layer, style: { color: _.color.hexToRgbString("#FF0000"), fillColor: _.color.hexToRgbString("#FF0000"), stroke: { width: 1 }, radius: 10 } }); }); }); globalScope.gis.selectFeatures({ layerName: tempPointLayer, propertiesBitmask: 2 }, function(features3) { if (!features3) { return; } var geom = _.toArray(features3).selectMany(function(x) { return x.value.selectMany(function(y) { return _.toArray(y).select(function(z) { return z.value; }) }) }).first(); globalScope.gis.helpers.geoHelper.getWKT(geom, function(wkt) { scope.vector.layer.remove({ layerName: tempPointLayer }, function() { controller.InsertMarkers({ geometry: wkt }, function () { viewer.gisviewer("refreshMap", function() { viewer.gisviewer("clearSelection"); }); }); }); }); }); } //switch (wkts.length) { // case 0: // alert('Geen intersections gevonden.'); // break; // case 1: // //alles OK // break; // default: // var markerLayer = schetsenManager.data.layerNames.where(function (x) { return x.contains("marker"); }).first(); // viewer.gisviewer("filter", { // filter: [ // [markerLayer, "gid in (" + markerIds.join(",") + ")"] // ] // }, function () { // viewer.gisviewer("refreshMap", function () { // viewer.gisviewer("clearSelection", function () { // alert('Selecteer 1 van de 2 gegenereerde punten.'); // globalScope.gis.selectFeatures({ layerName: markerLayer, propertiesBitmask: 1 }, function (features3) { // if (!features3) { // return; // } // console.log('features3', features3); // var id = parseInt(_.toArray(features3).selectMany(function (x) { return x.value.selectMany(function (y) { return _.toArray(y).select(function (z) { return z.value; }) }) }).first()); // console.log('selectedId', id); // var deleteIds = markerIds.where(function (x) { return x !== id; }); // console.log('deleteIds', deleteIds); // var items = {}; // var tableName = schetsenManager.data.layers.where(function (y) { return y.Name === markerLayer; }).select(function (y) { return y.TableName; }).first(); // items[tableName] = deleteIds; // removeItems(items, function () { // viewer.gisviewer("filter", { // filter: [ // [markerLayer, null] // ] // }, function () { // viewer.gisviewer("refreshMap", function () { // viewer.gisviewer("clearSelection"); // }); // }); // }); // }); // }); // }); // }); // break; //} } ); }); }); } } } } } }); window.mm.Register("redlining", function(moduleName) { return { MarkerPointsDirectionDirective: function(config) { return { restrict: "EA", scope: {}, templateUrl: function(el, attr) { return _.toArray(attr).where(function(x) { return x.key.endsWith("Directive") }).select(function(x) { return x.value; }).first() || attr.src; }, link: function(scope, el) { var globalScope = scope.$parent; var viewer = globalScope.gis.viewer; scope.OriginalPoint = null; scope.DirectionPoint = null; scope.Distance = null; scope.validation = new ValidationHelper(el); scope.GetOriginalPointFromSelection = function() { viewer.gisviewer("getSelectedItems", { propertiesBitmask: 2 }, function(result) { if (!result) { return; } var wkts = _.toArray(result).selectMany(function(x) { return x.value.selectMany(function(y) { return _.toArray(y).select(function(z) { return z.value; }) }) }); var pointWkt = wkts.where(function(x) { return x.contains("POINT") }).first(); if (!pointWkt) { return; } scope.OriginalPointWkt = pointWkt; globalScope.gis.helpers.geoHelper.getFlatCoordinates(pointWkt, function(coordinates) { scope.$apply(function() { scope.OriginalPoint = (Math.floor(coordinates[0][0] * 100) / 100) + ',' + (Math.floor(coordinates[0][1] * 100) / 100); }); }); }); } scope.GetDirectionPointFromSelection = function() { viewer.gisviewer("getSelectedItems", { propertiesBitmask: 2 }, function(result) { if (!result) { return; } var wkts = _.toArray(result).selectMany(function(x) { return x.value.selectMany(function(y) { return _.toArray(y).select(function(z) { return z.value; }) }) }); var pointWkt = wkts.where(function(x) { return x.contains("POINT") }).first(); if (!pointWkt) { return; } scope.DirectionPointWkt = pointWkt; globalScope.gis.helpers.geoHelper.getFlatCoordinates(pointWkt, function(coordinates) { scope.$apply(function() { scope.DirectionPoint = (Math.floor(coordinates[0][0] * 100) / 100) + ',' + (Math.floor(coordinates[0][1] * 100) / 100); }); }); }); } scope.Cancel = function () { el.remove(); } scope.Save = function() { var customItems = []; if (!scope.OriginalPoint) { customItems.add({ message: 'Te verplaatsen punt is verplicht.' }); } if (!scope.DirectionPoint) { customItems.add({ message: 'Richting punt is verplicht.' }); } if (!scope.validation.validate(customItems)) { return; } globalScope.gis.helpers.geoHelper.getFlatCoordinates(scope.OriginalPointWkt, function(coordinates1) { globalScope.gis.helpers.geoHelper.getFlatCoordinates(scope.DirectionPointWkt, function(coordinates2) { G.post({ controller: "Redlining", action: "InsertMarkerBy2PointsAndDistance", parameters: { x1: coordinates1[0][0], y1: coordinates1[0][1], x2: coordinates2[0][0], y2: coordinates2[0][1], distance: scope.Distance }, success: function() { viewer.gisviewer("refreshMap"); } }); }); }); } } } } } }); function RedliningController() { this.InsertTexts = function (items, callback) { items = _.array(items); if (!items || !items.any()) { if (callback) { callback(); } return; } G.post({ controller: "Redlining", action: "InsertTexts", parameters: { items: items }, success: callback }); } this.InsertMarkers = function (items, callback) { items = _.array(items); if (!items || !items.any()) { if (callback) { callback(); } return; } G.post({ controller: "Redlining", action: "InsertMarkers", parameters: { items: items }, success: callback }); } this.InsertLines = function (items, callback) { items = _.array(items); if (!items || !items.any()) { if (callback) { callback(); } return; } G.post({ controller: "Redlining", action: "InsertLines", parameters: { items: items }, success: callback }); } this.InsertPolygons = function (items, callback) { items = _.array(items); if (!items || !items.any()) { if (callback) { callback(); } return; } G.post({ controller: "Redlining", action: "InsertPolygons", parameters: { items: items }, success: callback }); } this.RemoveItems = function (items, callback) { G.post({ controller: "Redlining", action: "RemoveItems", parameters: { items: items }, success: callback }); } this.RemoveAll = function (callback) { G.post({ controller: "Redlining", action: "RemoveAll", success: callback }); } this.GetGeometriesByIntersectingCircles = function(parameters, callback) { G.get({ controller: "Redlining", action: "GetGeometriesByIntersectingCircles", parameters: parameters, success: callback }); } this.BufferGeometries = function(geometries, buffer, callback) { G.post({ controller: "Redlining", action: "BufferGeometries", parameters: { geometries: geometries, buffer: buffer }, success: callback }); } } var redlining = redlining || {}; redlining.RedliningDirective = (function (moduleName) { "use strict"; function RedliningDirective(commandBag, $translate, $compile) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, link: function (scope, el) { //console.log(moduleName.toUpperCase(), this, $.extend(true, {}, scope)); var viewer = scope.gis.viewer; var module = scope.modules[moduleName]; var controller = new RedliningController(); function executeCommand(commandName) { var content = el.children(".content"); content.empty(); if (commandName) { var commandEl = $("
"); content.append(commandEl); $compile(commandEl)(scope); } } el .on("shown", function (/*e, arg*/) { el.children(".content").empty(); }) .on("hidden", function (/*e, arg*/) { }); module.root = (function () { return { el: el, data: { layers: null }, gisEvents: { mapload: function (/*e, arg*/) { module.root.initializeLayers(); } }, initializeLayers: function () { G.get({ controller: "Redlining", action: "CreateLayers", success: function (result) { module.root.data.layers = result.Layers; viewer.gisviewer("addLayers", { items: result.Items, position: 0 }, function () { //viewer.gisviewer("refreshLegend"); viewer.gisviewer("refreshMap"); }); } }); }, addText: function () { executeCommand(); scope.gis.digitize.point(function (arg) { var tekst = prompt("Voer de tekst in:"); if (!tekst) { return; } controller.InsertTexts({ geometry: arg.wkt, tekst: tekst }, function () { viewer.gisviewer("refreshMap"); }); }); }, addMarker: function () { executeCommand(); scope.gis.digitize.point(function (arg) { controller.InsertMarkers({ geometry: arg.wkt }, function () { viewer.gisviewer("refreshMap"); }); }); }, addLine: function () { executeCommand(); scope.gis.digitize.line(function (arg) { controller.InsertLines({ geometry: arg.wkt }, function () { viewer.gisviewer("refreshMap"); }); }); }, addPolygon: function () { executeCommand(); scope.gis.digitize.polygon(function (arg) { controller.InsertPolygons({ geometry: arg.wkt }, function () { viewer.gisviewer("refreshMap"); }); }); }, removeSelected: function () { executeCommand(); scope.gis.viewer.gisviewer("getSelectedItems", { layerNames: module.root.data.layers.select(function (x) { return x.Name; }) }, function (result) { if (!_.toArray(result).any()) { return; } var items = {}; _.toArray(result).each(function (x) { var tableName = module.root.data.layers.where(function (y) { return y.Name === x.key; }).select(function (y) { return y.TableName; }).first(); items[tableName] = result[x.key].select(function (y) { return parseInt(y["gid"]); }); }); controller.RemoveItems(items, function () { viewer.gisviewer("refreshMap"); }); }); }, removeAll: function () { executeCommand(); if (!confirm("Bent u zeker dat u alle redlining objecten wilt verwijderen?")) { return; } //viewer.gisviewer("removeLayer", { layerName: "Measure" }); //$(this).blur(); controller.RemoveAll(function () { viewer.gisviewer("refreshMap"); }); }, copySelected: function () { executeCommand(); scope.gis.viewer.gisviewer("getSelectedItems", { propertiesBitmask: 2 }, function (result) { var wkts = _.toArray(result).selectMany(function (x) { return x.value.selectMany(function (y) { return _.toArray(y).select(function (z) { return z.value; }) }) }); var markers = wkts.where(function (x) { return x.contains("POINT") }).select(function (x) { return { geometry: x }; }); var lines = wkts.where(function (x) { return x.contains("LINESTRING") }).select(function (x) { return { geometry: x }; }); var polygons = wkts.where(function (x) { return x.contains("POLYGON") }).select(function (x) { return { geometry: x }; }); controller.InsertMarkers(markers, function () { controller.InsertLines(lines, function () { controller.InsertPolygons(polygons, function () { viewer.gisviewer("refreshMap"); }); }); }); }); }, addGpsMarker: function () { executeCommand(); scope.gis.digitize.myLocation({}, function (geom) { controller.InsertMarkers({ geometry: geom.wkt }, function () { viewer.gisviewer("refreshMap"); }); }); }, addMarkerByDirection: function () { executeCommand("marker-points-direction"); }, addMarkerByCircles: function () { executeCommand("marker-points-circles"); }, createBuffer: function () { executeCommand("buffer"); } }; })(); scope.gis.addEvents(module.root.gisEvents, moduleName); //command commandBag.on("execute", "Redlining", function () { scope.panels.show(el, "right"); }); scope.modules.redlining["measure"] = { el: el.find(".measure"), color: "#FF4500", fillColor: "#FF7F50" }; var moduleScope = scope.modules.redlining.measure; function formatNumber(n) { return (Math.round(n * 100) / 100).toLocaleString("nl-BE", { minimumFractionDigits: 2 }); } $.extend(true, moduleScope, { getDistanceText: function (number) { var km = 1000, cm = 0.01; var s = formatNumber(number) + "m"; if (number < 1) { s = formatNumber(number / cm) + "cm"; } else if (number > 1000) { s = formatNumber(number / km) + "km"; } return "" + s; }, getAreaText: function (number) { var sqKm = 1000000, ha = 10000; //, a = 100; var s = formatNumber(number) + "m²"; if (number >= 10000000) { s = formatNumber(number / sqKm) + "km²"; } else if (number >= 100000) { s = formatNumber(number / ha) + "ha"; //} else if (number >= 1000) { // s = formatNumber(number / a) + "a"; } return "" + s; } }); scope.gis .createVectorScope({ target: scope.modules.redlining.measure }); var vectorScope = moduleScope.vector; $.extend(true, moduleScope, { commands: { measureDistance: function () { moduleScope.measureDistance(function (arg) { moduleScope.addDistance({ geom: arg.geom, distance: arg.distance }, function () { //console.log("ADDED", arguments); }); }); }, measureArea: function () { moduleScope.measureArea(function (arg) { moduleScope.addArea({ geom: arg.geom, area: arg.area }, function () { //console.log("ADDED", arguments); }); }); } }, setColor: function (o, callback) { if (o.color) moduleScope.color = o.color; if (o.fillColor) moduleScope.fillColor = o.fillColor; moduleScope.update(callback); }, update: function (callback) { if (vectorScope.feature.list.items.any()) { vectorScope.feature.list.items.each(function (x) { var style = x.properties.style; style.color = moduleScope.color; if (style.fillColor) style.fillColor = moduleScope.fillColor; }); vectorScope.feature.update(vectorScope.feature.list.items, function () { viewer.gisviewer("refreshMap", callback); }); } }, measureDistance: function (callback) { scope.gis.digitize.line(function (geom) { //console.log("MEASURE_DISTANCE", geom); if (!geom) { callback(null); return; } scope.gis.helpers.geoHandler.getLength(geom.wkt, function (length) { var arg = { geom: geom, distance: length }; if (callback) callback(arg); }); }); }, addDistance: function (o, callback) { var length = o.distance; controller.InsertLines({ geometry: o.geom.wkt, label: moduleScope.getDistanceText(length) }, function () { viewer.gisviewer("refreshMap", callback); }); }, measureArea: function (callback) { scope.gis.digitize.polygon(function (geom) { //console.log("MEASURE_AREA", geom); if (!geom) { callback(null); return; } scope.gis.helpers.geoHandler.getArea(geom.wkt, function (area) { var arg = { geom: geom, area: area }; if (callback) callback(arg); }); }); }, addArea: function (o, callback) { var area = o.area; controller.InsertPolygons({ geometry: o.geom.wkt, label: moduleScope.getAreaText(area) }, function () { viewer.gisviewer("refreshMap", callback); }); } }); } } } RedliningDirective.$inject = ["commandBag", "$translate", "$compile"]; return RedliningDirective; })("redlining"); //window.mm.Register("schade", function (moduleName) { // var directive = function (config, projectModuleHelper, $timeout) { // return { // restrict: "EA", // templateUrl: ModuleManager.templateUrl, // link: function ($scope, $el, $attr) { // console.log(moduleName.toUpperCase(), moduleName, $.extend(true, {}, $scope), $attr); // if (!config.gisSchadeLayername) { // console.error("GisSchadeLayerName not found in config"); // return; // } // var moduleHandlers = { // category: $scope.getEntityHandler({ Module: "Notities", Type: "Category" }), // typeschade: $scope.getEntityHandler({ Module: "Notities", Type: "TypeSchade" }), // schadegeval: $scope.getEntityHandler({ Module: "Notities", Type: "SchadeGeval" }) // }; // $.extend(moduleHandlers.schadegeval, { // Download: function (item, callback) { // return $scope.executeEntityHandler($.extend({ Action: "download", Module: "Notities", Type: "SchadeGeval" }, config, { data: { Item: item } }), callback); // }, // Rotate: function (item, angleDegrees, callback) { // return G.post({ // handler: "Handlers/SchadeGevalRotateHandler.aspx?niscode=" + config.niscode + "&angleDegrees=" + (angleDegrees || 0), // parameters: JSON.stringify(item), // success: callback, // async: true // }); // } // }); // var viewer = $scope.gis.viewer; // var fm = $el.find(".upload-container"); // var moduleScope = {}; // var emptyItem = { // Id: 0, // CreatedBy: config.user, // Created: new Date(), // Category: null, // TypeSchade: null, // Files: [], // Geometry: { // WKT: null // } // }; // $scope.modules["schade"] = $.extend(true, moduleScope, (function () { // return { // css: $.loadCss("Content/modules/schade/schade.css"), // handlers: moduleHandlers, // isReadOnly: true, // project: null, // category: { // list: { // items: [] // } // }, // typeschade: { // list: { // items: [] // } // }, // schadegeval: { // isReadOnly: true, // item: null, // show: function (item, isReadOnly) { // console.log("SG.SHOW", item, isReadOnly); // viewer.gisviewer("clearTempFeatures", function () { // $timeout(function () { // moduleScope.schadegeval.isReadOnly = !!isReadOnly && item && item.Id > 0; // moduleScope.schadegeval.timeLoaded = new Date().getTime(); // if (!item) { // moduleScope.schadegeval.item = $.extend(true, {}, emptyItem); // } else { // moduleScope.schadegeval.item = item; // if (!isReadOnly && item.Geometry && item.Geometry.WKT) { // viewer.gisviewer("createTempFeatures", { geom: item.Geometry.WKT }); // } // } // if ($scope.modules.featureinfo) { // $scope.modules.featureinfo.setListeningEnabled(moduleScope.schadegeval.isReadOnly); // } // moduleScope.schadegeval.form.setOriginal(moduleScope.schadegeval.item); // }); // $scope.panels.show($el, "bottom", "half"); // if (!isReadOnly && moduleScope.schadegeval.item.Id > 0) { // $scope.panels.freezePanel($el); // } // }); // }, // loadSelection: function (isReadOnly) { // moduleScope.schadegeval.form.geomCopied = false; // moduleScope.schadegeval.form.geomMyLocation = false; // moduleScope.schadegeval.form.geomAccuracy = null; // viewer.gisviewer("getSelectedItems", { layerName: moduleScope.schadegeval.form.layerName, propertyBitmask: 1 }, function (selection) { // if (!selection[moduleScope.schadegeval.form.layerName]) { // return; // } // var item = selection[moduleScope.schadegeval.form.layerName].first(); // if (item) { // var id = _.toArray(item).first().value; // moduleScope.schadegeval.loadById(id, isReadOnly); // } // }); // }, // loadById: function (id, isReadOnly, callback) { // moduleHandlers.schadegeval.Details(id, function (item) { // if (item) { // item.Files = (item.Files || []).select(function (item) { // return moduleScope.schadegeval.convertGisDocumentToFile(item); // }); // } // moduleScope.schadegeval.show(item, isReadOnly); // if (callback) { // callback(item); // } // }); // }, // getFileSrc: function (file) { // return config.baseUrl + "/Handlers/GisDocumentHandler.aspx?niscode=" + config.niscode + "&id=" + file.Id + "&v=" + moduleScope.schadegeval.timeLoaded; // }, // convertGisDocumentToFile: function (item, file) { // return { // file: file, // data: item, // name: item.Document, // src: file ? null : moduleScope.schadegeval.getFileSrc(item) // } // }, // form: { // el: $el, // original: null, // mapName: null, // layerName: config.gisSchadeLayername, // geomCopied: false, // geomMyLocation: false, // geomAccuracy: null, // hide: function () { // moduleScope.schadegeval.saving = false; // $scope.panels.hide($el); // }, // setOriginal: function (item) { // moduleScope.schadegeval.form.original = $.extend(true, {}, item); // }, // cancel: function () { // moduleScope.schadegeval.show(moduleScope.schadegeval.form.original, true); // $scope.panels.unfreezePanel($el); // }, // rotateFiles: function (files, callback) { // var file = files.shift(); // if (!file) { // callback(); // return; // } // moduleHandlers.schadegeval.Rotate(file.data, file.angle, function () { // moduleScope.schadegeval.form.rotateFiles(files, callback); // }); // }, // save: function (item, callback) { // console.log("SG.SAVING", item); // projectModuleHelper.checkProject() // .then(function (project) { // if (!project) { // alert("No project selected"); // return; // } // var filesToUpload = item.Files.where(function (x) { return x.file; }).select(function (x) { return x.file; }); // var filesToRotate = item.Files.where(function (x) { return !x.deleted && x.angle; }); // item.Files = item.Files.where(function (x) { return !x.deleted; }).select(function (x) { return x.data; }); // $el.spinnerOverlay(); // $scope.panels.unfreezePanel($el); // item.ProjectId = moduleScope.project.id; // if (item.Category) { // item.CategoryId = item.Category.Id; // } // if (item.TypeSchade) { // item.TypeSchadeId = item.TypeSchade.Id; // } // var errorCallback = function (xhr) { // G.handleError(xhr); // $el.removeOverlay(); // }; // console.log("SG.UPLOAD", filesToUpload); // fm.filemanager("upload", filesToUpload, function (arg) { // try { // filesToUpload.each(function (file) { // var uploadSuccess = arg.uploaded.any(function (x) { return x.name === file.alias }); // if (!uploadSuccess) { // throw "Uploaden bestand '" + file.alias + "' is mislukt."; // } // }); // } catch (e) { // errorCallback(e); // return; // } // moduleScope.schadegeval.form.rotateFiles(filesToRotate, function () { // moduleHandlers.schadegeval.Save(item, function (saved) { // //console.log("SAVED", saved); // viewer.gisviewer("refreshMap", function () { // $el.removeOverlay(); // moduleScope.schadegeval.loadById(saved.Id, true, callback); // }); // }); // }); // }); // }); // }, // remove: function (item) { // if (!confirm("Zeker verwijderen?")) // return; // $scope.panels.unfreezePanel($el); // moduleHandlers.schadegeval.Delete(item, function () { // viewer.gisviewer("refreshMap", function () { // moduleScope.schadegeval.show(null, true); // moduleScope.schadegeval.form.hide(); // }); // }); // } // }, // list: { // items: [], // selected: [], // find: function (id) { // return moduleScope.schadegeval.list.items.first(function (x) { return x.Id === id; }); // } // }, // browseFile: function () { // fm.filemanager("browse"); // }, // openFile: function (file) { // window.open(file.src, "_blank"); // }, // setGeometry: function (o, callback) { // //console.log("S.SET_GEOMETRY", o); // var schadegeval = o.schadegeval; // var geomType = o.type; // moduleScope.schadegeval.form.geomCopied = false; // moduleScope.schadegeval.form.geomMyLocation = false; // moduleScope.schadegeval.form.geomAccuracy = null; // function setGeom(geom) { // if (geom) { // viewer.gisviewer("clearTempFeatures", function () { // viewer.gisviewer("createTempFeatures", { geom: geom.wkt }, function () { // $timeout(function () { // moduleScope.schadegeval.item = schadegeval; // schadegeval.Geometry.WKT = geom.wkt; // }) // .then(callback); // }); // }); // } // } // switch (geomType) { // case "LineString": // case "MultiLineString": // $scope.gis.digitize.line(function (geom) { // setGeom(geom); // }); // break; // case "Polygon": // case "MultiPolygon": // $scope.gis.digitize.polygon(function (geom) { // setGeom(geom); // }); // break; // case "Copy": // $scope.gis.digitize.copy(function (geom) { // moduleScope.schadegeval.form.geomCopied = true; // setGeom(geom); // }); // break; // case "MyLocation": // $scope.gis.digitize.myLocation(function (geom, accuracy) { // viewer.gisviewer("zoom", { center: geom.geoJson.coordinates }, function () { // moduleScope.schadegeval.form.geomMyLocation = true; // moduleScope.schadegeval.form.geomAccuracy = accuracy; // setGeom(geom); // }); // }); // break; // default: //"Point" // $scope.gis.digitize.point(function (geom) { // setGeom(geom); // }); // break; // } // }, // download: function (item, callback) { // moduleHandlers.schadegeval.Download(item, function (data) { // console.log("DOWNLOAD", data); // window.open(config.baseUrl + "/Handlers/FileHandler.aspx?action=download&file=" + encodeURIComponent(data.filename) + "&delete=1&clientfile=" + encodeURIComponent("schadegevallen-" + item.Id + ".zip")); // if (callback) { // callback(); // } // }); // } // }, // gisEvents: { // mapload: function (e, arg) { // moduleScope.schadegeval.form.mapName = arg.mapinfo.Name; // var layerName = config.gisSchadeLayername; // moduleScope.schadegeval.form.layerName = arg.layers // .where(function (x) { // if (layerName.startsWith("*") && layerName.endsWith("*")) { // return x.Code.contains(layerName.trim("*")); // } else if (layerName.endsWith("*")) { // return x.Code.startsWith(layerName.trim("*")); // } else if (layerName.startsWith("*")) { // return x.Code.endsWith(layerName.trim("*")); // } else // return x.Code === layerName; // }) // .select(function (x) { return x.Code; }) // .first(); // console.log("SG", arg, moduleScope.schadegeval.form.layerName); // if ($scope.modules.featureinfo) { // $scope.modules.featureinfo.registerShortcut([moduleScope.schadegeval.form.layerName], function () { // moduleScope.schadegeval.loadSelection(true); // }); // } // $scope.panels.container.on("closed hidden", function (e, arg) { // if (arg && arg.panel === "bottom") { // viewer.gisviewer("clearTempFeatures"); // } // }); // $timeout(function () { // moduleScope.isReadOnly = !config.roles || !config.roles.any(function (x) { // return x.roleName === moduleName + "_editeren"; // }); // }); // //Projects // projectModuleHelper.attachToProject(moduleScope.gisfoto.layerNames); // }, // featurechange: function (e, arg) { // var geom = arg.features.select(function (x) { return x.geometry; }).first(); // $scope.gis.helpers.geoHelper.GetWKT(geom, function (wkt) { // moduleScope.schadegeval.item.Geometry.WKT = wkt; // }); // } // } // }; // })()); // ModuleManager.registerCommands(moduleName, [ // { // name: "AddSchadeGeval", // icon: "glyphicon glyphicon-warning-sign", // title: function () { // return $scope.lang.translate("Damages", moduleName); // }, // callback: function () { // projectModuleHelper.checkProject() // .then(function (project) { // if (!project) { // return; // } // moduleScope.project = project; // moduleScope.schadegeval.show($.extend(true, {}, emptyItem), false); // }); // } // }]); // fm // .filemanager({ // files: [], // uploadUrl: "Upload/Html5Upload.aspx?niscode=" + config.niscode, // overwrite: true, // multiple: true, // autoUpload: true, // droppable: true, // update: function (e, arg) { // var item = moduleScope.schadegeval.item; // if (!item) { // return; // } // $timeout(function () { // arg.added.each(function (x) { // var gisDocument = { // Kaart: moduleScope.schadegeval.form.mapName, // Laag: moduleScope.schadegeval.form.layerName, // Feature: item.Id, // Gebruiker: config.user, // Document: null // } // item.Files.add(moduleScope.schadegeval.convertGisDocumentToFile(gisDocument, x)); // }); // }); // } // }); // $scope.gis.addEvents(moduleScope.gisEvents, moduleName); // moduleHandlers.category.List({}, function (categories) { // console.log("S.CATEGORIES", categories); // moduleHandlers.typeschade.List({}, function (types) { // console.log("S.TYPES", types); // $timeout(function () { // moduleScope.category.list.items = categories; // moduleScope.typeschade.list.items = types; // }); // }); // }); // } // }; // }; // directive.$inject = ["config", "projectModuleHelper", "$timeout"]; // return { SchadeDirective: directive }; //}); var schetsen = schetsen || {}; schetsen.Bootstrapper = (function (moduleName) { "use strict"; function bootstrapper(config, schetsenManager) { var bs = this; this.initCommands = function (commandBag, $translate) { commandBag.add([{ name: moduleName + ".Open", content: '', title: function () { return $translate("schetsen.Schetsen"); } }]); return Promise.resolve(bs); }; this.initProjects = function (projectManager, gisViewerManager) { projectManager .on("change-loaded-items", function (e, arg) { //console.log("NB.CHANGE_LOADED_PROJECTS", { evt: e, arg: arg }); var t0 = performance.now(); var projectIds = arg.items.select(function (x) { return x.id; }); var filter = "project_id NULL" + (projectIds.any() ? " OR project_id IN (" + projectIds.join(',') + ")" : ""); var layerNames = schetsenManager.data.layerNames; var mapFilter = layerNames.aggregate(function (r, x) { r[x] = filter; return r; }, {}); return gisViewerManager.filter({ filter: mapFilter }) .then(function (result) { var t1 = performance.now(); //console.log("PERFORMANCE", Math.round(t1 - t0), "ProjectManager[change-loaded-items].Schetsen[GisViewerManager.filter]"); return result; }); }) // zoom to project(s) .on("request-extents", function (e, arg) { //console.debug("SBP.REQUEST_EXTENTS", { arg: arg }); var projects = arg.items; var projectIds = projects.select(function (x) { return x.id; }); return schetsenManager.getExtent({ projectIds: projectIds }) .then(function (extent) { arg.addExtent(extent); return extent; }); }); return Promise.resolve(bs); }; this.initCss = function () { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); return Promise.resolve(bs); }; this.initElements = function (commandBag, panelHelper) { //var pm = new PanelManager($(".content-container")); var $el = $("#SchetsenContainer"); var lastMode = "full"; //window.innerWidth < 1280 ? "half" : "full"; commandBag.on("execute", moduleName + ".Open", function () { return panelHelper .show({ el: $el, panel: "right", mode: lastMode }); }); panelHelper.on("resize", function (e, arg) { if (arg && arg.panel === "right" && $el.is(":visible")) { lastMode = arg.mode; } }); return Promise.resolve(bs); }; this.initLayers = function (gisViewerManager) { return schetsenManager.init() .then(function (result) { return gisViewerManager.addLayers({ items: result.Items }); }) .then(function() { return bs; }); } } return bootstrapper; })("schetsen"); var schetsen = schetsen || {}; schetsen.MarkerPointsCirclesDirective = (function () { function MarkerPointsCirclesDirective($timeout, schetsenService, projectManager, gisViewer, infoManager) { return { restrict: "EA", scope: {}, templateUrl: function (el, attr) { return _.toArray(attr).where(function (x) { return x.key.endsWith("Directive") }).select(function (x) { return x.value; }).first() || attr.src; }, link: function ($scope, el) { var globalScope = $scope.$parent; $scope.Point1 = null; $scope.Point2 = null; $scope.Radius1 = null; $scope.Radius2 = null; $scope.validation = new ValidationHelper(el); var tempPointLayer = "point_temp"; globalScope.gis.createVectorScope({ target: $scope, layer: { Code: tempPointLayer, ShowInLegend: false }, featureStyle: { color: "#FF0000", fillColor: "#FF0000", stroke: { width: 1 }, radius: 10 } }); function resetTempLayer(callback) { $scope.vector.feature.remove({ features: $scope.vector.feature.list.items }, callback); } function fillTempLayer(callback) { resetTempLayer(function () { if ($scope.Point1Wkt) { $scope.vector.feature.addGeometry({ geom: $scope.Point1Wkt }); } if ($scope.Point2Wkt) { $scope.vector.feature.addGeometry({ geom: $scope.Point2Wkt }); } if (callback) { callback(); } }); } function userSelectFeature(o) { o = o || {}; var layerNames = o.layerNames; if (o.layerName) { layerNames = [o.layerName]; } if (!layerNames || !layerNames.length) { return Promise.reject("No layerName(s) specified"); } var message = o.message || globalScope.lang.translate('SelectObjectInMap'); return new Promise(function (resolve) { var selectionchanged = function (e, arg) { if (arg.selection && arg.selection.features) { for (var i = 0; i < layerNames.length; i++) { var layerFeatures = arg.selection.features[layerNames[i]]; if (layerFeatures) { var feature = layerFeatures[0]; if (feature) { resolve(feature); infoManager.cancel(); return; } } } } selectFeatures(o).then(function (result) { resolve(result); }); }; infoManager.push({ text: message, cancel: function () { gisViewer.off("selection-change", selectionchanged); resolve(null); }, extra: { toggleUi: true } }); gisViewer.once("selection-change", selectionchanged); }); } el //.on("shown", function () { //}) .on("hidden", function (e, arg) { resetTempLayer(arg.callback); }); NavigationManager.container .on("command.executing", function () { resetTempLayer(); }); $scope.GetPoint1FromSelection = function () { globalScope.gis.digitize.copy(function (geom) { if (!geom) { return; } if (geom.geoJson.type !== 'MultiPoint' && geom.geoJson.type !== 'Point') { return; } var pointWkt = geom.wkt; $scope.Point1Wkt = pointWkt; fillTempLayer(); globalScope.gis.helpers.geoHelper.getFlatCoordinates(pointWkt, function (coordinates) { $timeout(function () { var coordinate = coordinates[0]; $scope.Point1 = (Math.floor(coordinate[0] * 100) / 100) + ',' + (Math.floor(coordinate[1] * 100) / 100); }); }); }); } $scope.GetPoint2FromSelection = function () { globalScope.gis.digitize.copy(function (geom) { if (!geom) { return; } if (geom.geoJson.type !== 'MultiPoint' && geom.geoJson.type !== 'Point') { return; } var pointWkt = geom.wkt; $scope.Point2Wkt = pointWkt; fillTempLayer(); globalScope.gis.helpers.geoHelper.getFlatCoordinates(pointWkt, function (coordinates) { $timeout(function () { var coordinate = coordinates[0]; $scope.Point2 = (Math.floor(coordinate[0] * 100) / 100) + ',' + (Math.floor(coordinate[1] * 100) / 100); }); }); }); } //$scope.Cancel = function () { // $scope.vector.layer.remove({ // layerName: tempPointLayer // }); // el.remove(); //} $scope.Save = function () { var customItems = []; if (!$scope.Point1) { customItems.add({ message: globalScope.lang.translate('PointXIsRequired').inject({ 'x': 1 }) }); } if (!$scope.Point2) { customItems.add({ message: globalScope.lang.translate('PointXIsRequired').inject({ 'x': 2 }) }); } if (!$scope.validation.validate(customItems)) { return; } globalScope.gis.helpers.geoHelper.getFlatCoordinates($scope.Point1Wkt, function (coordinates1) { globalScope.gis.helpers.geoHelper.getFlatCoordinates($scope.Point2Wkt, function (coordinates2) { G.get({ controller: "Redlining", action: "GetGeometriesByIntersectingCircles", parameters: { x1: coordinates1[0][0], y1: coordinates1[0][1], radius1: $scope.Radius1, x2: coordinates2[0][0], y2: coordinates2[0][1], radius2: $scope.Radius2 }, success: function (wkts) { switch (wkts.length) { case 0: alert(globalScope.lang.translate('NoIntersectionsFound')); break; case 1: var overlay = el.spinnerOverlay(); schetsenService.insertPunten({ projectId: projectManager.activeId, items: [{ geometry: wkts[0] }] }) .then(function () { return gisViewer.refreshMap(); }) .then(function () { overlay.remove(); }) .catch(function (err) { overlay.remove(); G.handleError(err); }); break; default: resetTempLayer(function () { wkts.each(function (wkt) { $scope.vector.feature.addGeometry({ geom: wkt }); }); userSelectFeature({ message: globalScope.lang.translate('SelectXOfYPoints').inject({ 'x': 1, 'y': 2 }), layerName: tempPointLayer }).then(function (feature) { resetTempLayer(); if (!feature) { return; } var geom = feature.get('data-item').geometry; if (!geom) { return; } var overlay = el.spinnerOverlay(); globalScope.gis.helpers.geoHelper.getWKT(geom, function (wkt) { schetsenService.insertPunten({ projectId: projectManager.activeId, items: [{ geometry: wkt }] }) .then(function () { return gisViewer.refreshMap(); }) .then(function () { return gisViewer.clearSelection(); }) .then(function () { overlay.remove(); }) .catch(function (err) { overlay.remove(); G.handleError(err); }); }); }); }); } } }); }); }); } } } } MarkerPointsCirclesDirective.$inject = ["$timeout", "schetsenService", "projectManager", "gisViewerManager", "infoContainerManager"]; return MarkerPointsCirclesDirective; })("schetsen"); var schetsen = schetsen || {}; schetsen.MarkerPointsDirectionDirective = (function () { function MarkerPointsDirectionDirective($timeout, schetsenService, projectManager, gisViewer) { return { restrict: "EA", scope: {}, templateUrl: function (el, attr) { return _.toArray(attr).where(function (x) { return x.key.endsWith("Directive") }).select(function (x) { return x.value; }).first() || attr.src; }, link: function ($scope, el) { var globalScope = $scope.$parent; $scope.OriginalPoint = null; $scope.DirectionPoint = null; $scope.Distance = null; $scope.validation = new ValidationHelper(el); var tempPointLayer = "point_temp"; globalScope.gis.createVectorScope({ target: $scope, layer: { Code: tempPointLayer, ShowInLegend: false }, featureStyle: { color: "#FF0000", fillColor: "#FF0000", stroke: { width: 1 }, radius: 10 } }); function resetTempLayer(callback) { $scope.vector.feature.remove({ features: $scope.vector.feature.list.items }, callback); } function fillTempLayer(callback) { resetTempLayer(function () { if ($scope.OriginalPointWkt) { $scope.vector.feature.addGeometry({ geom: $scope.OriginalPointWkt }); } if ($scope.DirectionPointWkt) { $scope.vector.feature.addGeometry({ geom: $scope.DirectionPointWkt }); } if (callback) { callback(); } }); } el //.on("shown", function () { //}) .on("hidden", function () { resetTempLayer(); }); NavigationManager.container .on("command.executing", function () { resetTempLayer(); }); $scope.GetOriginalPointFromSelection = function () { globalScope.gis.digitize.copy(function (geom) { if (!geom) { return; } if (geom.geoJson.type !== 'MultiPoint' && geom.geoJson.type !== 'Point') { return; } var pointWkt = geom.wkt; $scope.OriginalPointWkt = pointWkt; fillTempLayer(); globalScope.gis.helpers.geoHelper.getFlatCoordinates(pointWkt, function (coordinates) { $timeout(function () { var coordinate = coordinates[0]; $scope.OriginalPoint = (Math.floor(coordinate[0] * 100) / 100) + ',' + (Math.floor(coordinate[1] * 100) / 100); }); }); }); } $scope.GetDirectionPointFromSelection = function () { globalScope.gis.digitize.copy(function (geom) { if (!geom) { return; } if (geom.geoJson.type !== 'MultiPoint' && geom.geoJson.type !== 'Point') { return; } var pointWkt = geom.wkt; $scope.DirectionPointWkt = pointWkt; fillTempLayer(); globalScope.gis.helpers.geoHelper.getFlatCoordinates(pointWkt, function (coordinates) { $timeout(function () { var coordinate = coordinates[0]; $scope.DirectionPoint = (Math.floor(coordinate[0] * 100) / 100) + ',' + (Math.floor(coordinate[1] * 100) / 100); }); }); }); } //$scope.Cancel = function () { // el.remove(); //} $scope.Save = function () { //var customItems = []; //if (!$scope.OriginalPoint) { // customItems.add({ message: 'Te verplaatsen punt is verplicht.' }); //} //if (!$scope.DirectionPoint) { // customItems.add({ message: 'Richting punt is verplicht.' }); //} //if (!$scope.validation.validate(customItems)) { // return; //} globalScope.gis.helpers.geoHelper.getFlatCoordinates($scope.OriginalPointWkt, function (coordinates1) { globalScope.gis.helpers.geoHelper.getFlatCoordinates($scope.DirectionPointWkt, function (coordinates2) { schetsenService.insertMarkerBy2PointsAndDistance({ projectId: projectManager.activeId, x1: coordinates1[0][0], y1: coordinates1[0][1], x2: coordinates2[0][0], y2: coordinates2[0][1], distance: $scope.Distance }) .then(function () { resetTempLayer(); return gisViewer.refreshMap(); }) .then(function () { overlay.remove(); }) .catch(function (err) { overlay.remove(); G.handleError(err); }); }); }); } } } } MarkerPointsDirectionDirective.$inject = ["$timeout", "schetsenService", "projectManager", "gisViewerManager"]; return MarkerPointsDirectionDirective; })("schetsen"); var schetsen = schetsen || {}; schetsen.SchetsenController = (function (moduleName) { function schetsenController(projectManager) { Object.defineProperties(this, { _projectManager: { value: projectManager }, project: { get: function () { return projectManager.activeItem; }, enumerable: true } }); } return schetsenController; })("schetsen"); var schetsen = schetsen || {}; schetsen.SchetsenDirective = (function (moduleName) { "use strict"; function schetsenDirective($compile, schetsenService, schetsenManager, gisViewer, infoManager) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, controller: 'schetsenController as ctrl', link: function ($scope, $el, $attr, $ctrl) { //console.log("SCHETSEN", $scope); if (!$scope.modules[moduleName]) { $scope.modules[moduleName] = {}; } var module = $scope.modules[moduleName]; var tempLayer = "schetsen_temp"; $scope.gis.createVectorScope({ target: module, layer: { Code: tempLayer, ShowInLegend: false }, featureStyle: { color: "#FF0000", fillColor: "#FF0000", stroke: { width: 1 }, radius: 10 } }); var setAction = function (action) { module.action = action; } function executeCommand(commandName) { var content = $el.find(".command-content"); $scope.application.hide(content.children()); content.empty(); module.commandName = commandName; //viewer.gisviewer("cancelDigitizing"); infoManager.cancel(); setAction(commandName); if (commandName) { var commandEl = $("
"); content.append(commandEl); $scope.application.show(commandEl); $compile(commandEl)($scope); } } function resetTempLayer(callback) { if (module.vector.feature.list.items.length === 0) { if (callback) { callback(); } return; } module.vector.feature.remove({ features: module.vector.feature.list.items }, callback); } $el .on("shown", function () { $el.find(".command-content").empty(); //featureInfoBag.setDisabled(true); }) .on("hidden", function () { resetTempLayer(function () { var callback = function () { //featureInfoBag.setDisabled(false); }; //force hidden trigger of open command var content = $el.find(".command-content"); if (content.children().length > 0) { $scope.application.hide(content.children(), callback); } else { callback(); } }); }) .on("activated", function () { //featureInfoBag.setDisabled(true); }) .on("deactivated", function () { //featureInfoBag.setDisabled(false); }); NavigationManager.container .on("command.executing", function () { if ($el.is(":visible")) { resetTempLayer(); } }); module.root = (function () { return { el: $el, data: { layers: null, action: null }, executeCommand: executeCommand, addText: function () { executeCommand(); setAction('addText'); $scope.gis.digitize.point(function (arg) { setAction(); if (!arg) { return; } var tekst = prompt($scope.lang.translate("InsertText") + ":"); if (!tekst) { return; } var overlay = $el.spinnerOverlay(); schetsenService.insertPunten({ projectId: $ctrl.project.id, items: [{ geometry: arg.wkt, label: tekst }] }) .then(function () { return gisViewer.refreshMap(); }) .then(function () { overlay.remove(); }) .catch(function (err) { overlay.remove(); G.handleError(err); }); }); }, addPoint: function () { executeCommand(); setAction('addPoint'); $scope.gis.digitize.point(function (arg) { setAction(); if (!arg) { return; } var overlay = $el.spinnerOverlay(); schetsenService.insertPunten({ projectId: $ctrl.project.id, items: [{ geometry: arg.wkt }] }) .then(function () { return gisViewer.refreshMap(); }) .then(function () { overlay.remove(); }) .catch(function (err) { overlay.remove(); G.handleError(err); }); }); }, addMyLocation: function () { executeCommand(); setAction('addMyLocation'); $scope.gis.position.current({}, function (arg) { setAction(); var overlay = $el.spinnerOverlay(); schetsenService.insertPunten({ projectId: $ctrl.project.id, items: [{ geometry: arg.geom.wkt }] }) .then(function () { return gisViewer.refreshMap(); }) .then(function () { return gisViewer.zoom({ center: arg.geom.geoJson.coordinates, scale: 500 }); }) .then(function () { overlay.remove(); }) .catch(function (err) { overlay.remove(); G.handleError(err); }); }); }, addLine: function () { executeCommand(); setAction('addLine'); $scope.gis.digitize.line(function (arg) { setAction(); if (!arg) { return; } var overlay = $el.spinnerOverlay(); schetsenService.insertLijnen({ projectId: $ctrl.project.id, items: [{ geometry: arg.wkt }] }) .then(function () { return gisViewer.refreshMap(); }) .then(function () { overlay.remove(); }) .catch(function (err) { overlay.remove(); G.handleError(err); }); }); }, addPolygon: function () { executeCommand(); setAction('addPolygon'); $scope.gis.digitize.polygon(function (arg) { setAction(); if (!arg) { return; } var overlay = $el.spinnerOverlay(); schetsenService.insertPolygonen({ projectId: $ctrl.project.id, items: [{ geometry: arg.wkt }] }) .then(function () { return gisViewer.refreshMap(); }) .then(function () { overlay.remove(); }) .catch(function (err) { overlay.remove(); G.handleError(err); }); }); }, removeSelected: function () { executeCommand(); setAction('removeSelected'); $scope.gis.viewer.gisviewer("getSelectedItems", { layerNames: schetsenManager.data.layerNames }, function (result) { setAction(); if (!_.toArray(result).any()) { $el.messageOverlay($scope.lang.translate("SelectObject", moduleName)); return; } var overlay = $el.spinnerOverlay(); var items = {}; _.toArray(result).each(function (x) { //var layerName = schetsenManager.data.layerNames.where(function (layerName) { return layerName === x.key; }).first(); items[x.key] = result[x.key].select(function (y) { return parseInt(y["id"]); }); }); schetsenService.removeItems({ items: items }) .then(function () { return gisViewer.refreshMap(); }) .then(function () { overlay.remove(); }) .catch(function (err) { overlay.remove(); G.handleError(err); }); }); }, removeAll: function () { executeCommand(); setAction('removeAll'); if (!confirm($scope.lang.translate("ConfirmDeleteAllSchetsObjects", moduleName))) { return; } setAction(); var overlay = $el.spinnerOverlay(); schetsenService.removeAll({ projectId: $ctrl.project.id }) .then(function () { return gisViewer.refreshMap(); }) .then(function () { overlay.remove(); }) .catch(function (err) { overlay.remove(); G.handleError(err); }); }, addGpsMarker: function () { executeCommand(); setAction('addGpsMarker'); $scope.gis.digitize.myLocation({}, function (geom) { setAction(); var overlay = $el.spinnerOverlay(); schetsenService.insertPunten({ projectId: $ctrl.project.id, items: [{ geometry: geom.wkt }] }) .then(function () { return gisViewer.zoom({ center: geom.geoJson.coordinates, scale: 500 }); }) .then(function () { overlay.remove(); }) .catch(function (err) { overlay.remove(); G.handleError(err); }); }); }, addMaatlijn: function () { executeCommand(); setAction('addMaatlijn'); $scope.gis.digitize.point({ message: $scope.lang.translate("DigitizeStartPoint") }, function (arg) { if (!arg) { setAction(); return; } module.vector.feature.addGeometry({ geom: arg.wkt }, function () { $scope.gis.digitize.point({ message: $scope.lang.translate("DigitizeEndPoint") }, function (arg2) { resetTempLayer(); if (!arg2) { setAction(); return; } var tekst = prompt($scope.lang.translate("InsertText") + ":"); setAction(); if (!tekst) { return; } $scope.gis.helpers.geoHelper.getFlatCoordinates(arg.wkt, function (coordinates1) { $scope.gis.helpers.geoHelper.getFlatCoordinates(arg2.wkt, function (coordinates2) { var coordinates = [[coordinates1[0][0], coordinates1[0][1]], [coordinates2[0][0], coordinates2[0][1]]]; $scope.gis.helpers.geoHelper.getWKT(coordinates, function (wkt) { var overlay = $el.spinnerOverlay(); schetsenService.insertLijnen({ projectId: $ctrl.project.id, items: [{ geometry: wkt, label: tekst }] }) .then(function () { return gisViewer.refreshMap(); }) .then(function () { overlay.remove(); }) .catch(function (err) { overlay.remove(); G.handleError(err); }); }); }); }); }); }); }); }, addPointByDirection: function () { executeCommand("marker-points-direction"); }, addPointByCircles: function () { executeCommand("marker-points-circles"); } }; })(); $scope.gis.addEvents(module.root.gisEvents, moduleName); } } } schetsenDirective.$inject = ["$compile", "schetsenService", "schetsenManager", "gisViewerManager", "infoContainerManager"]; return schetsenDirective; })("schetsen"); var schetsen = schetsen || {}; schetsen.SchetsenManager = (function () { "use strict"; function schetsenManager(service) { this._service = service; this.data = { layerNames: [] }; } Object.defineProperties(schetsenManager.prototype, { constructor: { value: schetsenManager }, init: { value: function () { var me = this; //console.log("SCHETSEN.INIT", { o: o, mgr: this }); //if ("canEdit" in o) { // this.canEdit = !!o.canEdit; //} return me._service.createLayers() .then(function (result) { //data.layers = result.Layers; me.data.layerNames = result.Layers.select(function (x) { return x.Name; }); return result; }); } }, getExtent: { value: function (o) { var me = this; return Promise.all(o.projectIds.map(function (projectId) { return me._service.getProjectBounds({ id: projectId }); })).then(function (bounds) { var extents = bounds.where(function (x) { return x; }).select(function (x) { return [x.BotLeft.X, x.BotLeft.Y, x.TopRight.X, x.TopRight.Y]; }); if (!extents.length) { return null; } return [ extents.min(function (x) { return x[0] }), extents.min(function (x) { return x[1] }), extents.max(function (x) { return x[2] }), extents.max(function (x) { return x[3] }) ]; }); } } }); return schetsenManager; })("schetsen"); var schetsen = schetsen || {}; schetsen.SchetsenService = (function () { function schetsenService(config, $http) { EntityServiceBase.call(this, { niscode: config.niscode, url: config.baseUrl + "/GeoRest/Schetsen" }, $http); } schetsenService.prototype = Object.create(EntityServiceBase.prototype, { constructor: { value: schetsenService }, createLayers: { value: function () { var sv = this; return sv._get('CreateLayers').then(sv._getResponseData); } }, removeItems: { value: function (o) { var sv = this; return sv._post('RemoveItems', o).then(sv._getResponseData); } }, removeAll: { value: function (o) { var sv = this; return sv._post('RemoveAll', o).then(sv._getResponseData); } }, insertPunten: { value: function (o) { var sv = this; return sv._post('InsertPunten', o).then(sv._getResponseData); } }, insertLijnen: { value: function (o) { var sv = this; return sv._post('InsertLijnen', o).then(sv._getResponseData); } }, insertPolygonen: { value: function (o) { var sv = this; return sv._post('InsertPolygonen', o).then(sv._getResponseData); } }, insertMarkerBy2PointsAndDistance: { value: function (o) { var sv = this; return sv._post('InsertMarkerBy2PointsAndDistance', o).then(sv._getResponseData); } }, getProjectBounds: { value: function (o) { var sv = this; return sv._get('GetProjectBounds', o).then(sv._getResponseData); } } }); return schetsenService; })("schetsen"); var security = security || {}; security.SecurityManager = (function () { "use strict"; function SecurityManager(config) { this.config = config; } SecurityManager.$inject = ["config"]; Object.defineProperties(SecurityManager.prototype, { hasRole: { value: function () { var moduleName = arguments[0]; var roleName = arguments[1]; if (roleName) { roleName = moduleName + "_" + roleName; } else { roleName = moduleName; } //console.log("SM.HAS_ROLE", { roles: this.config.roles, moduleName: moduleName, roleName: roleName }); return (this.config.roles || []).any(function (x) { return x.roleName === roleName; }); } }, hasMultipleModules: { value: function () { return (this.config.roles || []).where(function (x) { return x.roleName.indexOf("module_") === 0 && x.roleName !== 'module_global'; }).length > 1; } } }); return SecurityManager; })(); var security = security || {}; security.SelectUserController = (function () { "use strict"; function SelectUserController(config, $translate, securityUserService) { var vm = this; Object.defineProperties(vm, { _config: { value: config }, _translate: { value: $translate }, _securityUserService: { value: securityUserService }, items: { value: [], writable: true }, selected: { value: [] }, filter: { value: { organizationNiscode: null } } }); } SelectUserController.$inject = ["config", "$translate", "securityUserService"]; SelectUserController.prototype = Object.create(ControllerBase.prototype); EventHandler.injectInto(SelectUserController.prototype); Object.defineProperties(SelectUserController.prototype, { constructor: { value: SelectUserController }, init: { value: function () { var vm = this; vm._securityUserService.list(vm.filter).then(function (items) { if (vm.blacklistUsernames) { items = items.where(function (x) { return !vm.blacklistUsernames.contains(x.username); }); } vm.items = items.orderBy(function (x) { return (x.isGroup ? "0" : "1") + vm._securityUserService.getUserDisplay(x); }); }); } }, toggleSelected: { value: function (item) { var vm = this; if (vm.selected.contains(item)) { vm.selected.remove(item); } else { vm.selected.add(item); } } }, isSelected: { value: function(item) { var vm = this; return vm.selected.contains(item); } } }); return SelectUserController; })("security"); var security = security || {}; security.SelectUserDirective = (function () { function SelectUserDirective(config) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, controller: "selectUserController", controllerAs: "ctrl", scope: { eventTarget: "=", onSelect: "=", onCancel: "=", blacklistUsernames: "=", niscode: "=", isGroup: "=" }, link: function ($scope, $el, $attr, $ctrl) { $scope.cancel = function () { if (!$scope.onCancel) { throw new Error("onCancel is not implemented"); } $scope.onCancel.call($scope.eventTarget || $scope); } $ctrl.blacklistUsernames = $scope.blacklistUsernames; $ctrl.filter.organizationNiscode = $scope.niscode || config.niscode; $ctrl.filter.isGroup = $scope.isGroup || null; $scope.confirm = function () { if (!$scope.onSelect) { throw new Error("onSelect is not implemented"); } $scope.onSelect.call($scope.eventTarget || $scope, { selected: $ctrl.selected }); } $scope.itemsFilter = function (item) { var q = ($ctrl.filter.q || '').toLowerCase(); return item.username.toLowerCase().contains(q) || (item.firstName || '').toLowerCase().contains(q) || (item.lastName || '').toLowerCase().contains(q); } $el.find(".list-filter input").focus(); $ctrl.init(); } }; } SelectUserDirective.$inject = ["config"]; return SelectUserDirective; })("security"); var security = security || {}; security.UserFormController = (function () { "use strict"; function UserFormController(config, $translate, securityUserService, langConfig, indexService) { var vm = this; Object.defineProperties(vm, { _config: { value: config }, _translate: { value: $translate }, _securityUserService: { value: securityUserService }, _langConfig: { value: langConfig }, _indexService: { value: indexService } }); } UserFormController.$inject = ["config", "$translate", "securityUserService", "langConfig", "indexService"]; UserFormController.prototype = Object.create(ControllerBase.prototype, { constructor: { value: UserFormController } }); Object.defineProperties(UserFormController.prototype, { init: { value: function () { var vm = this; return vm._securityUserService.details(vm._config.user).then(function(item) { vm.item = item; }); } }, save: { value: function() { var vm = this; return vm._indexService.saveAccount({ language: vm.item.user.language }); } } }); return UserFormController; })("security"); var security = security || {}; security.UserFormDirective = (function () { function UserFormDirective(config, commandBag, $translate, panelHelper) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, controller: "securityUserFormController", controllerAs: "ctrl", scope: { }, link: function ($scope, $el, $attr, $ctrl) { $el.addClass("security-user-form"); Object.defineProperties($scope, { config: { value: config }, close: { value: function () { return panelHelper.close({ el: $el }); } }, save: { value: function () { var save = config.securityEnabled ? $ctrl.save() : Promise.resolve(); save.then(function () { $translate.use($ctrl.item.user.language); return $scope.close(); }).catch($ctrl.handleError); } }, logout: { value: function () { commandBag.execute('Logout'); } } }); $el.on('closed', function (e, arg) { $el.remove(); }); panelHelper.show({ el: $el, panel: 'overlay' }).then(function () { $ctrl.init(); }); } }; } UserFormDirective.$inject = ["config", "commandBag", "$translate", "panelHelper"]; return UserFormDirective; })("security"); var security = security || {}; security.UserController = (function () { "use strict"; var _manager; function UserController(manager) { _manager = manager; //console.log("USER_CTRL", { ctrl: this, manager: _manager }); } Object.defineProperties(UserController.prototype, { currentUser: { get: function () { return _manager.currentUser; }, enumerable: true }, filter: { get: function () { return _manager.filter; }, enumerable: true }, items: { get: function () { return _manager.items; }, enumerable: true }, list: { value: function () { return _manager.list(); } }, selectedItems: { get: function () { return _manager.selectedItems; }, set: function (value) { return _manager.selectedItems = value; }, enumerable: true }, selectItem: { value: function (item) { _manager.selectItem(item); } }, deselectItem: { value: function (item) { _manager.deselectItem(item); } } }); return UserController; })(); var security = security || {}; security.UserManager = (function () { "use strict"; var _service; var _filter = null; var _items = []; var _selectedItems = []; function UserManager(service) { _service = service; } Object.defineProperties(UserManager.prototype, { currentUser: { get: function () { return _service.currentUser; }, enumerable: true }, config: { get: function () { return _service.config; }, enumerable: true }, filter: { get: function () { return _filter; }, set: function (value) { _filter = value; }, enumerable: true }, items: { get: function () { return _items; }, set: function (value) { _items = value; }, enumerable: true }, selectedItems: { get: function () { return _selectedItems; }, set: function (value) { _selectedItems = value; }, enumerable: true }, list: { value: function () { return _service.list(this.filter) .then(function (items) { _items = items; return _items; }); } }, selectItem: { value: function (item) { if (!this.isSelected(item)) { this.selectedItems.push(item); } } }, deselectItem: { value: function (item) { if (this.isSelected(item)) { this.selectedItems.remove(item); } } }, isSelected: { value: function (item) { return this.selectedItems.any(function (x) { return x.username === item.username; }); } } }); return UserManager; })(); var security = security || {}; security.userSelectorComponent = (function () { "use strict"; function UserSelectorViewModel() { Object.defineProperties(this, { _items: { value: [], writable: true }, _filter: { value: { q: "" } }, _filteredItems: { value: [], writable: true }, _selectedItems: { value: [], writable: true }, _originalSelectedItems: { value: [], writable: true }, _hiddenItems: { value: [], writable: true }, onSelect: { writable: true }, onDeselect: { writable: true }, onSubmit: { writable: true }, onCancel: { writable: true } }); //console.log("USER_SELECTOR_VM", { vm: this }); } Object.defineProperties(UserSelectorViewModel.prototype, { items: { get: function () { return this._items; }, set: function (value) { this._items = value || []; this.filterItems(); }, enumerable: true }, selectedItems: { get: function () { return this._selectedItems; }, set: function (value) { this._selectedItems = value || []; this._originalSelectedItems = this._selectedItems.select(); }, enumerable: true }, hiddenItems: { get: function () { return this._hiddenItems; }, set: function (value) { this._hiddenItems = value || []; this.filterItems(); }, enumerable: true }, filter: { get: function () { return this._filter; }, enumerable: true }, filteredItems: { get: function () { return this._filteredItems; }, enumerable: true }, toggleSelected: { value: function (e, item) { var vm = this; if (vm.selectedItems.any(function (selItem) { return vm._equals(selItem, item); })) { console.log("DESELECT_USER", { item: item }); vm.onDeselect({ event: e, item: item }); } else { console.log("SELECT_USER", { item: item }); vm.onSelect({ event: e, item: item }); } } }, handleSubmit: { value: function (e) { var vm = this; var arg = { event: e, items: vm.items, added: vm.selectedItems.where(function (x) { return !vm._originalSelectedItems.any(function (original) { return vm._equals(x, original); }); }), removed: vm._originalSelectedItems.where(function (original) { return !vm.selectedItems.any(function (x) { return vm._equals(x, original); }); }) }; console.log("HANDLE_SUBMIT", arg); vm.onSubmit(arg); } }, handleCancel: { value: function (e) { var vm = this; return this.onCancel({ event: e, items: vm.items, added: vm.selectedItems.where(function (x) { return !vm._originalSelectedItems.any(function (original) { return vm._equals(x, original); }); }), removed: vm._originalSelectedItems.where(function (original) { return !vm.selectedItems.any(function (x) { return vm._equals(x, original); }); }) }); } }, isSelected: { value: function (item) { var vm = this; return this.selectedItems.any(function (x) { return vm._equals(x, item); }); } }, filterItems: { value: function () { var vm = this; var q = this.filter.q; //console.log("FILTER_USERS", { items: vm.items.select(), hiddenItems: vm.hiddenItems.select() }); this._filteredItems = (vm.items || []) .where(function (x) { return !Array.isArray(vm.hiddenItems) || !vm.hiddenItems.any(function (h) { return vm._equals(x, h); }); }) .where(function (x) { return !q || x.username.contains(q, true) || (x.displayName || '').contains(q, true); }); return this._filteredItems; } }, _equals: { value: function (item1, item2) { return item1.username === item2.username; } } }); function userSelectorComponent(templateUrl) { return { controller: UserSelectorViewModel, bindings: { items: "<", selectedItems: "<", hiddenItems: "<", onSelect: "&", onDeselect: "&", onSubmit: "&", onCancel: "&" }, templateUrl: ["config", function (config) { return config.baseUrl + "/" + templateUrl + "?v=" + config.version; }] }; } return userSelectorComponent; })("security"); var security = security || {}; security.UserService = (function () { "use strict"; var _currentUser; var _config; function UserService(config, $http) { _config = config; _currentUser = config.user; EntityServiceBase.call(this, { niscode: config.niscode, url: config.baseUrl + "/GeoRest/Beheer" }, $http); } UserService.$inject = ["config", "$http"]; UserService.prototype = Object.create(EntityServiceBase.prototype, { currentUser: { get: function () { return _currentUser; }, enumerable: true }, config: { get: function () { return _config; }, enumerable: true }, _processItem: { value: function (item) { if (!item) item = {}; return { displayName: item.DisplayName || null, email: item.Email || null, fax: item.Fax || null, firstName: item.FirstName || null, lastName: item.LastName || null, isGroup: item.IsGroup || false, phone: item.Phone || null, username: item.Username || null, password: item.Password || null, language: item.Language || null, niscode: item.Niscode || null } } }, getUserDisplay: { value: function (item) { if (item.isGroup) { return item.username.substr(item.niscode.length + 1); } return item.firstName || item.lastName ? ((item.firstName || '') + ' ' + (item.lastName || '')).trim() : item.username; } }, list: { value: function (o) { var sv = this; o = o || {}; if (typeof (o.organizationNiscode) !== "string") { o.organizationNiscode = sv._niscode; } //console.log("LIST_USERS", { so: o }); return sv._get("GetUsers", o) .then(function (response) { return response.data.select(function (x) { return sv._processItem(x); }); }); } }, details: { value: function (o) { var sv = this; return sv._get("GetUser", { username: o.username || o, inheritedRoles: o && o.inheritedRoles }) .then(function (response) { return { user: sv._processItem(response.data.User), roles: response.data.Roles }; }); } }, save: { value: function (item) { var sv = this; return sv._post("SaveUser", item) .then(function (response) { return response.data; }); } }, getAllUserRoles: { value: function (o) { var sv = this; return sv._get("GetAllUserRoles", o) .then(function (response) { return response.data; }); } }, getAllRoles: { value: function () { var sv = this; return sv._get("GetAllRoles") .then(function (response) { return response.data; }); } }, getGroupConnections: { value: function (o) { var sv = this; return sv._get("GetGroupConnections", o) .then(function (response) { return response.data; }); } }, getGroupUsers: { value: function (o) { var sv = this; return sv._get("GetGroupUsers", o) .then(function (response) { return response.data.select(function (x) { return sv._processItem(x); }); }); } }, getOrganizations: { value: function () { var sv = this; return sv._get("GetOrganizations") .then(function (response) { return response.data; }); } }, getOrganizationModules: { value: function (o) { var sv = this; return sv._get("GetOrganizationModules", o) .then(function (response) { return response.data; }); } }, getOrganizationModuleRoles: { value: function (o) { var sv = this; return sv._get("GetOrganizationModuleRoles", o) .then(function (response) { return response.data; }); } }, saveOrganization: { value: function (o) { var sv = this; return sv._post("SaveOrganization", o) .then(function (response) { return response.data; }); } }, deleteOrganization: { value: function (o) { var sv = this; return sv._post("DeleteOrganization", o) .then(function (response) { return response.data; }); } } }); return UserService; })("security"); var signalisatie = signalisatie || {}; signalisatie.BackupManager = (function () { function BackupManager() { Object.defineProperties(this, { items: { value: [], enumerable: true }, _restoreIndex: { value: 0, writable: true }, _busy: { value: false, writable: true }, _canUndo: { value: false, writable: true }, _canRedo: { value: false, writable: true }, _refreshCanUndoRedo: { value: function() { this._canUndo = this.items.length > 0 && this._restoreIndex > 0 && !this._busy; this._canRedo = this.items.length > 0 && this._restoreIndex < this.items.length - 1 && !this._busy; } }, setBusy: { value: function () { var me = this; if (me._busy) { return Promise.reject("Action in progress"); } me._busy = true; me._refreshCanUndoRedo(); return Promise.resolve(function() { me._busy = !me._busy; me._refreshCanUndoRedo(); }); } } }); } EventHandler.injectInto(BackupManager.prototype); Object.defineProperties(BackupManager.prototype, { canUndo: { get: function () { return this._canUndo; }, enumerable: true }, canRedo: { get: function () { return this._canRedo; }, enumerable: true }, backup: { value: function (item) { var me = this; return me.setBusy() .then(function(cancel) { var backup = JSON.stringify(item); me.items.splice(me._restoreIndex + 1); if (me.items.last() !== backup) { me.items.push(backup); me._restoreIndex = me.items.length - 1; } var arg = { index: me._restoreIndex, backup: item }; return me.trigger("backup", arg) .then(function () { return arg; }) .then(function (result) { cancel(); return result; }) .catch(function (error) { cancel(); throw error; }); }); } }, restore: { value: function (index) { var me = this; return me.setBusy() .then(function (cancel) { me._restoreIndex = index; var arg = { index: index, backup: JSON.parse(me.items[index]) }; return me.trigger("restore", arg) .then(function () { return arg; }) .then(function (result) { cancel(); return result; }) .catch(function (error) { cancel(); throw error; }); }); } }, undo: { value: function () { var me = this; return me.restore(me._restoreIndex - 1); } }, redo: { value: function () { var me = this; return me.restore(me._restoreIndex + 1); } }, clear: { value: function () { var me = this; return me.setBusy() .then(function (cancel) { me.items.clear(); me._restoreIndex = 0; var arg = { index: me._restoreIndex }; return me.trigger("clear", arg) .then(function () { return arg; }) .then(function (result) { cancel(); return result; }) .catch(function (error) { cancel(); throw error; }); }); } } }); return BackupManager; })(); var signalisatie = signalisatie || {}; signalisatie.CategoryService = (function () { "use strict"; function CategoryService(config, $http) { var sv = this; EntityServiceBase.call(sv, { niscode: config.niscode, url: config.url }, $http); } CategoryService.prototype = Object.create(EntityServiceBase.prototype, { constructor: { value: CategoryService }, _processItem: { value: function (item) { if (!("titleNL" in item)) { item.titleNL = item.title; } if (!("titleFR" in item)) { item.titleFR = item.titleFR || item.category.title; } return item; } } }); return CategoryService; })(); var signalisatie = signalisatie || {}; signalisatie.projectButtonsComponent = (function () { "use strict"; function ProjectButtonsViewModel() { Object.defineProperties(this, { showFilter: { writable: true }, showZoom: { writable: true }, display: { writable: true }, isLocked: { writable: true }, canCreate: { writable: true }, canEdit: { writable: true }, onAddItem: { writable: true }, onChangeFilterDisplay: { writable: true }, onExport: { writable: true }, onChangeDisplay: { writable: true }, onSave: { writable: true }, onRemove: { writable: true }, onReset: { writable: true }, onZoom: { writable: true } }); } Object.defineProperties(ProjectButtonsViewModel.prototype, { handleAddItem: { value: function (e) { return this.onAddItem({ event: e }); } }, toggleFilter: { value: function (e) { return this.onChangeFilterDisplay({ event: e, visible: !this.showFilter }); } }, handleExport: { value: function (e) { return this.onExport({ event: e }); } }, setDisplay: { value: function (e, display) { return this.onChangeDisplay({ event: e, display: display }); } }, handleSave: { value: function (e) { return this.onSave({ event: e }); } }, handleRemove: { value: function (e) { return this.onRemove({ event: e }); } }, handleReset: { value: function (e) { return this.onReset({ event: e }); } }, handleZoom: { value: function (e) { return this.onZoom({ event: e }); } } }); function projectButtonsComponent(templateUrl) { return { controller: ProjectButtonsViewModel, bindings: { showFilter: "<", showZoom: "<", display: "<", isLocked: "<", canCreate: "<", canEdit: "<", onRemove: "&", onAddItem: "&", onChangeFilterDisplay: "&", onExport: "&", onChangeDisplay: "&", onSave: "&", onReset: "&", onZoom: "&" }, templateUrl: ["config", function (config) { return config.baseUrl + "/" + templateUrl + "?v=" + config.version; }] }; } return projectButtonsComponent; })(); var signalisatie = signalisatie || {}; signalisatie.ProjectController = (function (moduleName) { "use strict"; function ProjectController(config, manager, securityManager, fileHelper, $timeout, $translate) { var ctrl = this; projects.ProjectController.call(ctrl, manager, $timeout, $translate); Object.defineProperties(ctrl, { _fileHelper: { value: fileHelper }, _securityManager: { value: securityManager }, isAdministrator: { get: function () { return securityManager.isAdministrator(); }, enumerable: true }, isProjectLeider: { get: function () { return securityManager.isProjectLeider(); }, enumerable: true }, security: { value: Object.create(null, { getUsers: { value: function () { return this.projectUsers.select(function (pUser) { return pUser.user; }); } }, project: { get: function () { return securityManager.loadedProject; }, enumerable: true }, projectUsers: { get: function () { return securityManager.loadedProjectUsers; }, enumerable: true }, canEditModuleTitleTranslationKey: { get: function () { return 'signalisatie.CanEditSignalisatie'; }, enumerable: true }, canEditModuleProperty: { get: function () { return 'editSignalisatie'; }, enumerable: true }, isAdministrator: { get: function () { return securityManager.isAdministrator(); }, enumerable: true }, isProjectLeider: { get: function () { return securityManager.isProjectLeider(); }, enumerable: true }, canCreate: { value: function () { return securityManager.canCreate(); } }, canRead: { value: function (project) { return securityManager.canRead(project); } }, canEdit: { value: function (project) { return securityManager.canEdit(project); } }, addUsers: { value: function (users) { console.log("ADD_USERS", { users: _.array(users) }); return securityManager.addLoadedUsers(users); } }, removeUsers: { value: function (users) { console.log("REMOVE_USERS", { users: _.array(users) }); return securityManager.removeLoadedUsers(users); } }, listProjectUsers: { value: function () { return securityManager.loadProjectAndUsers(this.project); } }, saveProjectUsers: { // { project, projectUsers } value: function () { return securityManager.saveProjectUsers(this.project, this.projectUsers); } }, modifyProjectUser: { value: function (projectUser, prop, value) { return securityManager.modifyProjectUser(projectUser, prop, value); } } }) } }); ctrl.tabs = [{ code: 'general', displayTranslation: 'global.General' }, { code: 'admin', displayTranslation: 'global.Configuration' }, { code: 'security', displayTranslation: 'global.Security', show: function() { return ctrl.security.canEdit(ctrl.item); } }, { code: 'documents', displayTranslation: 'global.Documents', show: function () { return ctrl.item && ctrl.item.id > 0; } }]; ctrl.tabs.forEach(function(tab) { tab.src = tab.src || 'Content/modules/' + moduleName + '/project/tabs/' + tab.code + '.html?v=' + config.version; }); } ProjectController.prototype = Object.create(projects.ProjectController.prototype, { constructor: { value: ProjectController }, gisDocumentsLayerName: { value: 'signalisatie_projecten' }, categories: { get: function () { return this._manager.categories; }, enumerable: true }, onChangeDisplay: { value: function (o) { var ctrl = this; if (o.newValue === 'form') { ctrl.selectedTab = ctrl.tabs.first(); ctrl.security.showUserSelector = false; } } }, setItem: { value: function (item, display) { projects.ProjectController.prototype.setItem.call(this, item, display); item.documents = item.documents || []; }, configurable: true }, save: { value: function (project, projectUsers, display) { var ctrl = this; var state = ctrl.stateManager.addState("loading"); var isNew = !project.id || project.id <= 0; //console.log("SAVING_PROJECT", { project: project, projectUsers: projectUsers }); return ctrl._manager.save(project, display) .then(function (savedProject) { if (savedProject == null) { return false; } return Promise.resolve() .then(function () { if (!isNew) { return ctrl._securityManager.saveProjectUsers(savedProject, projectUsers); } return false; }) .then(function () { return ctrl._securityManager.loadProjectAndUsers(savedProject); }) .then(function (loadedProjectUsers) { project.id = savedProject.id; return ctrl._manager.setActiveItem(savedProject) .then(function () { return loadedProjectUsers; }); }); }) .then(ctrl._timeout) .then(state.completed) .catch(function (error) { state.error(error); G.handleError(error); }); } }, remove: { value: function () { return projects.ProjectController.prototype.remove.apply(this, arguments) .catch(function(error) { G.handleError(error); }); } }, // import/export importGeoJson: { value: function (includeProperties) { var ctrl = this; return ctrl._fileHelper.browse({ accept: ".geojson" }) .then(function (files) { return files.select(function (file) { return ctrl._fileHelper.readAllText(file); }); }) .then(function (geoJsonList) { return ctrl._manager.importGeoJson(ctrl.item, geoJsonList, includeProperties); //.then(ctrl._timeout); }) .then(function () { return ctrl.item; }); } }, exportGeoJson: { value: function () { var ctrl = this; return ctrl._manager.exportGeoJson(ctrl.item) .then(function (geoJson) { return ctrl._fileHelper.writeAllText(geoJson, "application/geojson", ctrl.item.layerName + ".geojson"); }) .then(function (blob) { return ctrl._fileHelper.forceDownload(blob); }); } }, exportExcel: { value: function (/*items*/) { //var items = ctrl.items; //ToDo: implement! alert("ToDo: export Excel"); } } }); return ProjectController; })("signalisatie"); var signalisatie = signalisatie || {}; signalisatie.projectFilterComponent = (function () { "use strict"; function ProjectFilterViewModel() { Object.defineProperties(this, { filter: { writable: true }, categories: { writable: true }, onChange: { writable: true }, onConfirm: { writable: true }, onReset: { writable: true } }); } Object.defineProperties(ProjectFilterViewModel.prototype, { handleChange: { value: function (e, prop) { return this.onChange({ event: e, prop: prop, filter: this.filter }); } }, handleConfirm: { value: function (e) { return this.onConfirm({ event: e, filter: this.filter }); } }, handleReset: { value: function (e) { return this.onReset({ event: e, filter: this.filter }); } } }); function projectFilterComponent(templateUrl) { return { controller: ProjectFilterViewModel, bindings: { filter: "<", categories: "<", onChange: "&", onConfirm: "&", onReset: "&" }, templateUrl: ["config", function (config) { return config.baseUrl + "/" + templateUrl + "?v=" + config.version; }] }; } return projectFilterComponent; })(); var signalisatie = signalisatie || {}; signalisatie.projectFormComponent = (function () { "use strict"; function ProjectFormViewModel($translate) { common.EntityFormViewModel.call(this); Object.defineProperties(this, { _translate: { value: $translate }, categories: { writable: true } }); } ProjectFormViewModel.prototype = Object.create(common.EntityFormViewModel.prototype, { constructor: { value: ProjectFormViewModel }, lang: { get: function () { return this._translate.use().toUpperCase(); }, enumerable: true } }); function projectFormComponent(templateUrl) { var component = common.entityFormComponent(templateUrl); $.extend(component, { controller: ["$translate", ProjectFormViewModel] }); $.extend(component.bindings, { isAdmin: "<", categories: "<", customFormUrl: "<" }); return component; } return projectFormComponent; })(); var signalisatie = signalisatie || {}; signalisatie.ProjectGisManager = (function () { "use strict"; function ProjectGisManager(config, gisViewer, gisVectorManager, geoHelper) { Object.defineProperties(this, { _config: { value: config }, _layers: { value: [] }, _viewer: { value: gisViewer }, _layerManager: { value: gisVectorManager.layer }, _featureManager: { value: gisVectorManager.feature }, _geoHelper: { value: geoHelper } }); } Object.defineProperties(ProjectGisManager.prototype, { getLayer: { value: function (item) { if (item == null) { return Promise.resolve(null); } return this._layerManager.createIfNotExists({ Code: item.layerName, Title: item.title, Transparency: 0, group: this._config.group }); } }, addItemToMap: { value: function (item) { var mgr = this; return mgr.getLayer(item) .then(function (layer) { var features = item.geoJson.features; return mgr._featureManager.add({ layer: layer, features: features }); }); } }, removeItemFromMap: { value: function (item) { var mgr = this; return mgr.getLayer(item) .then(function (layer) { return mgr._layerManager.remove({ layerName: layer.Code }); }); } }, getExtent: { value: function (items) { var mgr = this; var features = items.selectMany(function (item) { return item.geoJson.features; }); var bounds = !features.length ? null : mgr._geoHelper.getBounds(features); return Promise.resolve(bounds); } }, zoom: { value: function (items, minScale) { var mgr = this; return mgr.getExtent(items) .then(function (extent) { if (extent == null) { return false; } return mgr._viewer.zoomToExtent({ extent: extent, minScale: minScale }); }); } } }); return ProjectGisManager; })("signalisatie"); var signalisatie = signalisatie || {}; signalisatie.ProjectManager = (function () { "use strict"; function ProjectManager(service, gisdocumentConfig) { projects.ProjectManager.call(this, service); Object.defineProperties(this, { categories: { value: [], enumerable: true }, _gisdocumentConfig: { value: gisdocumentConfig } }); //console.log("SP.MGR", { mgr: this }); } ProjectManager.prototype = Object.create(projects.ProjectManager.prototype, { constructor: { value: ProjectManager }, canEditDocuments: { get: function() { return this._gisdocumentConfig.canEdit; } }, //init init: { value: function (o) { o = o || {}; var categories = o.categories || []; this.categories.clear().addRange(categories); return projects.ProjectManager.prototype.init.call(this, o); } }, save: { value: function(item, display) { var mgr = this; if (mgr.canEditDocuments) { item.documents = (item.documents || []).where(function (x) { return !x.removed; }); } return projects.ProjectManager.prototype.save.call(mgr, item, display); } }, // validation validate: { value: function (item) { var mgr = this; //console.log("SPM.VALIDATING", { item: item, mgr: mgr }); return projects.ProjectManager.prototype.validate.call(mgr, item) .then(function () { if (!item.category && !item.categoryId) { mgr.errors.push("CategoryMissing"); } return !mgr.errors.length; }); } }, saveFeatures: { value: function (item, features) { var mgr = this; //console.log("SPM.SAVE", { item: $.extend(true, {}, item), features: features }); var original = $.extend(true, {}, item); return Promise.resolve(item) .then(function () { if (features) { //cleanup geometries features.forEach(function(feature) { if (feature.geometry.type === "LineString") { //remove duplicate coordinates var coordinates = []; feature.geometry.coordinates.forEach(function(coordinate) { if (!coordinates.length) { coordinates.push(coordinate); return; } var lastCoordinate = coordinates.last(); if (lastCoordinate[0] !== coordinate[0] || lastCoordinate[1] !== coordinate[1]) { coordinates.push(coordinate); } }); if (feature.geometry.coordinates.length !== coordinates.length) { feature.geometry.coordinates = coordinates; console.log('Removed duplicate coordinates', feature); } } }); item.geoJson.features = features; original.geoJson.features = features.select(); } return item; }) .then(function (item) { return projects.ProjectManager.prototype.save.call(mgr, item); }) .then(function (saved) { var arg = { original: original, item: item, saved: saved, features: features }; return mgr.trigger("save-features", arg) .then(function () { return arg; }); }); } } }); return ProjectManager; })(); var signalisatie = signalisatie || {}; signalisatie.ProjectService = (function (moduleName) { "use strict"; function ProjectService(config, imageHelper, featureHelper, $http, $translate) { var sv = this; projects.ProjectService.call(sv, { niscode: config.niscode, url: config.url }, $http); Object.defineProperties(sv, { //_config: { value: config }, _baseUrl: { value: config.baseUrl }, _imageHelper: { value: imageHelper }, _featureHelper: { value: featureHelper }, _translate: { value: $translate } }); //console.debug("PROJECT_SERVICE", { sv: this }); } ProjectService.prototype = Object.create(projects.ProjectService.prototype, { constructor: { value: ProjectService }, _emptyGeoJson: { get: function () { return { type: "FeatureCollection", properties: {}, features: [], crs: { type: "name", properties: { name: "EPSG:XXXX" } } }; }, enumerable: true }, save: { value: function (item) { var sv = this; //console.log("SPS.SAVE", { saving: $.extend(true, {}, item), item: item, geoJson: item.geoJson }); if (item.geoJson) { if (item.geoJson.features && item.geoJson.features.length) { item.geoJson.features.forEach(function (feature) { if ("$$hashKey" in feature) { delete feature.$$hashKey; } var imgStyle = feature.properties.style.image; if (imgStyle) { if (imgStyle._base64) { delete imgStyle._base64; } if (imgStyle.resizedUrl) { delete imgStyle.resizedUrl; } if (imgStyle.transformedIconUrl) { delete imgStyle.transformedIconUrl; } if (imgStyle.scaleX != null) { delete imgStyle.scaleX; } if (imgStyle.scaleY != null) { delete imgStyle.scaleY; } if (imgStyle._imgEl) { delete imgStyle._imgEl; } } }); } } return projects.ProjectService.prototype.save.call(sv, item) .then(function(result) { if (item.geoJson && item.geoJson.features && item.geoJson.features.length) { sv._processFeatures(item.geoJson.features); } return result; }); } }, _processFeatures: { value: function (features) { var sv = this; var id = 0; var promises = features .select(function (feature) { var featureProperties = feature.properties; id++; featureProperties.id = id; var featureStyle = featureProperties.style; return Promise.resolve() .then(function () { if (featureStyle && featureStyle.stroke) { if ("measure,distance".split(",").contains(featureStyle.stroke.type)) { featureStyle.stroke.measure = 1; if (featureStyle.stroke.type === "distance") { featureStyle.stroke.arrowLocation = "end"; featureStyle.stroke.labelLocation = "end"; } else { featureStyle.stroke.arrowLocation = "start end"; featureStyle.stroke.labelLocation = "center"; } featureStyle.stroke.type = "solid"; } } return false; }) .then(function () { // only process image-features if (feature.geometry.type === "Point" && featureStyle && featureStyle.image) { var imgStyle = featureStyle.image; // make iconUrl more generic var baseUrls = ["/touchviewer/", "/touchviewer-2018/", "/mobileviewer/", "/ol-viewer/"].concat([sv._baseUrl]); baseUrls.forEach(function (baseUrl) { if (imgStyle.iconUrl) { var iconUrl = imgStyle.iconUrl.replaceAll(',', ''); if (iconUrl.startsWith(baseUrl, true)) { iconUrl = iconUrl.substring(baseUrl.length).trimStart("/"); } // catch old iconUrls 'Handlers/SymbolHandler.aspx?img={foldername}/{filename}.png' if (iconUrl.contains('/SymbolHandler.aspx')) { var imgParams = (Q.queryUrl('img', iconUrl) || '').split('/'); if (imgParams.length === 2) { var folder = imgParams[0]; var img = sv._imageHelper.getFilenameWithoutExtension(imgParams[1]).replaceAll("_", " "); iconUrl = "Handlers/PictureHandler.aspx?type=picture&action=img&identifier=" + folder + "/" + img; } else { console.warn('Converting old iconUrl failed', { iconUrl: iconUrl }); } } imgStyle.iconUrl = iconUrl; } }); if (!imgStyle.scale && imgStyle.scaleY) { imgStyle.scale = imgStyle.scaleY; delete imgStyle.scaleY; } // process resized urls if (imgStyle.iconUrl && !imgStyle.iconUrl.contains("svg=1")) { var iconUrl = imgStyle.iconUrl; return sv._imageHelper.getImageFromUrl(iconUrl) .then(function (img) { Object.defineProperty(imgStyle, "_imgEl", { value: img, writable: true, configurable: true, enumerable: false }); var transformedSize = sv._featureHelper.calcTransformedIconSize(feature); if (transformedSize) { return sv._imageHelper.resizeFixed(img, transformedSize[0], transformedSize[1]) .then(function (resizedBlob) { imgStyle.transformedIconUrl = sv._imageHelper.createUrl(resizedBlob); return img; }); } imgStyle.transformedIconUrl = imgStyle.iconUrl; return img; }) .then(function(img) { if (feature.properties && feature.properties.resizeByScale) { imgStyle.resizedUrl = imgStyle.transformedIconUrl; } else if (img.width !== imgStyle.width || img.height !== imgStyle.height) { //console.debug("PS.RESIZING", { feature: feature, iconUrl: iconUrl }); var width = imgStyle.width > 1 ? imgStyle.width : 1; var height = imgStyle.height > 1 ? imgStyle.height : 1; return sv._imageHelper.resizeFixed(img, width, height) .then(function (resizedBlob) { imgStyle.resizedUrl = sv._imageHelper.createUrl(resizedBlob); }); } return false; }) .catch(function (error) { console.error("Could not process img", { error: error, iconUrl: imgStyle.iconUrl, feature: feature }); }); } } return false; }) .then(function () { return feature; }); }); return Promise.all(promises); } }, _processItem: { value: function (item) { var sv = this; item.layerName = item.layerName || 'signalisatie-project-' + item.id; var emptyGeoJson = sv._emptyGeoJson; return Promise.resolve() .then(function () { if (item) { if (item.geoJson == null) { item.geoJson = emptyGeoJson; } if (item.geoJson.type == null) { item.geoJson.type = emptyGeoJson.type; } return Promise.resolve() .then(function () { if (item.geoJson.features == null) { item.geoJson.features = emptyGeoJson.features; return false; } else { item.geoJson.features.forEach(function (feature) { if (feature.properties && feature.properties.style && feature.properties.style.image && feature.properties.style.image.transformedIconUrl) { delete feature.properties.style.image.transformedIconUrl; } }); return sv._processFeatures(item.geoJson.features); } }) .then(function () { if (item.category) { item.categoryId = item.category.id; if (!("titleNL" in item.category)) { item.category.titleNL = item.category.title; } if (!("titleFR" in item.category)) { item.category.titleFR = item.category.titleFR || item.category.title; } } Object.keys(item.geoJson.properties) .forEach(function (key) { if (!item.hasOwnProperty(key) && item.geoJson.properties.hasOwnProperty(key)) { Object.defineProperty(item, key, { get: function () { return item.geoJson.properties[key]; }, enumerable: true }); } }); return true; }); } return false; }) .then(function () { return projects.ProjectService.prototype._processItem.call(sv, item); }); } }, getReport: { value: function (item, exportType) { var sv = this; var report = item.geoJson.features .where(function (x) { return x.geometry.type === "Point" && x.properties.style.image; }) .groupBy(function (x) { return x.properties.style.image.iconUrl; }) .select(function (x) { var identifier = decodeURIComponent(x.key.split("=").last()); var category = identifier.split("/").first(); var relUrl = x.key; if (relUrl.startsWith(sv._baseUrl)) { relUrl = relUrl.substring(sv._baseUrl.length); } var absUrl = location.protocol + "//" + location.host + (sv._baseUrl || '').trimEnd('/') + "/" + relUrl.trimStart("/") + "&niscode=" + sv._niscode + "&lang=" + sv._translate.use();// + "&imagetype=jpg"; var title = x.values.select(function (v) { return v.properties.title; }).first(); var count = x.values.length; return { category: category, title: title, count: count, url: absUrl }; }) //ignore features that were dragged directly on map .where(function (x) { return x.category !== "_temp"; }); //console.log("SP.REPORT", { item: item, lang: sv._translate.use(), report: report, service: sv }); return sv._translate(["signalisatie.Signalling", "signalisatie.BillOfMaterials", "global.Category", "signalisatie.Piece", "global.Quantity", "global.Picture"]) .then(function (translations) { var arr = [[translations["global.Picture"], translations["global.Quantity"], translations["global.Category"], translations["signalisatie.Piece"]]] .concat(report.orderByDesc(function (x) { return x.count; }) .select(function (x) { return [x.url, x.count, x.category, x.title]; })); //console.log("REPORT", { item: item, report: report, arr: arr }); exportType = exportType || "pdf"; var query = { type: exportType, title: item.title + " (" + item.code + ")" }; var exportUrl = sv._baseUrl + "/Handlers/ExportHandler.aspx?" + Q.toQuery(query); var arg = { data: arr, code: item.code, title: item.title, category: item.category != null ? item.category.title : null, startDate: item.startDate, endDate: item.endDate, description: item.description }; return sv._http.post(exportUrl, arg) .then(function (response) { var query = Q.toQuery({ file: response.data.filename, clientfile: /*item.title + "-" +*/ item.code + "-" + translations["signalisatie.BillOfMaterials"] + "." + exportType //"delete": 1 }); window.open(sv._baseUrl + "/Handlers/FileHandler.aspx?" + query); }); }); } } }); return ProjectService; })("signalisatie"); var signalisatie = signalisatie || {}; signalisatie.Bootstrapper = (function (moduleName) { "use strict"; function Bootstrapper(config, signalisatieConfig, categoryService, projectManager, infoManager, $timeout, $scope, $http) { var bs = this; var failedChangeProjectMessage; var signalisatieContainer; //console.log("ROOTSCOPE", { scope: $scope, timeout: $timeout, config: config }); this.initProjectData = function (indexService) { // project events projectManager // active project changed .on("change-active-item", function (e, arg) { if (arg.hasChanged) { //console.debug("SB.PROJECT", { project: arg.activated }); indexService.saveUserLastProjectId((arg.activated || {}).id); } }); return categoryService .list() // init project-manager .then(function (categories) { return projectManager .init({ canEdit: config.canEdit, categories: categories, autoLoad: true }); }) .then(function () { return bs; }); }; this.initProjectGis = function (projectGisManager, snappingManager, gisViewer) { projectManager // loaded items changed .on("change-loaded-items", function (e, arg) { return Promise.enqueue(arg.removed.select(function (x) { return function () { return projectGisManager.removeItemFromMap(x); }; })) .then(function () { //console.log("SB.ADD_PROJECT_LAYER", { evt: e, arg: arg }); return Promise.enqueue(arg.added.select(function (x) { return function () { return projectGisManager.addItemToMap(x); }; })) .then(function () { if (projectManager.activeItem) { return projectGisManager.getLayer(projectManager.activeItem) .then(function (layer) { if (layer) { return snappingManager.list() .then(function () { //console.debug("SB.SNAPPING_MANAGER", { snappingManager: snappingManager, layer: layer }); return snappingManager.setSelected(layer); }); } return false; }); } return false; }) .then(function (result) { return result; }); }); }) // zoom to project(s) .on("request-extents", function (e, arg) { //console.debug("SBP.REQUEST_EXTENTS", { arg: arg }); return projectGisManager.getExtent(arg.items) .then(function (extent) { arg.addExtent(extent); return extent; }); }) .on("focus", function (e, arg) { //console.debug("SBP.FOCUS", { arg: arg }); return gisViewer.zoomToExtent({ bounds: arg.bounds }); }); return Promise.resolve(bs); }; this.initFeatureData = function (featureManager, featureHelper, projectSecurityManager) { //console.log("SB.FEATURE_DATA", { config: config, projMgr: projectManager, featMgr: featureManager }); projectManager .on("change-active-item", function (e, arg) { //console.log("ACTIVE_PROJECT", { projectMgr: projectManager, featureMgr: featureManager, evt: e, arg: arg }); if (!arg.hasChanged) { return; } var project = arg.activated; var features = project ? project.geoJson.features : []; var canEditModule = projectSecurityManager.canEditModule(project); // don't use return -> messes up order of events (project-change > features-init) featureManager .init({ items: features, modes: canEditModule && project && !project.isLocked ? ["gis", "html", "style"] : [] }); }); // select feature after creation featureManager .on("change-selected-items", function (e, arg) { if (arg.selectedItems.length === 1) { return $timeout(function () { if (arg.selectedItems.length === 1) {// check again after timeout var itemId = featureHelper.getProperty(arg.selectedItems.first(), "id"); //console.log("SB.SCROLLING_TO", { evt: e, arg: arg, itemId: itemId, mgr: featureManager }); $("#SignalisatieContainer").find(".feature-list-item[data-id=" + itemId + "]").scrollTo(); } }, 250); } return $timeout(); }) .on("change-interface-modes", function ( /*e, arg*/) { //console.log("SB.FM_INTERFACE_MODES", { evt: e, arg: arg, mgr: featureManager }); }) .on("save-items", function (e, arg) { //console.log("SB.SAVE_ITEM_DATA", { evt: e, arg: arg, mgr: featureManager }); // recalculate resized img var ih = new ImageHelper(); return Promise.all( arg.items .where(function (item) { return featureHelper.isImage(item); }) .select(function (item) { var imgStyle = featureHelper.getStyle(item).image; return Promise.resolve(imgStyle._imgEl) .then(function (img) { if (!img) { return ih.getImageFromUrl(imgStyle.iconUrl) .then(function (iconImage) { imgStyle._imgEl = iconImage; return iconImage; }); } return img; }) .then(function (img) { //debugger;//TODO-rik #8399 on-hold //console.log('FeatureResize', item.properties.title, new Date().toISOString(), 'calcTransformedIconSize', JSON.stringify(item.properties)); var transformedSize = featureHelper.calcTransformedIconSize(item); if (transformedSize) { //console.log('FeatureResize', item.properties.title, new Date().toISOString(), 'transformedSize', transformedSize[0], transformedSize[1]); return ih.resizeFixed(img, transformedSize[0], transformedSize[1]) .then(function (resizedBlob) { imgStyle.transformedIconUrl = ih.createUrl(resizedBlob); return img; }); } imgStyle.transformedIconUrl = imgStyle.iconUrl; return img; }) .then(function (img) { if (item.properties && item.properties.resizeByScale) { imgStyle.resizedUrl = imgStyle.transformedIconUrl; } else if (img && (img.width !== imgStyle.width || img.height !== imgStyle.height)) { //console.debug("DISTORTED", { imgStyle: imgStyle, img: img }); var width = imgStyle.width > 1 ? imgStyle.width : 1; var height = imgStyle.height > 1 ? imgStyle.height : 1; return ih.resizeFixed(img, width, height) .then(function (resizedBlob) { imgStyle.resizedUrl = ih.createUrl(resizedBlob); }); } return false; }); })) .then($timeout); }) .on("focussing", function (e, arg) { //console.log("SB.FM_FOCUSSING", { evt: e, arg: arg }); arg.onReady(function (/*o*/) { //console.log("SB.FM_FOCUSED", o); }); }); return Promise.resolve(bs); }; this.initFeatureStyle = function (featureStyleManager, featureManager, featureHelper) { //return Promise.resolve(bs); featureManager // loaded changed .on("change-loaded-items", function (e, arg) { //console.log("SB.CHANGE_LOADED", { evt: e, arg: arg, featureStyleManager: featureStyleManager }); return featureStyleManager .init({ items: arg.items }) .then(function () { return $timeout(); }); }) .on("save-items", function (e, arg) { var hasModifiedLoadedItems = arg.items.innerJoin(featureManager.loadedItems).length; // update style features if (hasModifiedLoadedItems) { featureStyleManager .init({ items: featureManager.loadedItems }); } }); featureStyleManager .on("change-style", function (e, arg) { //console.debug("SB.CHANGE_STYLE", { arg: arg }); if (["height", "width"].contains(arg.prop)) { if (!parseFloat(arg.style[arg.prop])) { return false; } } featureHelper.updateItems(arg.items, arg.style, arg.scale, arg.upp, arg.keepRatio); return featureManager.save(arg.items); }); return Promise.resolve(bs); }; this.initFeatureGis = function (featureGisManager, featureManager, projectGisManager, snappingManager, gisViewer, featureHelper) { var modeName = "gis"; var prevSnappable = []; var setSnappableFeatures = function () { return Promise.resolve() .then(function () { if (prevSnappable.length > 0) { return gisViewer.removeSnappable(prevSnappable); } return false; }) .then(function () { var canSnap = config.canEdit && featureManager.enabled; if (canSnap && featureGisManager.layer != null) { return Promise.resolve() .then(function () { if (snappingManager.selected) { return snappingManager.selected; } //return projectGisManager.getLayer(projectManager.activeItem); return null; }) .then(function (layer) { if (layer) { return snappingManager.list() .then(function () { return snappingManager.setSelected(layer); }); } return false; }); //var snappableFeatures = featureManager.items // .where(function (feature) { // return featureHelper.getProperty(feature, "snappable"); // }); //prevSnappable = snappableFeatures; //gisViewer.addSnappable(snappableFeatures); } return false; }); } var setSelectedGisItems = function (selectedItems) { return featureGisManager.setSelectedItems(selectedItems) .then(function () { var hasValidSelectedItems = selectedItems.any(function (x) { return featureHelper.isSimplePoint(x) || featureHelper.isLineString(x) || featureHelper.isPolygon(x); }); var canModifyFeatures = config.canEdit && featureManager.enabled && hasValidSelectedItems && featureManager.hasMode(modeName); var canTransformFeatures = config.canEdit && featureManager.enabled && hasValidSelectedItems && featureManager.hasMode(modeName) && !selectedItems.all(function (x) { return featureHelper.isSimplePoint(x); }); featureGisManager.setEditMode(canModifyFeatures); featureGisManager.setTransformMode(canTransformFeatures); return setSnappableFeatures(); }); }; // map events gisViewer .on("feature-change", function (e, arg) { //console.log("SB.FEATURE_CHANGE", { evt: e, arg: arg }); //if ((arg.layers || []).contains(featureGisManager.layer)) { // featureManager.save(arg.features); //} if (featureGisManager.layer.Code) { var features = arg.changed[featureGisManager.layer.Code] || []; if (features.length > 0) { featureManager.save(features); } } }); // project event projectManager .on("change-active-item", function (e, arg) { if (!arg.hasChanged) { return false; } var t0 = performance.now(); var project = arg.activated; var features = project ? project.geoJson.features : []; return projectGisManager.getLayer(projectManager.activeItem) .then(function (layer) { return featureGisManager .init({ layer: layer, items: features }) .then(function () { return setSnappableFeatures(); }); }) .then(function (result) { var t1 = performance.now(); //console.log("PERFORMANCE", Math.round(t1 - t0), "ProjectManager[change-active-item].Signalisatie[FeatureGisManager]"); return result; }); }); // feature events featureManager .on("change-enabled", function () { return setSelectedGisItems(featureManager.selectedItems); }) .on("change-interface-modes", function (e, arg) { if (arg.added.contains(modeName)) { return featureGisManager.enable(true); } else if (arg.removed.contains(modeName)) { return featureGisManager.enable(false); } return null; }) // init //.on("init", function () { // featureGisManager.refreshLayer(); //}) // selection changed .on("change-selected-items", function (e, arg) { //console.log("SB.FM_SELECTION", { evt: e, arg: arg, mgr: featureGisManager }); return setSelectedGisItems(arg.selectedItems); }) // zoom to feature(s) .on("focus", function (e, arg) { return featureGisManager.zoom(arg.items, arg.minScale); }) // item moved in list .on("change-item-index", function ( /*e, arg*/) { featureGisManager.update(featureManager.items); }) .on("save-items", function (e, arg) { //console.log("SB.SAVE_ITEM_GIS", { evt: e, arg: arg, features: featureManager.items, mgr: featureGisManager }); return Promise .all([ featureGisManager.add(arg.added), featureGisManager.update(arg.modified) ]) .then(function () { return setSnappableFeatures(); }); }) // item(s) removed .on("remove-items", function (e, arg) { //console.log("FG.REMOVE", { selected: featureGisManager.selectedItems.select(), evt: e, arg: arg }); return featureGisManager.remove(arg.items); }) .on("change-interface-modes", function (e, arg) { return featureGisManager.enable(arg.items.contains(modeName)); }); featureGisManager .on("change-enabled", function () { return setSelectedGisItems(featureManager.selectedItems); }) .on("change-selected-items", function (e, arg) { //console.log("SB.FGM_SELECTION", { evt: e, arg: arg, mgr: featureGisManager }); // ignore when event is not triggered by a user-action on the map if (arg.initiator !== "user" || (!arg.selectedItems.length && !featureManager.selectedItems.length)) { // no changes -> do nothing return null; } // set selected features return featureManager.setSelectedItems(arg.selectedItems); }); return Promise.resolve(bs); }; this.initFeatureHtml = function (featureHtmlManager, featureManager, featureHelper, featureGisManager, gisViewer) { var modeName = "html"; var filterHtmlItems = function (items) { return items.where(function (x) { return featureHelper.isLabel(x) || featureHelper.isImage(x); }); }; var setHtmlItems = F.debounce(function () { var items = filterHtmlItems(featureManager.items); var selected = filterHtmlItems(featureManager.selectedItems); //console.log("SB.SET_HTML", { items: items, selected: selected, mgr: featureHtmlManager }); return Promise.resolve() .then(function () { if (!config.canEdit || !featureManager.enabled || !featureHtmlManager.enabled) { var deselected = selected; items = []; selected = []; return featureGisManager.show(deselected); } return false; }) .then(function () { return featureHtmlManager.setItems(items); }) .then(function () { return featureHtmlManager.setSelectedItems(selected); }) .then(function () { return $timeout(250); }); }, 50); var saveHtmlItems = F.debounce(function (items) { return featureManager.save(items); }, 50); featureManager .on("change-enabled", function () { return setHtmlItems(); }) .on("change-items", function () { setHtmlItems(); }) .on("change-selected-items", function (e, arg) { //console.log("SB.FM.SELECTION", { selected: featureManager.selectedItems.select(), manager: featureHtmlManager }); if (!config.canEdit || !featureManager.enabled || !featureHtmlManager.enabled) { return featureHtmlManager.setItems([]) .then($timeout); } var selected = filterHtmlItems(arg.selectedItems); //var deselected = filterHtmlItems(arg.removed); return featureHtmlManager.setItems(selected) .then(function () { return featureHtmlManager.setSelectedItems(selected); }) .then($timeout); }) .on("save-items", function (e, arg) { var hasModifiedSelectedItems = filterHtmlItems(featureManager.selectedItems).innerJoin(arg.modified).length; //console.log("SB.SAVE_ITEM_HTML", { hasModifiedSelectedItems: hasModifiedSelectedItems, evt: e, arg: arg, mgr: featureHtmlManager }); if (hasModifiedSelectedItems) { return featureHtmlManager.setItems(arg.items) .then(function () { return featureHtmlManager.setSelectedItems(featureManager.selectedItems); }) .then($timeout); } return null; }) .on("change-interface-modes", function (e, arg) { return featureHtmlManager.enable(arg.items.contains(modeName)); }); featureHtmlManager .on("change-enabled", function () { return setHtmlItems(); }) .on("change-selected-items", function (e, arg) { //console.log("SB.FHM_SELECTION", { evt: e, arg: arg, mgr: featureHtmlManager }); if (!config.canEdit || !featureManager.enabled || !featureHtmlManager.enabled) { return null; } var selected = arg.selectedItems; var deselected = arg.removed; return Promise.resolve() .then(function () { if (selected.length > 0) { return featureGisManager.hide(selected); } return true; }) .then(function () { if (deselected.length) { return featureGisManager.show(deselected); } return true; }) .then(function () { if (selected.length > 0) { return featureGisManager.update(selected); } return true; }); }) .on("copy-item", function (e, arg) { return gisViewer.getCoordinateFromPixel(arg.pixel) .then(function (coordinate) { return featureManager.copyItem(arg.item, { type: "Point", coordinates: coordinate }); }) .then(function (items) { return featureManager.save(items); }) .then(function (items) { // select cloned feature after creation if (featureHtmlManager.enabled) { return featureManager.selectItems(items); } return true; }); }) .on("move-item", function (e, arg) { return gisViewer.getCoordinateFromPixel(arg.pixel) .then(function (coordinate) { var geometry = featureHelper.getGeometry(arg.item); geometry.coordinates = coordinate; return featureManager.save(arg.item); }); }) .on("resize-item", function (e, arg) { var style = featureHelper.getStyle(arg.item); var factor = arg.size[1] / arg.originalSize[1]; if ("height" in style) { style.height *= factor; } if ("width" in style) { style.width *= factor; } if (arg.type === "image") { style.image.scale *= factor; } else if (arg.type === "label") { style.label.scale *= factor; } return saveHtmlItems(arg.item); }) .on("rotate-item", function (e, arg) { var style = featureHelper.getStyle(arg.item); style.rotation = arg.rotation; return featureManager.save(arg.item); }); gisViewer .on("scale-change center-change resize-map", function () { //console.log("SB.VC", e.type, { args: arguments }); setHtmlItems(); }); var windowSize = [$(window).width(), $(window).height()]; $(window).on("resize", function () { var newSize = [$(window).width(), $(window).height()]; if (windowSize[0] !== newSize[0] || windowSize[1] !== newSize[1]) { windowSize = newSize; setHtmlItems(); } }); return Promise.resolve(bs); }; this.initFeatureFabric = function (featureFabricManager, featureManager, featureHelper, featureGisManager, gisViewer) { var modeName = "fabric"; var filterFabricItems = function (items) { var fabricItems = items.where(function (x) { return featureHelper.isImage(x); }); return gisViewer.getMapInfo() .then(function (info) { return Promise.all(fabricItems.select(function (x) { return info.extent.contains(featureHelper.getGeometry(x)) .then(function (valid) { if (valid) { return x; } return null; }); })); }) .then(function (fabricItems) { return fabricItems.where(function (x) { return x != null; }); }); }; var setSelectedItems = function () { return filterFabricItems(featureManager.selectedItems) .then(function (selected) { if (!config.canEdit || !featureManager.enabled || !featureFabricManager.enabled) { selected = []; } return featureFabricManager.setSelectedItems(selected); }); }; var setFabricItems = F.debounce(function () { return filterFabricItems(featureManager.items) .then(function (items) { if (!config.canEdit || !featureManager.enabled || !featureFabricManager.enabled) { items = []; } return items; }) .then(function (items) { return Promise.resolve() .then(function () { return featureFabricManager.init({ items: items }); }) .then(function () { if (featureFabricManager.enabled) { return featureGisManager.hide(items); } else { return featureFabricManager.getFeatures() .then(function (items) { return featureGisManager.show(items); }); } }); }) .then(function () { return setSelectedItems(); }) .then($timeout); }, 50); featureManager .on("change-enabled", function (/*e, arg*/) { //console.log("SB.FM_ITEMS", { evt: e, arg: arg, mgr: featureFabricManager }); return featureFabricManager .init({ enabled: featureManager.hasMode(modeName) }); }) .on("change-items", function () { return setFabricItems(); }) .on("change-selected-items", function (/*e, arg*/) { //console.log("SB.FM.SELECTION", { selected: featureManager.selectedItems.select(), manager: featureFabricManager }); return setSelectedItems(); }) .on("change-interface-modes", function (e, arg) { return featureFabricManager.enable(arg.items.contains(modeName)); }) .on("save-items", function (/*e, arg*/) { //console.log("SB.SAVE_ITEM_FABRIC", { evt: e, arg: arg, mgr: featureFabricManager }); setFabricItems(); }); featureFabricManager .on("change-enabled", function () { //console.log("SB.FFM_ENABLED", { mgr: featureFabricManager }); if (featureFabricManager.enabled) { return infoManager.push({ info: "global.MapDisabled", cancel: function () { return featureManager.setModes(["style", "gis", "html"]); } }); } else { return infoManager.cancel(); } }) .on("change-enabled modify-items", function () { var currentSelection = featureManager.selectedItems.select(); if (featureFabricManager.canvas == null || projectManager.activeItem == null) { return $timeout(); } return Promise.resolve() // show/hide canvas .then(function () { if (featureFabricManager.enabled) { $(featureFabricManager.canvas.wrapperEl) .appendTo(gisViewer.element) .show(); } else { $(featureFabricManager.canvas.wrapperEl) .hide(); } }) .then(function () { // deselect items first to ungroup them (causes problems with rotating multiple features at once) return featureFabricManager.setSelectedItems([]) // update features .then(function () { return filterFabricItems(featureManager.items) .then(function (items) { console.debug("SBF.MODIFY_FEATURES", { items: items }); return featureFabricManager.updateFeatures(items); }) .then(function (items) { return featureManager.save(items); }); }) // show features .then(function () { if (!featureFabricManager.enabled) { return filterFabricItems(featureManager.items) .then(function (items) { return featureGisManager.show(items); }); } return true; }) // restore selected items .then(function () { return featureFabricManager.setSelectedItems(currentSelection); }); }) .then(function () { setFabricItems(); }); }) .on("change-selected-items", function (e, arg) { //console.log("SB.FFM_SELECTED", { evt: e, arg: arg, mgr: featureFabricManager }); return Promise.resolve(arg.selectedItems) .then(function (features) { // ignore when event is not triggered by a user-action on the map // no changes -> do nothing if (arg.initiator !== "user" || (!features.length && !featureManager.selectedItems.length)) { return null; } // set selected features return featureManager.setSelectedItems(features); }); }) .on("start-copy", function (e, arg) { //console.log("SB.START_COPY", { evt: e, arg: arg, mgr: featureFabricManager }); return featureGisManager.show(arg.items); }) .on("end-copy", function (e, arg) { return Promise .enqueue(arg.items.select(function (clone) { return function () { return gisViewer.getCoordinateFromPixel(clone.pixel) .then(function (coordinate) { return featureManager.copyItem(clone.item, { type: "Point", coordinates: coordinate }); }); }; })) .then(function (items) { return featureManager.save(items); }); }); gisViewer .on("scale-change center-change resize-map", function (/*e*/) { if (featureFabricManager.enabled) { //console.log("SB.FFM_CHANGE_MAP", { evt: e, args: arguments }); setFabricItems(); } }); var windowSize = [$(window).width(), $(window).height()]; $(window).on("resize", function () { var newSize = [$(window).width(), $(window).height()]; if (windowSize[0] !== newSize[0] || windowSize[1] !== newSize[1]) { windowSize = newSize; setFabricItems(); } }); return Promise.resolve(bs); }; this.initBackup = function (featureManager, backupManager) { var _ignoreBackup = false; function backup() { if (_ignoreBackup) { return; } backupManager.backup(featureManager.items); } projectManager .on("change-active-item", function (e, arg) { if (!arg.hasChanged) { return; } backupManager.clear(); }) .on("save-features", function (/*e, arg*/) { //console.log("SB.PROJECT_FEATURES_SAVE", { evt: e, arg: arg }); backupManager.clear(); projectManager.canChangeActiveItem = true; }); featureManager .on("init remove-items save-items change-item-index", function (/*e, arg*/) { //console.log("SB.FEATURES_CHANGE", { evt: e, arg: arg }); backup(); }); backupManager .on("backup", function () { // nothing... projectManager.canChangeActiveItem = !backupManager.canUndo; }) .on("restore", function (e, arg) { _ignoreBackup = true; return featureManager.remove(featureManager.items) .then(function () { return featureManager.save(arg.backup); }) .then(function () { projectManager.canChangeActiveItem = !backupManager.canUndo; if (failedChangeProjectMessage != null && projectManager.canChangeActiveItem) { failedChangeProjectMessage.cancel(); } _ignoreBackup = false; return $timeout(); }); }); return Promise.resolve(bs); }; this.initDroppableViewer = function (gisViewer, featureManager, pictureService) { gisViewer.element .on("dragover", function (e) { e.preventDefault(); }) .on("drop", function (e) { var dt = e.dataTransfer || e.originalEvent.dataTransfer; if (dt && dt.files) { e.preventDefault(); e.stopImmediatePropagation(); if (!featureManager.enabled) { return null; } var files = e.target.files || dt.files; var position = { x: e.originalEvent.offsetX, y: e.originalEvent.offsetY }; if (files && files.length) { var file = files[0]; var pixel = [parseInt(position.x, 10), parseInt(position.y, 10)]; return pictureService.createNew(file) .then(function (symbol) { return pictureService.save(symbol); }) .then(function (savedSymbol) { return gisViewer.getCoordinateFromPixel(pixel) .then(function (coordinate) { var factor = (savedSymbol.width > 640) ? (640 / savedSymbol.width) : 1; //console.log("SB.SAVED_SYMBOL", { pic: savedSymbol }); return featureManager.getNewImage({ url: pictureService.getUrl(savedSymbol, $scope.currentLanguage), width: savedSymbol.width, height: savedSymbol.height, scale: gisViewer.scale * factor }, { type: "Point", coordinates: coordinate }); }) .then(function (item) { return featureManager.save(item); }); }); } } return null; }); return Promise.resolve(bs); }; this.initCommands = function (commandBag, $translate) { var configProjectenTitle = config.projectenTitle; var configSignalisatieTitle = config.signalisatieTitle; commandBag.add([{ name: moduleName + ".Projects", content: '', title: function () { return $translate("global.Projects"); } }, { name: moduleName + ".ShowSignalisatie", content: '', title: function () { return configSignalisatieTitle || $translate(moduleName + ".Signalling"); } }]); return Promise.resolve(bs); }; this.initPanels = function (commandBag, backupManager) { var panelManager = new PanelManager($(".content-container")); function disableProjectPanel() { panelManager.freezePanel($("#ProjectContainer")); panelManager.disablePanel("right"); commandBag.disable(commandBag.items.where(function (x) { var toIgnore = "security.User,gislegend.Legend,TrackMyLocation,crab.SearchAddress,ZoomIn,ZoomOut,InitialExtent".split(","); return !toIgnore.contains(x.name); })); } function enableProjectPanel() { panelManager.unfreezePanel($("#ProjectContainer")); panelManager.enablePanel("right"); commandBag.enableAll(); } function disableSignalisatiePanel() { panelManager.freezePanel($("#SignalisatieContainer")); panelManager.disablePanel("bottom"); commandBag.disable(commandBag.items.where(function (x) { var toIgnore = "security.User,gislegend.Legend,TrackMyLocation,crab.SearchAddress,ZoomIn,ZoomOut,InitialExtent".split(","); return !toIgnore.contains(x.name); })); } function enableSignalisatiePanel() { panelManager.unfreezePanel($("#SignalisatieContainer")); panelManager.enablePanel("bottom"); commandBag.enableAll(); } projectManager .on("change-display", function (e, arg) { if (arg.display === "form") { disableProjectPanel(); } else { enableProjectPanel(); } }); backupManager .on("backup restore clear", function () { //console.log("SB.CHECK_PANELS", { args: arguments }); var disable = backupManager.canUndo; if (disable) { disableSignalisatiePanel(); } else { enableSignalisatiePanel(); } }); return Promise.resolve(bs); }; this.initElements = function (commandBag, featureManager, $compile) { var pm = new PanelManager($(".content-container")); var projectContainer = $('
').hide(); $compile(projectContainer)($scope).appendTo($(".panel-bottom")); signalisatieContainer = $("#SignalisatieContainer"); commandBag .on("execute", moduleName + ".Projects", function () { pm.show($("#ProjectContainer"), "bottom"); }) .on("execute", moduleName + ".ShowSignalisatie", function () { pm.show($("#SignalisatieContainer"), "right", "full"); }); pm.container .on("shown closed", function () { var isVisible = signalisatieContainer.is(":visible"); featureManager.enable(isVisible); }); // feature html markers var featureHtmlContainer = $('
'); $compile(featureHtmlContainer)($scope).appendTo($(".viewer-container:first")); return Promise.resolve(bs); }; this.initCss = function () { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); return Promise.resolve(bs); }; this.initPrint = function (printService) { printService .on("before-print", function (e, arg) { var project = projectManager.activeItem; console.log("SM.PRINTING", { evt: e, arg: arg, project: project }); if (project && project.geoJson && project.geoJson.properties) { arg.addParameter("TITLE", project.title); arg.addParameter("CODE", project.code); arg.addParameter("PROJECT_DESCRIPTION", project.description); arg.addParameter("PROJECT_STARTDATE", project.startDate); arg.addParameter("PROJECT_ENDDATE", project.endDate); arg.addParameter("PROJECT_CATEGORY_NL", project.category.titleNL); arg.addParameter("PROJECT_CATEGORY_FR", project.category.titleFR); var identifiers = project.geoJson.features .where(function (f) { return f.properties.style.image && f.properties.style.image.iconUrl; }) .select(function (f) { return Q.queryUrl("identifier", f.properties.style.image.iconUrl); }); arg.addParameter("SYMBOL_LEGEND_URL", window.location.origin + config.baseUrl + "/Handlers/DynamicSymbolLegend.aspx?niscode=" + $scope.niscode + "&identifier=" + identifiers.join(",")); arg.clientFilename = "print-" + project.code + "-" + arg.template.Name + "-" + moment().format("YYYYMMDDhhmmss") + ".pdf"; var props = project.geoJson.properties; Object.keys(props).forEach(function (key) { arg.addParameter(key, props[key]); }); } }); return Promise.resolve(bs); }; this.initShortCuts = function (hotkeyService, featureManager, featureHelper, gisViewerManager) { function getPointFeatures() { if (featureManager.enabled) { return featureManager.selectedItems.where(function (x) { return featureHelper.isPoint(x); }); } return []; } hotkeyService .on("alt+f", function (e /*, handler*/) { //console.log("HOTKEY_SERVICE", { evt: e, handler: handler, thisScope: this, featureManager: featureManager }); if (featureManager.enabled) { e.preventDefault(); var modes = !featureManager.interfaceModes.contains("fabric") ? ["style", "fabric"] : ["style", "gis", "html"]; featureManager.setModes(modes); } }); hotkeyService .on("up,right,down,left", function (e) { var features = getPointFeatures(); if (!features.any()) { return; } features.forEach(function (feature) { var geometry = featureHelper.getGeometry(feature); var coordinates = geometry.coordinates; switch (e.code) { case "ArrowUp": coordinates[1]++; break; case "ArrowRight": coordinates[0]++; break; case "ArrowDown": coordinates[1]--; break; case "ArrowLeft": coordinates[0]--; break; } }); featureManager.save(features); }); hotkeyService .on("shift+up,shift+down", function (e) { var features = getPointFeatures() .where(function (f) { return !featureHelper.isSimplePoint(f); }); if (!features.any()) { return; } features.forEach(function (feature) { var featureStyle = featureHelper.getStyle(feature); var style = { height: featureStyle.height }; if (style.height == null) { style.height = featureHelper.calcHeightUnits(feature, gisViewerManager.scale, gisViewerManager.unitsPerPixel); } switch (e.code) { case "ArrowUp": style.height++; break; case "ArrowDown": if (style.height > 1) { style.height--; } break; } featureHelper.updateItems([feature], style, gisViewerManager.scale, gisViewerManager.unitsPerPixel, null); }); featureManager.save(features); }); return Promise.resolve(bs); }; this.initSecurity = function (projectSecurityManager, userManager) { projectManager // active project changed .on("change-active-item", function (e, arg) { //console.log("SECURITY.CHANGE_PROJECT", { evt: e, arg: arg }); projectSecurityManager.loadProjectAndUsers(arg.activated); }); return userManager.list() .then(function () { return Promise.resolve(bs); }); }; this.initHashEvents = function (locationHashHelper, commandBag) { var hashEvents = (function () { return { showSignalisatie: [function () { commandBag.execute(moduleName + ".ShowSignalisatie"); }], project: [function (v) { var activeItem = projectManager.activeItem; var projectCode = v.project; if ((!activeItem && projectCode) || (activeItem && activeItem.code !== projectCode)) { projectManager.activateByFilter({ code: projectCode }); } }], zoomProject: [function () { if (projectManager.activeItem != null) { return projectManager.focus(projectManager.activeItem); } return false; }] }; })(); locationHashHelper.addHashchangeEvents(hashEvents); return Promise.resolve(bs); }; this.initToolbar = function (toolbarService) { return toolbarService .buildTree([ "Home", "security.User", "separator", //---------- !signalisatieConfig.submitProjectUrl ? moduleName + ".Projects" : null, moduleName + ".ShowSignalisatie", !signalisatieConfig.submitProjectUrl && signalisatieConfig.gipodEnabled ? "Gipod.ShowHandhaving" : null, !signalisatieConfig.submitProjectUrl && signalisatieConfig.gipodEnabled ? "ToggleGipodFilter" : null, !signalisatieConfig.submitProjectUrl ? "notities.Open" : null, //"notities.AddGpsNotitie", //"schetsen.Open", !signalisatieConfig.submitProjectUrl ? "dwf.Open" : null, "separator", //---------- "Print", "measure.Measure", "crab.SearchAddress", "TrackMyLocation", "featureinfo.ShowSelection", "gislegend.Legend" ].where(function (x) { return x != null; })) .then(function () { return bs; }); }; this.initOnlineState = function (onlineStateService) { var offlineMsg = null; onlineStateService .on("change-online-state", function (e, arg) { if (!arg.isOnline) { return infoManager.push({ info: "global.Offline" }) .then(function (msg) { offlineMsg = msg; return $timeout(); }); } else if (offlineMsg != null) { offlineMsg.cancel(); } return $timeout(); }); return bs; }; this.initGipodConfig = function () { if (signalisatieConfig.gipodEnabled) { return Promise.resolve() .then(function () { if (!config.gipodConfigApi) { throw "Missing configuration: gipodConfigApi"; } return $http.get(config.gipodConfigApi) .then(function (gipodConfig) { signalisatieConfig.gipod = gipodConfig.data; signalisatieConfig.trigger("gipodLoad", signalisatieConfig.gipod); return bs; }); }) .catch(function (err) { G.handleError({ translate: 'gipod.ConfigurationMissing' }); console.error("Failed to load Gipod configuration", err, config.gipodConfigApi); return bs; }); } return bs; }; } return Bootstrapper; })("signalisatie"); var signalisatie = signalisatie || {}; signalisatie.buttonsComponent = (function () { "use strict"; function ButtonsViewModel() { Object.defineProperties(this, { canEdit: { writable: true }, canAdd: { writable: true }, canSelectProject: { writable: true }, container: { writable: true }, containerDisplay: { writable: true }, display: { writable: true }, isLocked: { writable: true }, displayfilter: { writable: true }, fabricmodeEnabled: { writable: true }, displayscalebar: { writable: true }, scalebarValue: { value: 100, writable: true }, moveEnabled: { writable: true }, submitProjectUrl: { writable: true }, onChangeContainer: { writable: true }, onChangeContainerDisplay: { writable: true }, onChangeDisplay: { writable: true }, onChangeFilterdisplay: { writable: true }, onChangeFabricmode: { writable: true }, onChangeScalebardisplay: { writable: true }, onFocus: { writable: true }, onSave: { writable: true }, onCancel: { writable: true }, onChangeListposition: { writable: true }, onExportGeoJson: { writable: true }, onImportGeoJson: { writable: true }, onExportReport: { writable: true }, onUndo: { writable: true }, onRedo: { writable: true }, onSubmitProject: { writable: true } }); } Object.defineProperties(ButtonsViewModel.prototype, { setContainer: { value: function (e, container) { return this.onChangeContainer({ event: e, container: container }); } }, setContainerDisplay: { value: function (e, containerDisplay) { return this.onChangeContainerDisplay({ event: e, containerDisplay: containerDisplay }); } }, setDisplay: { value: function (e, display) { return this.onChangeDisplay({ event: e, display: display }); } }, toggleFilter: { value: function (e) { return this.onChangeFilterdisplay({ event: e, visible: !this.displayfilter }); } }, toggleFabricmode: { value: function (e) { return this.onChangeFabricmode({ event: e, enabled: !this.fabricmodeEnabled }); } }, toggleScalebar: { value: function (e) { return this.onChangeScalebardisplay({ event: e, visible: !this.displayscalebar }); } }, handleFocus: { value: function (e) { return this.onFocus({ event: e }); } }, handleSave: { value: function (e) { return this.onSave({ event: e }); } }, handleCancel: { value: function (e) { return this.onCancel({ event: e }); } }, handleMove: { value: function (e, steps) { return this.onChangeListposition({ event: e, steps: steps }); } }, handleExportGeoJson: { value: function (e) { return this.onExportGeoJson({ event: e }); } }, handleImportGeoJson: { value: function (e) { return this.onImportGeoJson({ event: e }); } }, handleExportReport: { value: function (e) { return this.onExportReport({ event: e }); } }, handleRemove: { value: function (e) { return this.onRemove({ event: e }); } }, handleReset: { value: function (e) { return this.onReset({ event: e }); } }, handleZoom: { value: function (e) { return this.onZoom({ event: e }); } }, handleUndo: { value: function (e) { return this.onUndo({ event: e }); } }, handleRedo: { value: function (e) { return this.onRedo({ event: e }); } }, submitProject: { value: function (e) { return this.onSubmitProject({ event: e }); } }, }); function buttonsComponent(templateUrl) { return { controller: ButtonsViewModel, bindings: { canEdit: "<", canAdd: "<", canUndo: "<", canRedo: "<", canSelectProject: "<", container: "<", containerDisplay: "<", display: "<", isLocked: "<", displayfilter: "<", fabricmodeEnabled: "<", displayscalebar: "<", scalebarValue: "<", moveEnabled: "<", submitProjectUrl: "<", onChangeContainer: "&", onChangeDisplay: "&", onChangeContainerDisplay: "&", onChangeFilterdisplay: "&", onChangeFabricmode: "&", onChangeScalebardisplay: "&", onFocus: "&", onSave: "&", onCancel: "&", onChangeListposition: "&", onExportGeoJson: "&", onImportGeoJson: "&", onExportReport: "&", onUndo: "&", onRedo: "&", onSubmitProject: "&" }, templateUrl: ["config", function (config) { return config.baseUrl + "/" + templateUrl + "?v=" + config.version; }], transclude: { count: "?countTemplate", filter: "?filterTemplate", scalebar: "?scalebarTemplate" } }; } return buttonsComponent; })(); var signalisatie = signalisatie || {}; signalisatie.SignalisatieController = (function (moduleName) { "use strict"; var _display = "form"; function SignalisatieController(projectManager, featureManager, backupManager, featureHelper, featureHtmlManager, featureFabricManager, imageHelper, gisViewerManager, $timeout, signalisatieConfig) { var ctrl = this; Object.defineProperties(ctrl, { //container: home, list, styling container: { value: "list", writable: true, enumerable: true }, containerDisplay: { value: "digitize", writable: true, enumerable: true }, //display: form, details loading: { value: false, writable: true }, showfilter: { value: false, writable: true }, showscalebar: { value: false, writable: true }, _projectManager: { value: projectManager }, _featureManager: { value: featureManager }, _backupManager: { value: backupManager }, _featureHelper: { value: featureHelper }, _featureHtmlManager: { value: featureHtmlManager }, _featureFabricManager: { value: featureFabricManager }, _imageHelper: { value: imageHelper }, _fileHelper: { value: imageHelper }, _gisViewer: { value: gisViewerManager }, _timeout: { value: F.debounce($timeout, 25) }, stateManager: { value: StateManagerFactory.createEntityStateManager(_.newGuid(), { controller: ctrl, entityType: 'Signalisatie', module: moduleName }), enumerable: true }, signalisatieConfig: { value: signalisatieConfig } }); featureManager .on("change-selected-items", function (e, arg) { if (arg.selectedItems.length) { ctrl.container = "list"; } }); ctrl.featuremode = "gis"; //console.log("S.CTRL", { ctrl: ctrl }); } Object.defineProperties(SignalisatieController.prototype, { interfaceModes: { get: function () { return this._featureManager.interfaceModes; }, enumerable: true }, canEditModule: { get: function () { return this.interfaceModes.length > 0; }, enumerable: true }, display: { get: function () { return this.canEditModule ? _display : "details"; }, set: function (value) { _display = value || "details"; }, enumerable: true }, canUndo: { get: function () { return this.canEditModule && this._backupManager.canUndo; }, enumerable: true }, canRedo: { get: function () { return this.canEditModule && this._backupManager.canRedo; }, enumerable: true }, formProject: { get: function () { return this._projectManager.formItem; }, enumerable: true }, activeProject: { get: function () { return this._projectManager.activeItem; }, enumerable: true }, projects: { get: function () { return this._projectManager.items; }, enumerable: true }, features: { get: function () { return this._featureManager.items; }, enumerable: true }, scale: { get: function () { return this._gisViewer.scale; }, enumerable: true }, unitsPerPixel: { get: function () { return this._gisViewer.unitsPerPixel; }, enumerable: true }, selectProject: { value: function (project) { var ctrl = this; if (project == null) { return ctrl._projectManager.setActiveItem(null); } //console.log("SC.SELECT_PROJECT", { project: project, ctrl: ctrl }); ctrl.container = "list"; var unloadProject; if (ctrl.activeProject != null) { if (project.id === ctrl.activeProject.id) { // no changes, list features again return Promise.resolve(ctrl.activeProject); } else { // unload previous active project unloadProject = ctrl.activeProject; } } return ctrl._projectManager.setActiveItem(project) .then(function (arg) { if (unloadProject != null) { return ctrl._projectManager.unloadItem(unloadProject) .then(function () { return arg; }); } return arg; }); } }, loadFeatures: { value: function (features) { var ctrl = this; //console.log("SC.LOAD_FEATURES", { items: features, ctrl: ctrl }); var loaded = _.array(features || []); var selected = ctrl._featureManager.selectedItems; if (!loaded.length) { loaded = selected.length ? selected : ctrl.features; } return ctrl._featureManager.setLoadedItems(loaded) .then(function (arg) { ctrl.container = "styling"; ctrl._timeout(); return arg; }); } }, focusLoadedFeatures: { value: function (options) { return this._featureManager.focus(this._featureManager.loadedItems, options); } }, save: { value: function () { var ctrl = this; var state = ctrl.stateManager.addState("loading"); //console.log("SC.SAVE", { item: this.activeProject, features: this.features, ctrl: this }); return ctrl._projectManager.saveFeatures(ctrl.formProject || ctrl.activeProject, ctrl.features) .then(state.completed) .catch(function (error) { state.error(error); G.handleError(error); }); } }, cancel: { value: function () { var ctrl = this; var state = ctrl.stateManager.addState("loading"); var currentProject = ctrl.activeProject; ctrl.showfilter = false; ctrl.showscalebar = false; ctrl._projectManager.canChangeActiveItem = true; // clear activeItem first so all references are also renewed return ctrl._projectManager.setActiveItem(null) .then(function () { // make sure to get the server version of the project return ctrl._projectManager.details(currentProject.id); }) .then(function (project) { return ctrl._projectManager.setActiveItem(project); }) .then(state.completed) .catch(function (error) { state.error(error); G.handleError(error); }); } }, newFeature: { value: function (geom, sourceFeature, extra) { var ctrl = this; extra = extra || {}; if (geom == null) { return Promise.resolve(null); } var promise = Promise.resolve(); switch (geom.type) { case "Point": case "MultiPoint": var pointOptions = { isLabel: extra.isLabel, scale: ctrl._gisViewer.scale, upp: ctrl._gisViewer.unitsPerPixel, height: extra.isLabel ? 1 : null, isImage: extra.isImage, transparency: extra.transparency }; promise = ctrl._featureManager.getNewPoint(pointOptions, geom.geoJson); //promise = ctrl._featureManager.getNewLabel({ scale: ctrl._gisViewer.scale }, geom.geoJson); break; case "LineString": case "MultiLineString": var lineOptions = { measure: extra.isMeasure ? 1 : 0, arrowLocation: extra.arrowLocation, labelLocation: extra.labelLocation, transparency: extra.transparency }; promise = ctrl._featureManager.getNewLineString(lineOptions, geom.geoJson); break; case "Polygon": case "MultiPolygon": promise = ctrl._featureManager.getNewPolygon({ transparency: extra.transparency }, geom.geoJson); break; } return promise .then(function (item) { if (item == null) { return null; } if (sourceFeature != null && sourceFeature.type === "Feature") { //console.log("SC.SRC_FEATURE", { sourceFeature: sourceFeature }); var sourceStyle = ctrl._featureHelper.getStyle(sourceFeature); $.extend(true, ctrl._featureHelper.getStyle(item), sourceStyle); } return ctrl._featureManager.save(item) .then(function (items) { //console.log("SC.SAVED_FEATURE", { features: items, ctrl: ctrl }); if (items.length === 1) { var saved = items.first(); if (!ctrl._featureHelper.isImage(saved)) { return ctrl.loadFeatures(saved); } } return items; }); }); } }, saveFeature: { value: function (feature) { return this._featureManager.save(feature); } }, addImageFeature: { // url: url to the actual picture (real size) // size: the size in which the picture thumbnail is added // pixel: destination of the picture in the map-container value: function (item, url, size, pixel) { var ctrl = this; return ctrl._gisViewer.getCoordinateFromPixel(pixel) .then(function (coordinate) { return ctrl._imageHelper.getImageFromUrl(url) .then(function (img) { // bereken de verhouding van de ware grootte van het symbool (img) met die van de thumbnail (size parameter) var factor = size[0] / img.width; return ctrl._featureManager.getNewImage({ url: url, width: item.resizeByScale ? item.width : img.width, height: item.resizeByScale ? item.height : img.height, scale: item.defaultScale || (ctrl._gisViewer.scale * factor), resizeByScale: item.resizeByScale }, { type: "Point", coordinates: coordinate }); }); }) .then(function (item) { //var style = item.properties.style; //console.log('NEW.FEATURE.STYLE', 'mapScale', ctrl._gisViewer.scale, 'width', style.width, 'height', style.height, 'imgWidth', style.image.width, 'imgHeight', style.image.height, 'imgScale', style.image.scale); return ctrl._featureManager.save(item); }); } }, toggleFabricmode: { value: function (enabled) { var modes = enabled ? ["style", "fabric"] : ["style", "gis", "html"]; return this._featureManager.setModes(modes); } }, exportGeoJson: { value: function () { var ctrl = this; var features = ctrl.features; if (ctrl._featureManager.selectedItems.length) { features = ctrl._featureManager.selectedItems; } var project = $.extend(true, {}, ctrl.activeProject); project.geoJson.features = features; var geoJson = JSON.stringify(project.geoJson, null, 2); //console.log("SC.GEOJSON", { project: project, json: geoJson }); return ctrl._fileHelper.writeAllText(geoJson, "application/geojson", project.layerName + ".geojson") .then(function (blob) { return ctrl._fileHelper.forceDownload(blob); }); } }, importGeoJson: { value: function (includeProperties) { var ctrl = this; return ctrl._fileHelper.browse({ accept: ".geojson" }) .then(function (files) { var promises = files.select(function (file) { return ctrl._fileHelper.readAllText(file) .then(function (content) { var geoJson = JSON.parse(content); console.log("SC.IMPORT", { project: ctrl.activeProject, json: geoJson }); return ctrl._projectManager._service._processFeatures(geoJson.features); }) .then(function (features) { ctrl._featureManager.importItems(features); if (includeProperties) { //ctrl._service._geoJsonProperties.forEach(function (key) { // if (typeof (geoJson.properties[key]) !== "undefined") { // project.geoJson.properties = geoJson.properties[key]; // project[key] = geoJson.properties[key]; // } //}); } }); }); return Promise.all(promises); }); } }, exportReport: { value: function (exportType) { var ctrl = this; var state = ctrl.stateManager.addState("loading"); return this._projectManager.getReport(exportType) .then(state.completed) .catch(function (error) { state.error(error); throw error; }); } }, backup: { value: function () { this._backupManager.backup(this.activeProject.geoJson.features); } }, undo: { value: function () { return this._backupManager.undo(); } }, redo: { value: function () { return this._backupManager.redo(); } }, submitProject: { value: function () { if (!confirm('Ben je zeker dat het signalisatieplan volledig is en ingediend mag worden?')) { return Promise.reject(); } var ctrl = this; var state = ctrl.stateManager.addState("loading"); return G.ajax({ controller: 'Signalisatie', action: 'SubmitProject', data: { projectCode: ctrl.activeProject.code, submitProjectUrl: ctrl.signalisatieConfig.submitProjectUrl }, type: "POST", success: function (response) { if (response.message) { alert(response.message); } if (response.redirectUrl) { window.location.href = response.redirectUrl; } else { window.close(); } }, error: function (error) { state.error(error); G.handleError(error); } }); } } }); return SignalisatieController; })("signalisatie"); var signalisatie = signalisatie || {}; signalisatie.SignalisatieDirective = (function (moduleName) { function SignalisatieDirective(config) { return { restrict: "EA", template: '
' }; } return SignalisatieDirective; })("signalisatie"); var sitesettings = sitesettings || {}; sitesettings.fontSizeComponent = (function () { "use strict"; function FontSizeViewModel() { Object.defineProperties(this, { fontSize: { writable: true, enumerable: true }, fontSizeUnit: { writable: true, enumerable: true }, fontSizeFactor: { writable: true, enumerable: true }, fontSizePixels: { writable: true, enumerable: true } }); } Object.defineProperties(FontSizeViewModel.prototype, { add: { value: function (e, step) { return this.handleChange(e, this.fontSize + step); } }, handleChange: { value: function (e, fontSize) { return this.onChange({ event: e, fontSize: fontSize, fontSizeUnit: this.fontSizeUnit }); } } }); function fontSizeComponent(templateUrl) { return { controller: FontSizeViewModel, bindings: { fontSize: "<", fontSizeUnit: "<", fontSizeFactor: "<", fontSizePixels: "<", onChange: "&" }, templateUrl: ["config", function (config) { return config.baseUrl + "/" + templateUrl + "?v=" + config.version; }] } } return fontSizeComponent; })(); var sitesettings = sitesettings || {}; sitesettings.SiteSettingsController = (function () { "use strict"; function SiteSettingsController(manager) { Object.defineProperties(this, { _manager: { value: manager } }); } Object.defineProperties(SiteSettingsController.prototype, { fontSize: { get: function () { return this._manager.fontSize; }, enumerable: true }, fontSizePixels: { get: function () { return this._manager.getDefaultFontSize().digits; } }, fontSizeUnit: { get: function () { return this._manager.fontSizeUnit; }, enumerable: true }, fontSizeFactor: { get: function () { return (Math.round(this._manager.fontSizeFactor * 100) / 100); }, enumerable: true }, setFontSize: { value: function (fontSize) { return this._manager.setFontSize(fontSize); } }, setFontSizeByPct: { value: function (pct) { return this._manager.setFontSizeByPct(pct); } } }); return SiteSettingsController; })(); var sitesettings = sitesettings || {}; sitesettings.SiteSettingsManager = (function () { "use strict"; function SiteSettingsManager() { Object.defineProperties(this, { _root: { value: document.body }, _fontSizeFactor: { value: 1, writable: true }, _referenceFontSize: { writable: true }, _fontSize: { writable: true }, _fontSizeUnit: { writable: true } }); var fsData = this.getDefaultFontSize(); this._fontSize = fsData.digits; this._fontSizeUnit = fsData.unit; //console.log("SSM", { mgr: this }); } EventHandler.injectInto(SiteSettingsManager.prototype); Object.defineProperties(SiteSettingsManager.prototype, { fontSizeFactor: { get: function () { return this._fontSizeFactor; }, enumerable: true }, fontSize: { get: function () { return this._fontSize; }, enumerable: true }, fontSizeUnit: { get: function () { return this._fontSizeUnit; }, enumerable: true }, init: { value: function (o) { var mgr = this; o = o || {}; return Promise.resolve() .then(function () { if (typeof (o.fontSize) === "string") { return mgr.setFontSize(o.fontSize); } return null; }) .then(function () { if (typeof (o.lang) === "string") { return mgr.setLanguage(o.lang); } return null; }); } }, setFontSizeByPct: { value: function (pct) { return this.setFontSize(this._fontSize * (pct / 100)); } }, setFontSize: { value: function (value) { var oldValue = this._fontSize; var fsData = this._getFontSizeData(value); this._fontSize = fsData.digits; if (fsData.unit && this._fontSizeUnit !== fsData.unit) { if (this._referenceFontSize == null) { this._referenceFontSize = this._fontSize; } this._fontSizeUnit = fsData.unit; } this._fontSizeFactor = this._fontSize / this._referenceFontSize; this._root.style.fontSize = this._fontSize + this._fontSizeUnit; var arg = { oldValue: oldValue, fontSize: this._fontSize, factor: this._fontSizeFactor }; return this.trigger("change-fontsize", arg) .then(function () { return arg; }); } }, getDefaultFontSize: { value: function () { var cssFontSize = window.getComputedStyle(this._root) .fontSize; return this._getFontSizeData(cssFontSize); } }, _getFontSizeData: { value: function (value) { var input = "" + value; var fontSizeDigits = /\d+\.\d+|\.\d+|\d+/g.exec(input)[0]; var fontSizeUnit = input.substring(fontSizeDigits.length); return { digits: parseFloat(fontSizeDigits), unit: fontSizeUnit }; } } }); return SiteSettingsManager; })("sitesettings"); function TestController(config, $scope, $http, $timeout, $log) { } window.mm.Register("test", function (moduleName) { return { TestDirective: function (config, $http, $timeout, $log, $compile) { return { restrict: "EA", //controller: ["config", "$scope", "$http", "$log", TestController], templateUrl: function (el, attr) { return _.toArray(attr).where(function (x) { return x.key.endsWith("Directive") }).select(function (x) { return x.value; }).first() || attr.src; }, link: function ($scope, $el) { $log.info(moduleName.toUpperCase(), this, $.extend(true, {}, $scope)); var viewer = $scope.gis.viewer; if (!$scope.modules[moduleName]) { $scope.modules[moduleName] = {}; } function showPage(code) { var tabEl = $scope.panels.findByClass('test-' + code); if (tabEl) { tabEl.remove(); } tabEl = $('
'); tabEl.addClass('test-' + code); $compile(tabEl)($scope); $scope.panels.show(tabEl, 'bottom', 'full'); } $scope[moduleName] = (function () { return { css: $.loadCss("Content/modules/test/test.css"), config: {}, gisEvents: { mapload: function () { //if (config.application === moduleName) { // NavigationManager.addCommands([ // { name: "Home" }, // { module: moduleName, name: "upload" } // ]); //} $.delay("TEST.MAP_LOAD", function () { $scope.$apply(function () { $scope.test.selectedLayer = $scope.gis.layers.getAll().first(function (x) { return x.Code === "gebouwen"; }); }); }); if (!$scope.isMobile) { setTimeout(function () { viewer.gisviewer("addCommand", { name: "TestForm", icon: 'glyphicon glyphicon-cloud', callback: function () { $el.toggle(); } }, "toolbar"); }); } } }, selectedLayer: null, filter: "FeatId IN (348, 17095, 17136, 26657)", wkt: null }; })(); $scope.gis.addEvents($scope.test.gisEvents, moduleName); //ModuleManager.registerCommands(moduleName, [ // { // name: "upload", // icon: 'icon-ui-48px-glyph-1_attach-87', // title: "Upload", // callback: function () { // showPage("upload"); // } // } //]); $el .draggable({ handle: ".header", containment: viewer }) .on("click", ".gis-zoom-btn", function (e) { e.preventDefault(); $log.info("FILTER", $scope.test.selectedLayer.Code, $scope.test.filter); var filter = {}; filter[$scope.test.selectedLayer.Code] = $scope.test.filter; viewer.gisviewer("setSelectedItems", { filter: filter, geom: $scope.test.wkt, zoomToSelection: true, minScale: 250 }, function () { $log.info("ITEMS_SET"); }); }) .on("click", ".gis-filter-btn", function (e) { e.preventDefault(); $log.info("FILTER", $scope.test.selectedLayer.Code, $scope.test.filter); var filter = {}; filter[$scope.test.selectedLayer.Code] = $scope.test.filter; viewer.gisviewer("filter", { layer: $scope.test.selectedLayer.Code, filter: $scope.test.filter, geom: $scope.test.wkt }, function () { $log.info("ITEMS_FILTERED"); }); }) .parents(".popup").first() .draggable({ handle: ".header", containment: viewer }); } } } } }); window.mm.Register("test", function (moduleName) { return { UploadDirective: function (config, $http, $timeout, $log) { return { restrict: "EA", templateUrl: ModuleManager.templateUrl, link: function (scope, el, attr) { var module = scope.modules[moduleName]; module.upload = (function () { return { el: el } }); module.items = []; G.log = function () { //console.log.apply(null, arguments); $("#Output ul").append("
  • " + _.array(arguments).selectMany(function (x) { if (_.isArray(x)) { return x; } else { return [x]; } }).join(", ") + "
  • "); } var fm = $("#FileContainer") .on("click", "ul li .remove", function () { if (fm.data("geoitFilemanager")) fm.filemanager("remove", $(this).parent().find("strong").text()); }); $("#FileManagerContainer") .on("change", "[data-option]", function () { G.log("FM", $(this).attr("data-option"), this.checked); if (fm.data("geoitFilemanager")) fm.filemanager("option", $(this).attr("data-option"), this.checked); }) .on("click", ".browse", function (e) { e.preventDefault(); if (fm.data("geoitFilemanager")) fm.filemanager("browse"); }) .on("click", ".upload", function (e) { e.preventDefault(); if (fm.data("geoitFilemanager")) fm.filemanager("upload"); }); function initFileManager() { function filesToListItems(files) { return files.select(function (x) { return x; }).select(function (f) { var li = $("
  • ").data("file", f); var img = $("") .css({ cursor: "pointer" }) .click(function () { var file = $(this).parent().data("file"); fm.filemanager("getDataUrl", file, function (dataUrl) { window.open(dataUrl, "_blank"); }); }); if (f.type.startsWith("image")) { fm.filemanager("getDataUrl", f, function (data) { img.attr("src", data); }); } else { img.attr("src", config.baseUrl + "/Content/images/file.png"); } var title = $("").text(f.name); var remove = $("").addClass("remove").text("[x]"); return li.append(img, title, " ", remove); }); } fm .filemanager({ uploadUrl: config.baseUrl + "/Upload/Html5Upload.aspx", autoUpload: $("[data-option=autoUpload]").is(":checked"), accept: "image/*", multiple: $("[data-option=multiple]").is(":checked"), droppable: $("[data-option=droppable]").is(":checked"), overwrite: $("[data-option=overwrite]").is(":checked"), update: function (e, arg) { G.log("FILEMANAGER.UPDATE", arg); //$("#FileContainer ul").empty().append(filesToListItems(arg.added)); scope.$apply(function () { module.items.addRange(arg.added.select(function(file) { return { file: file }; })); }); }, //processFileBeforeSelect: function (arg, callback) { // //G.log("PROCESSING", arg.file.name); // //if (arg.file.name.endsWith(".exe")) { // // arg.file = null; // //} // callback(arg.file); //}, processFileBeforeUpload: function (arg, callback) { G.log("PROCESSING_BEFORE_UPLOAD", arg.file.name); if (arg.file.type.startsWith("image")) { fm.filemanager("resizeImage", { file: arg.file, maxSize: { width: 100, height: 100 } }, callback); } else { callback(arg.file); } }, upload: function (e, arg) { G.log("FILEMANAGER.UPLOADED", arg.name); //$("#Output ul").empty().append(filesToListItems(arg.processed)); } }); } $(".create").click(function () { if (!fm.data("geoitFilemanager")) initFileManager(); }); $(".destroy").click(function () { if (fm.data("geoitFilemanager")) fm.filemanager("destroy"); }); initFileManager(); } } } } }); var vectorfeatures = vectorfeatures || {}; vectorfeatures.FeatureController = (function () { function FeatureController(manager, featureHelper) { var ctrl = this; Object.defineProperties(ctrl, { errors: { value: [], enumerable: true }, selecting: { value: false, writable: true }, _manager: { value: manager }, _featureHelper: { value: featureHelper } }); } Object.defineProperties(FeatureController.prototype, { filter: { get: function () { return this._manager.filter; }, enumerable: true }, itemsScale: { get: function () { return this._manager.itemsScale; }, enumerable: true }, totalItemsCount: { get: function () { return this._manager.totalItemsCount; }, enumerable: true }, items: { get: function () { return this._manager.items; }, enumerable: true }, selectedItems: { get: function () { return this._manager.selectedItems; }, enumerable: true }, loadedItems: { get: function () { return this._manager.loadedItems; }, enumerable: true }, list: { value: function () { return this._manager.list(); } }, save: { value: function (items) { var ctrl = this; return ctrl._manager.save(items) .catch(function (error) { console.error("SAVE FEATURES", { error: error, items: items, ctrl: ctrl }); ctrl.errors.push("ServerError"); }); } }, remove: { value: function (items) { var ctrl = this; return ctrl._manager.remove(items) .catch(function (error) { console.error("REMOVE FEATURES", { error: error, items: items, ctrl: ctrl }); ctrl.errors.push("ServerError"); }); } }, reset: { value: function () { return this.showItem(this.item, (this.item != null && this.item.id > 0) ? "form" : "list"); } }, // (un)selecting items select: { value: function (items) { return this._manager.selectItems(items); } }, deselect: { value: function (items) { return this._manager.deselectItems(items); } }, toggleSelected: { value: function (item) { if (item == null) { if (this.selectedItems.length !== this.items.length) { return this._manager.setSelectedItems(this.items); } return this._manager.setSelectedItems([]); } return this._manager.toggleSelected(item); } }, // (un)loading items load: { value: function (items) { console.log("FC.LOAD", { items: items, ctrl: this }); var loaded = _.array(items || []); if (!loaded.length) { loaded = this.selectedItems.length ? this.selectedItems : this.items; } return this._manager.setLoadedItems(loaded); } }, unload: { value: function (items) { console.log("FC.UNLOAD", { item: items, ctrl: this }); return this._manager.unloadItems(items); } }, toggleLoaded: { value: function (item) { console.log("FC.TOGGLE_LOADED", { item: item, ctrl: this }); return this._manager.toggleLoaded(item); } }, focus: { value: function (items) { items = items ? _.array(items) : []; if (!items.length) { items = this.selectedItems.length ? this.selectedItems : this.items; } return this._manager.focus(items, { minScale: 250 }); } }, onChangeItem: { value: function (prop, style, scale, upp) { var ctrl = this; var changedItems = ctrl._featureHelper.updateItems(ctrl.loadedItems, style, scale, upp, null); return ctrl._manager.triggerModifyItems(changedItems); } }, move: { value: function (item, steps) { item = item || this.selectedItems.first(); return this._manager.move(item, steps); } }, setItemsScale: { // only rescale images that don't have a category starting with '_' value: function (value) { var ctrl = this; var imageItems = (ctrl.selectedItems.length ? ctrl.selectedItems : ctrl.items) .where(function (x) { return ctrl._featureHelper.isImage(x); }) .where(function (x) { var imageUrl = ctrl._featureHelper.getStyle(x).image.iconUrl; var category = (Q.queryUrl("identifier", imageUrl) || Q.queryUrl("img", imageUrl) || "") .split("/") .first(); return !category.startsWith("_"); }); return ctrl._manager.setItemsScale(imageItems, value) .then(function (arg) { return ctrl.save(arg.items) .then(function () { return arg; }); }); } }, resetItemsScale: { value: function () { return this._manager.resetItemsScale(); } } }); return FeatureController; })(); var vectorfeatures = vectorfeatures || {}; vectorfeatures.featureListComponent = (function () { "use strict"; function FeatureListViewModel(featureHelper) { var vm = this; Object.defineProperties(vm, { display: { value: "list", writable: true, enumerable: true }, helper: { value: featureHelper, enumerable: true }, items: { value: [], writable: true, enumerable: true }, selectedItems: { value: [], writable: true, enumerable: true }, loadedItems: { value: [], writable: true, enumerable: true }, onChange: { writable: true }, onSelect: { writable: true }, onDeselect: { writable: true }, onLoad: { writable: true }, onUnload: { writable: true }, onFocus: { writable: true }, onRemove: { writable: true }, onMove: { writable: true } }); } Object.defineProperties(FeatureListViewModel.prototype, { handleChange: { value: function (e, item, prop) { return this.onChange({ event: e, item: item, prop: prop }); } }, toggleSelectedItem: { value: function (e, item) { if (this.isSelected(item)) { return this.deselect(e, item); } else { return this.select(e, item); } } }, toggleLoadedItem: { value: function (e, item) { if (this.isLoaded(item)) { return this.unload(e, item); } else { return this.load(e, item); } } }, handleFocus: { value: function (e, items) { items = items ? _.array(items) : []; var item = items.first(); this.onFocus({ event: e, item: item, items: items }); } }, handleRemove: { value: function (e, items) { items = items ? _.array(items) : []; var item = items.first(); return this.onRemove({ event: e, item: item, items: items }); } }, handleMove: { value: function (e, index, steps) { return this.onMove({ event: e, item: this.items[index], steps: steps }); } }, select: { value: function (e, items) { items = items ? _.array(items) : []; var item = items.first(); return this.onSelect({ event: e, item: item, items: items }); } }, deselect: { value: function (e, items) { items = items ? _.array(items) : []; var item = items.first(); return this.onDeselect({ event: e, item: item, items: items }); } }, isSelected: { value: function (item) { return this.selectedItems.contains(item); } }, load: { value: function (e, items) { items = items ? _.array(items) : []; var item = items.first(); return this.onLoad({ event: e, item: item, items: items }); } }, unload: { value: function (e, items) { items = items ? _.array(items) : []; var item = items.first(); return this.onUnload({ event: e, item: item, items: items }); } }, isLoaded: { value: function (item) { return this.loadedItems.contains(item); } } }); function featureListComponent(templateUrl) { return { controller: ["featureHelper", FeatureListViewModel], bindings: { display: "<", items: "<", selectedItems: "<", loadedItems: "<", onChange: "&", onSelect: "&", onDeselect: "&", onLoad: "&", onUnload: "&", onFocus: "&", onRemove: "&", onMove: "&" }, templateUrl: ["config", function (config) { return config.baseUrl + "/" + templateUrl + "?v=" + config.version; }], transclude: { featureHeader: "?headerTemplate" } } } return featureListComponent; })(); var vectorfeatures = vectorfeatures || {}; vectorfeatures.FeatureManager = (function () { "use strict"; function FeatureManager(featureHelper) { Object.defineProperties(this, { _enabled: { value: false, writable: true }, //canEdit: { value: false, writable: true, enumerable: true }, filter: { value: {}, writable: true, enumerable: true }, _serial: { value: -1, writable: true }, _originalScales: { value: [], writable: true }, _itemsScale: { value: 100, writable: true }, _featureHelper: { value: featureHelper }, _data: { value: [], writable: true }, _items: { value: [], writable: true }, _selected: { value: [] }, _loaded: { value: [] }, _interfaceModes: { value: [], enumerable: true } }); } EventHandler.injectInto(FeatureManager.prototype); Object.defineProperties(FeatureManager.prototype, { enabled: { get: function () { return this._enabled; }, enumerable: true }, interfaceModes: { get: function () { return this._interfaceModes; }, enumerable: true }, itemsScale: { get: function () { return this._itemsScale; }, set: function (value) { this.setItemsScale(value); }, enumerable: true }, items: { get: function () { return this._items; }, set: function (value) { this.setItems(value); }, enumerable: true }, itemsCount: { get: function () { return this.items.length; }, enumerable: true }, totalItemsCount: { get: function () { return this._data.length; }, enumerable: true }, selectedItems: { get: function () { return this._selected; }, set: function (value) { this.setSelectedItems(value); }, enumerable: true }, loadedItems: { get: function () { return this._loaded; }, set: function (value) { this.setLoadedItems(value); }, enumerable: true }, // init init: { value: function (o) { var mgr = this; o = o || {}; return Promise.resolve() .then(function () { if ("enabled" in o) { mgr._enabled = !!o.enabled; } }) .then(function () { if ("modes" in o) { return mgr.removeModes(mgr.interfaceModes) .then(function () { return mgr.addModes(o.modes); }); } return null; }) .then(function () { mgr.filter = o.filter || {}; mgr._data = o.items || []; mgr._selected.clear().addRange(o.selectedItems || []); mgr._loaded.clear().addRange(o.loadedItems || []); //console.log("FM.INIT", { mgr: mgr }); return mgr.list(); }) .then(function (arg) { return mgr.trigger("init", arg) .then(function () { //console.log("FM.ITEMS", { items: mgr.items }); return arg; }); }); } }, enable: { value: function (value) { var enabled = !!value; var arg = { enabled: enabled }; var promise = Promise.resolve(); if (this._enabled !== enabled) { this._enabled = enabled; promise = this.trigger("change-enabled", arg); } return promise .then(function () { return arg; }); } }, hasMode: { value: function (value) { return this._interfaceModes.contains(value); } }, addModes: { value: function (value) { return this.setModes(this.interfaceModes.concat(_.array(value || []))); } }, removeModes: { value: function (value) { return this.setModes(this.interfaceModes.except(_.array(value || []))); } }, setModes: { value: function (modes) { var mgr = this; modes = _.array(modes || []).distinct(); var oldValue = mgr._interfaceModes.select(); var added = modes.except(oldValue); var removed = oldValue.except(modes); mgr._interfaceModes.clear().addRange(modes); return Promise.resolve({ items: modes, added: added, removed: removed }) .then(function (arg) { var promise = Promise.resolve(); if (added.length || removed.length) { promise = mgr.trigger("change-interface-modes", arg); } return promise.then(function () { return arg; }); }); } }, // new features getNewId: { value: function () { var mgr = this; return Promise.resolve((this._data.max(function (item) { return mgr._featureHelper.getProperty(item, "id"); }) || 0) + 1); } }, getNewPoint: { value: function (options, geometry, crs) { var item; options = options || {}; if (options.isLabel) { item = this._featureHelper.createLabel(options, geometry, crs); } else if (options.isImage) { item = this._featureHelper.createImage(options, geometry, crs); } else { item = this._featureHelper.createPoint(options, geometry, crs); } this._featureHelper.setProperty(item, "id", this._serial--); if (options.resizeByScale) { this._featureHelper.setProperty(item, "resizeByScale", options.resizeByScale); } if (options.width && options.height) { this._featureHelper.setProperty(item, "originalSize", { width: options.width, height: options.height }); } return Promise.resolve(item); } }, getNewImage: { value: function (options, geometry, crs) { options.isImage = true; return this.getNewPoint(options, geometry, crs); } }, getNewLabel: { value: function (options, geometry, crs) { options.isLabel = true; return this.getNewPoint(options, geometry, crs); } }, getNewLineString: { value: function (options, geometry, crs) { var item = this._featureHelper.createLineString(options, geometry, crs); this._featureHelper.setProperty(item, "id", this._serial--); var style = this._featureHelper.getStyle(item); if (options.measure) { style.stroke.measure = options.measure; } if (options.arrowLocation) { style.stroke.arrowLocation = options.arrowLocation; } if (options.labelLocation) { style.stroke.labelLocation = options.labelLocation; } return Promise.resolve(item); } }, getNewPolygon: { value: function (options, geometry, crs) { var item = this._featureHelper.createPolygon(options, geometry, crs); this._featureHelper.setProperty(item, "id", this._serial--); return Promise.resolve(item); } }, copyItem: { value: function (source, geometry) { var item = $.extend(true, {}, source); console.log("FM.COPY_ITEM", this._serial, { source: source, item: item, geometry: geometry, mgr: this }); this._featureHelper.setProperty(item, "id", this._serial--); this._featureHelper.setGeometry(item, geometry); return Promise.resolve(item); } }, details: { value: function (id) { return Promise.resolve(this._data.first(function (x) { return x.properties.id === id; })); } }, list: { value: function () { var mgr = this; var filter = mgr.filter || {}; return Promise.resolve(mgr._data) .then(function (items) { return mgr._filter(items, filter); }) .then(function (items) { return mgr.setItems(items); }); } }, _getImageTitle: { value: function (item) { var mgr = this; var style = mgr._featureHelper.getStyle(item); var title = Q.queryUrl("identifier", style.image.iconUrl); if (title == null) { title = style.image.iconUrl; } if (title != null) { title = title.split("/").last().split(".").first(); } return title; } }, save: { value: function (items) { items = _.array(items); var mgr = this; console.log("FM.SAVING", { items: items, mgr: mgr }); return items .aggregate(function (r, item) { return r.then(function (results) { return mgr._saveItem(item) .then(function (saved) { results.push(saved); return results; }); }); }, Promise.resolve([])) .then(function (results) { var added = results.where(function (x) { return x.isNew; }).select(function (x) { return x.item; }); var items = results.select(function (x) { return x.item; }); var modified = items.except(added); return { added: added, modified: modified, items: items }; }) .then(function (arg) { return Promise.resolve() .then(function () { if (arg.added.length > 0) { mgr._featureHelper.setSortOrder(mgr._data); return mgr.list(); } return true; }) .then(function () { return mgr.trigger("save-items", arg); }) .then(function () { return arg.items; }); }); } }, _saveItem: { value: function (item) { var mgr = this; var style = mgr._featureHelper.getStyle(item); var itemId = mgr._featureHelper.getProperty(item, "id"); var isNew = itemId <= 0 || !mgr._data.contains(item); return Promise.resolve(item) .then(function () { if (isNew) { return mgr.getNewId() .then(function (newId) { //console.log("SETTING_NEWID", { item: item, newId: newId, mgr: mgr }); itemId = newId; mgr._featureHelper.setProperty(item, "id", itemId); return item; }); } return true; }) .then(function () { // label if (isNew && mgr._featureHelper.isLabel(item)) { if (!style.label.text) { style.label.text = "New label #" + itemId; } } // icon if (mgr._featureHelper.isImage(item)) { var imgStyle = style.image; if (imgStyle.iconUrl.startsWith("http")) { imgStyle.iconUrl = "Handlers/Proxy.aspx?u=" + encodeURIComponent(imgStyle.iconUrl); } } return true; }) .then(function () { // title if (mgr._featureHelper.getProperty(item, "title") == null) { if (mgr._featureHelper.isLabel(item)) { mgr._featureHelper.setProperty(item, "title", "Label #" + itemId); } else if (mgr._featureHelper.isImage(item)) { var title = mgr._getImageTitle(item); mgr._featureHelper.setProperty(item, "title", title || "Image #" + itemId); } else { mgr._featureHelper.setProperty(item, "title", "Item #" + itemId); } } }) .then(function () { if (isNew) { var listItems = mgr.items; if (mgr._featureHelper.isPolygon(item)) { //console.log("FM.SAVING_POLYGON"); // add new item on top of other polygons, but below points and lines var lastDataPolygon = mgr._data.where(function (x) { return mgr._featureHelper.isPolygon(x); }).last(); var lastDataPolygonIndex = mgr._data.indexOf(lastDataPolygon); mgr._data.splice(lastDataPolygonIndex + 1, 0, item); var lastItemsPolygon = listItems.where(function (x) { return mgr._featureHelper.isPolygon(x); }).last(); var lastItemsPolygonIndex = listItems.indexOf(lastItemsPolygon); listItems.splice(lastItemsPolygonIndex + 1, 0, item); } else { mgr._data.add(item); listItems.add(item); } } return { item: item, isNew: isNew }; }); } }, remove: { value: function (items) { var mgr = this; items = _.array(items); var removed = mgr._data.where(function (d) { return items.any(function (r) { return mgr._equalsItem(d, r); }); }); // deselect items mgr.deselectItems(removed); // remove from _data mgr._data.remove(function (x) { return removed.contains(x); }); return Promise.resolve() .then(function () { if (!removed.length) { return null; } var promise = Promise.resolve(); var selectedRemoved = removed.where(function (x) { return mgr.isSelected(x); }); if (selectedRemoved.any()) { promise = mgr.setSelectedItems(mgr.selectedItems.except(selectedRemoved)); } return promise .then(function () { return mgr.setItems(mgr.items.except(removed)); }); }) .then(function () { return mgr.trigger("remove-items", { items: removed }); }) .then(function () { return removed; }); } }, importItems: { value: function (items) { var mgr = this; return mgr.save(items.select(function (item) { var copy = $.extend(true, {}, item); mgr._featureHelper.setProperty(copy, "id", mgr._serial--); return copy; })); } }, _filter: { value: function (items, filter) { var mgr = this; return items.where(function (x) { return (filter.q == null || (mgr._featureHelper.getProperty(x, "title") || "").contains(filter.q, true)) && (filter.geomType == null || mgr._featureHelper.getGeometry(x).type === filter.geomType); }); } }, // (un)load items loadItems: { value: function (items, options) { items = _.array(items); return this.setLoadedItems(this.loadedItems.concat(items).distinct(), options); } }, unloadItems: { value: function (items) { var mgr = this; items = _.array(items); var itemsToRemove = mgr.loadedItems.where(function (x) { return items.any(function (o) { return mgr._equalsItem(x, o); }); }); return mgr.setLoadedItems(mgr.loadedItems.except(itemsToRemove)); } }, toggleLoaded: { value: function (item) { return this.isLoaded(item) ? this.unloadItems(item) : this.loadItems(item); } }, // (un)selecting items selectItem: { value: function (item) { return this.selectItems(_.array(item)); } }, selectItems: { value: function (items) { return this.setSelectedItems(this.selectedItems.concat(_.array(items)).distinct()); } }, deselectItem: { value: function (item) { return this.deselectItems([item]); } }, deselectItems: { value: function (items) { var mgr = this; items = _.array(items); var itemsToRemove = mgr.selectedItems.where(function (x) { return items.any(function (o) { return mgr._equalsItem(x, o); }); }); return mgr.setSelectedItems(mgr.selectedItems.except(itemsToRemove)); } }, toggleSelected: { value: function (item) { return this.isSelected(item) ? this.deselectItem(item) : this.selectItem(item); } }, move: { value: function (item, steps) { var mgr = this; var oldIndex = mgr._data.indexOf(item); var newIndex = oldIndex + steps; mgr._data.move(item, newIndex); mgr._featureHelper.setSortOrder(mgr._data); var arg = { item: item, oldIndex: oldIndex, newIndex: newIndex }; return mgr.list() .then(function () { return mgr.trigger("change-item-index", arg); }) .then(function () { return arg; }); } }, triggerModifyItems: { value: function (items) { items = _.array(items || []); var arg = { modified: items, items: items }; return this.trigger("modify-items", arg) .then(function () { return arg; }); } }, // focus (zoom) focus: { value: function (items, options) { var mgr = this; var onReady; var arg = $.extend({}, options, { items: items }); return mgr.trigger("focussing", { items: items, options: options, onReady: function (callback) { onReady = callback; } }) .then(function () { return mgr.trigger("focus", arg); }) .then(function () { if (typeof (onReady) === "function") { return onReady({ items: items }); } return true; }) .then(function () { return arg; }); } }, setItemsScale: { value: function (items, value) { var mgr = this; var oldItemsScale = mgr._itemsScale; mgr._itemsScale = value; //console.log("FM.SET_ITEMS_SCALE", { scale: value, items: items, mgr: mgr }); items .forEach(function (item) { var itemId = mgr._featureHelper.getProperty(item, "id"); var itemStyle = mgr._featureHelper.getStyle(item); var original = mgr._originalScales.first(function (x) { return x.id === itemId; }); if (original == null) { original = { id: itemId, scale: itemStyle.image.scale }; mgr._originalScales.push(original); } itemStyle.image.scale = original.scale * (value / 100); }); var arg = { oldItemsScale: oldItemsScale, newItemsScale: value, items: items }; return mgr.trigger("change-items-scale", arg) .then(function () { return arg; }); } }, resetItemsScale: { value: function () { return this.setItemsScale(100); } }, setItems: { value: function (value) { var mgr = this; var oldValue = this._items.select(); var arg = { added: value.where(function (v) { return oldValue.all(function (o) { return mgr._equalsItem(o, v); }); }), removed: oldValue.where(function (v) { return value.all(function (o) { return mgr._equalsItem(o, v); }); }), oldValue: oldValue, items: this._items }; var newFeatures = _.array(value || []); mgr._items.clear().addRange(newFeatures); newFeatures.forEach(function (feature) { var style = mgr._featureHelper.getStyle(feature); var isSnappable = (style.stroke && style.stroke.type === "measure"); //console.log("CHANGE_FEATURE_STYLE", { feature: feature, isSnappable: isSnappable }); mgr._featureHelper.setProperty(feature, "snappable", isSnappable); }); return mgr.trigger("change-items", arg) .then(function () { return arg; }); } }, setSelectedItems: { value: function (value) { var mgr = this; //console.log("FM.SET_SELECTED_ITEMS", { value: value, mgr: mgr }); var oldValue = mgr._selected.select(); return Promise.resolve(_.array(value)) .then(function (items) { var added = items.where(function (v) { return oldValue.all(function (o) { return !mgr._equalsItem(o, v); }); }); var removed = oldValue.where(function (v) { return items.all(function (o) { return !mgr._equalsItem(o, v); }); }); var arg = { oldValue: oldValue, selectedItems: mgr._selected, added: added, removed: removed, hasSelected: added.length, hasUnselected: removed.length }; // update selected items Array.prototype.splice.apply(mgr._selected, [0, mgr._selected.length].concat(items)); // only trigger event when changes occured if (arg.hasSelected || arg.hasUnselected) { return mgr.trigger("change-selected-items", arg); } return arg; }); } }, isSelected: { value: function (item) { var mgr = this; return this.selectedItems.any(function (x) { return mgr._equalsItem(x, item); }); } }, setLoadedItems: { value: function (value) { var mgr = this; //console.log("FM.SET_LOADED_ITEMS", { value: value, mgr: mgr }); var oldValue = mgr._loaded.select(); return Promise.resolve(_.array(value)) .then(function (items) { var added = items.where(function (v) { return oldValue.all(function (o) { return !mgr._equalsItem(o, v); }); }); var removed = oldValue.where(function (v) { return items.all(function (o) { return !mgr._equalsItem(o, v); }); }); var arg = { oldValue: oldValue, items: mgr._loaded, added: added, removed: removed, hasLoaded: added.length, hasUnloaded: removed.length }; // update selected items Array.prototype.splice.apply(mgr._loaded, [0, mgr._loaded.length].concat(items)); // only trigger event when changes occured if (arg.hasLoaded || arg.hasUnloaded) { return mgr.trigger("change-loaded-items", arg); } return arg; }); } }, isLoaded: { value: function (item) { var mgr = this; return this.loadedItems.any(function (x) { return mgr._equalsItem(x, item); }); } }, _equalsItem: { value: function (item1, item2) { return item1 === item2; //return item1 === item2 || (item1 != null && item2 != null && this._featureHelper.getProperty(item1, "id") === this._featureHelper.getProperty(item2, "id")); } } }); return FeatureManager; })(); var vectorfeatures = vectorfeatures || {}; vectorfeatures.FeatureFabricConverter = (function () { "use strict"; function FeatureFabricConverter(featureHelper, gisViewerManager, imageHelper) { Object.defineProperties(this, { _helper: { value: featureHelper }, _viewer: { value: gisViewerManager }, _imageHelper: { value: imageHelper } }); } Object.defineProperties(FeatureFabricConverter.prototype, { viewerScale: { get: function () { return this._viewer.scale; }, enumerable: true }, unitsPerPixel: { get: function () { return this._viewer.unitsPerPixel; }, enumerable: true }, createItems: { value: function (features) { var cv = this; return Promise.all(_.array(features) .select(function (feature) { return cv._createItem(feature); })); } }, _createItem: { value: function (feature) { var cv = this; return cv._viewer.getPixelFromCoordinate(feature.geometry.coordinates) .then(function (pixel) { var item; var style = cv._helper.getStyle(feature); if (cv._helper.isImage(feature)) { var size = cv._helper.calcImageSize(feature, cv._viewer.scale); var url = cv._helper.getImageUrl(feature); return cv._imageHelper.getImageFromUrl(url) .then(function (img) { var scaleX = size[0] / img.width; var scaleY = size[1] / img.height; item = new fabric.Image(img, { left: pixel[0], top: pixel[1], originX: "center", originY: "center", width: img.width, height: img.height, scaleX: scaleX, scaleY: scaleY, angle: style.rotation || 0, opacity: cv._helper.getOpacity(feature), centeredScaling: true, //centeredRotation: true, //lockUniScaling: true, //lockScalingFlip: true }); //console.log("FFC.FROM_FEATURE", { imgSize: [img.width, img.height], size: size, feature: feature, item: item, pixel: pixel }); return item; }); } else { item = new fabric.Label(); } return item; }) .then(function (item) { item.set("_feature", feature); item.set("_state", { moved: false, resized: false, rotated: false }); //console.log("CREATE_ITEM", { item: item, feature: feature }); return item; }); } }, updateItem: { value: function (item, parent) { var cv = this; return cv.getFeature(item) .then(function (feature) { parent.remove(item); return cv._createItem(feature); }); } }, updateFeature: { value: function (item) { var cv = this; return cv.getFeature(item) .then(function (feature) { return cv.getState(item) .then(function (state) { if (state.resized || state.rotated) { var style = cv._helper.getStyle(feature); // rotation if (state.rotated) { var rotation = parseInt(cv.getItemAngle(item), 10) % 360; style.rotation = rotation; } // size if (state.resized) { var imgStyle = style.image; console.log("FBC.RESIZE", { item: item, feature: feature }, 'viewerScale', cv.viewerScale, 'unitsPerPixel', cv.unitsPerPixel); console.log('FBC.RESIZE before', 'style.width', style.width, 'style.height', style.height, 'imgStyle.width', imgStyle.width, 'imgStyle.height', imgStyle.height, 'imgStyle.scale', imgStyle.scale); style.width = cv._helper.calcWidthUnits(feature, cv.viewerScale, cv.unitsPerPixel); style.height = cv._helper.calcHeightUnits(feature, cv.viewerScale, cv.unitsPerPixel); var widthPixels = item.width * item.scaleX; imgStyle.scale = widthPixels / style.image.width * cv.viewerScale; console.log('FBC.RESIZE after', 'style.width', style.width, 'style.height', style.height, 'imgStyle.width', imgStyle.width, 'imgStyle.height', imgStyle.height, 'imgStyle.scale', imgStyle.scale); } } if (state.moved) { // coordinates var pixel = cv.getItemPixel(item).select(function (x) { return x; }); return cv._viewer.getCoordinateFromPixel(pixel) .then(function (coordinate) { feature.geometry.coordinates = coordinate; return feature; }); } return Promise.resolve(feature); }); }); } }, getItemPixel: { value: function (item) { var center = item.getCenterPoint(); var pixel = [center.x, center.y]; if (item.group != null) { var groupPixel = this.getItemPixel(item.group); pixel = [pixel[0] + groupPixel[0], pixel[1] + groupPixel[1]]; } return pixel; } }, getItemScale: { value: function (item) { var scale = item.scaleX; if (item.group != null) { scale *= (this.getItemScale(item.group) || 1); } return scale; } }, getItemAngle: { value: function (item) { var angle = item.angle; if (item.group != null) { angle += this.getItemAngle(item.group); } return angle; } }, getFeatures: { value: function (items) { var cv = this; return Promise.all(_.array(items || []).select(function (item) { return cv.getFeature(item); })); } }, getFeature: { value: function (item) { return Promise.resolve(item.get("_feature")); } }, getState: { value: function (item) { return Promise.resolve(item.get("_state")); } }, setState: { value: function (item, o) { return this.getState(item) .then(function (state) { return $.extend(state, o); }); } } }); return FeatureFabricConverter; })(); var vectorfeatures = vectorfeatures || {}; vectorfeatures.FeatureFabricManager = (function () { "use strict"; function FeatureFabricManager(canvasEl, featureFabricConverter, imageHelper) { var mgr = this; canvasEl = $(canvasEl); Object.defineProperties(mgr, { _items: { value: [] }, _selectedItems: { value: [] }, canvas: { configurable: true, enumerable: true }, _canvasEl: { value: canvasEl }, _enabled: { value: false, writable: true }, _converter: { value: featureFabricConverter }, _imageHelper: { value: imageHelper } }); } EventHandler.injectInto(FeatureFabricManager.prototype); Object.defineProperties(FeatureFabricManager.prototype, { enabled: { get: function () { return this._enabled; }, enumerable: true }, items: { get: function () { return this._items; }, enumerable: true }, selectedItems: { get: function () { return this._selectedItems; }, enumerable: true }, // init init: { value: function (o) { o = o || {}; var mgr = this; //console.log("FFM.INIT", { o: o, mgr: mgr }); return Promise.resolve() .then(function () { if (typeof (mgr.canvas) === "undefined") { return Promise.resolve(mgr._setCanvas()); } return true; }) .then(function () { if ("enabled" in o) { return mgr.enable(o.enable); } return true; }) .then(function () { if (_.isArray(o.items)) { return mgr.setItems(o.items); } return true; }) .then(function () { if (_.isArray(o.selectedItems)) { return mgr.setSelectedItems(o.selectedItems); } return true; }) .then(function () { return mgr.trigger("init", {}); }); } }, enable: { value: function (value) { var enabled = !!value; var mgr = this; return Promise.resolve({ enabled: enabled }) .then(function (arg) { if (mgr._enabled !== enabled) { mgr._enabled = enabled; return mgr.trigger("change-enabled", arg) .then(function () { return arg; }); } return arg; }); } }, _setCanvas: { value: function () { var mgr = this; Object.defineProperty(mgr, "canvas", { value: new fabric.Canvas(mgr._canvasEl.get(0), { //selection: false, backgroundColor: "transparent", width: mgr._canvasEl.width(), height: mgr._canvasEl.height() }) }); mgr.canvas.setBackgroundColor(null, mgr.canvas.renderAll.bind(mgr.canvas)); mgr._setCanvasEvents(); } }, _setCanvasEvents: { value: function () { var mgr = this; var cloning = false; var moving = false; var resizing = false; var rotating = false; function onSelectionChange(e) { //console.log("FFM.SELECTION_CHANGE", { evt: e, canvas: mgr.canvas, activeObject: mgr.canvas.getActiveObject() }); var activeObject = mgr.canvas.getActiveObject(); if (activeObject != null) { //activeObject.lockUniScaling = true; activeObject.centeredScaling = true; activeObject.centeredRotation = true; activeObject .on("mouseover", function (e) { e.e.preventDefault(); return false; }) .on("mousedown", function (e) { if (e.e.ctrlKey) { cloning = true; } }) .on("scaling", function () { resizing = true; }) .on("rotating", function () { rotating = true; }) .on("moving", function () { if (!moving && cloning) { mgr._converter.getFeatures(mgr.flatItems(activeObject)) .then(function (features) { return mgr.trigger("start-copy", { items: features }); }); } moving = true; }) .on("modified", function (e) { //console.log("FFM.OBJ_MODIFIED", { evt: e, cloned: cloning, moved: moving, me: this, active: activeObject, mgr: mgr }); var cloned = cloning; var moved = moving; var resized = resizing; var rotated = rotating; var target = this; return Promise.resolve() .then(function () { var items = mgr.flatItems(target); return Promise .all(items.select(function (item) { return mgr._converter.setState(item, { moved: moved || ((rotated || resized) && items.length > 1), resized: resized, rotated: rotated }); })) .then(function () { if (moved) { moving = false; if (cloned) { cloning = false; return mgr.copy(target); } } if (resized) { resizing = false; } if (rotated) { rotating = false; } return mgr._onModify(mgr.flatItems(target)); }); }); }); } var selectedItems = mgr.flatItems(activeObject); return mgr._onChangeSelectedItems(e.e, selectedItems) .then(function (arg) { mgr._setSelectedItems(selectedItems); return arg; }); } mgr.canvas .on("object:added", function (/*e*/) { //console.log("FFM.ADDED", { evt: e, mgr: mgr }); }) .on("selection:created", onSelectionChange) .on("selection:updated", onSelectionChange) .on("selection:cleared", onSelectionChange) .on("mouse:down", function (/*e*/) { //console.log("FFM.CV_MOUSE_DOWN", { evt: e, me: this, active: mgr.canvas.getActiveObject(), mgr: mgr }); }); } }, _list: { value: function () { return this.canvas.getObjects(); } }, flatItems: { value: function (items) { var mgr = this; return _.array(items || []) .selectMany(function (item) { if (item.getObjects) { return mgr.flatItems(item.getObjects()); } return [item]; }); } }, list: { value: function () { return this._helper.getFeatures(this._list()); } }, groupItems: { value: function () { if (!this.canvas.getActiveObject()) { return null; } var group = null; if (this.canvas.getActiveObject().type === 'group') { //ungroup group = this.canvas.getActiveObject().toActiveSelection(); console.log("UNGROUP", { group: group, activeObject: this.canvas.getActiveObject(), canvas: this.canvas }); } else if (this.canvas.getActiveObject().type === 'activeSelection') { //group group = this.canvas.getActiveObject().toGroup(); console.log("GROUP", { group: group, activeObject: this.canvas.getActiveObject(), canvas: this.canvas }); } this.canvas.requestRenderAll(); return group; } }, triggerModifyItems: { value: function (features) { var mgr = this; return mgr._getItems(features) .then(function (items) { return mgr._onModify(items); }); } }, update: { value: function (/*features*/) { var mgr = this; return mgr._converter.getFeatures(mgr.items) .then(function (features) { return mgr.setItems(features); }); } }, updateFeatures: { value: function (features) { var mgr = this; return mgr._getItems(features) .then(function (items) { return Promise.all(items.select(function (item) { return mgr._converter.updateFeature(item); })); }); } }, getFeatures: { value: function () { var mgr = this; return mgr._converter.getFeatures(mgr.items); } }, getSelectedFeatures: { value: function () { var mgr = this; return Promise.resolve(mgr.flatItems(mgr.canvas.getActiveObject())) .then(function (items) { return mgr._converter.getFeatures(items); }); } }, _onModify: { value: function (items) { var mgr = this; return mgr._converter.getFeatures(items) .then(function (features) { var arg = { items: features }; return mgr.trigger("modify-items", arg) .then(function () { return arg; }); }); } }, copy: { value: function (items) { var mgr = this; return Promise.resolve(mgr.flatItems(items)) .then(function (items) { return Promise .all(items.select(function (item) { return mgr._converter.getFeature(item) .then(function (feature) { var pixel = mgr._converter.getItemPixel(item); return { item: feature, pixel: pixel }; }); })); }) .then(function (clones) { return mgr.trigger("end-copy", { items: clones }); }); } }, _addItems: { value: function (items) { var mgr = this; _.array(items).forEach(function (item) { mgr.canvas.add(item); }); } }, _removeItems: { value: function (items) { var mgr = this; _.array(items).forEach(function (item) { if (item.getObjects) { mgr._removeItems(item.getObjects()); } else { mgr.canvas.remove(item); } }); } }, setItems: { value: function (features) { var mgr = this; var oldValue = mgr.items.select(); mgr.canvas.clear(); //mgr._removeItems(mgr._list()); //console.log("FFM.SET_ITEMS", { features: features, oldValue: oldValue, mgr: mgr }); mgr.items.clear(); return mgr._converter.createItems(features) .then(function (items) { var added = items.except(oldValue); var modified = oldValue.innerJoin(items); var removed = oldValue.except(items); mgr.items.addRange(items); mgr.items.forEach(function (item) { mgr._addItems(item); }); return Promise .all([ mgr._converter.getFeatures(oldValue), mgr._converter.getFeatures(added), mgr._converter.getFeatures(modified), mgr._converter.getFeatures(removed) ]) .then(function (results) { return { oldValue: results[0], added: results[1], modified: results[2], removed: results[3], items: features }; }) .then(function (arg) { return mgr.trigger("change-items", arg) .then(function () { return arg; }); }); }); } }, _getItems: { value: function (features) { var mgr = this; return mgr.items .aggregate(function (p, item) { return mgr._converter.getFeatures(item) .then(function (myFeatures) { var feature = myFeatures.first(); return p.then(function (items) { if (features.contains(feature)) { items.push(item); } return items; }); }); }, Promise.resolve([])); } }, setSelectedItems: { value: function (selectedFeatures) { var mgr = this; return mgr._getItems(selectedFeatures) .then(function (selectedItems) { return mgr._selectItems(selectedItems) .then(function () { return mgr._setSelectedItems(selectedItems); }); }); } }, _selectItems: { value: function (items) { var mgr = this; return mgr.getSelectedFeatures() .then(function (selectedFeatures) { return mgr._converter.getFeatures(items) .then(function (features) { //console.log("FFM.SELECT", { items: items, features: features, selectedFeatures: selectedFeatures, active: mgr.canvas.getActiveObject() }); if (features.length === selectedFeatures.length && features.innerJoin(selectedFeatures).length === items.length) { return mgr.canvas.getActiveObject(); } mgr.canvas.discardActiveObject(); var activeObject; if (items.length > 1) { activeObject = new fabric.ActiveSelection(items, { canvas: mgr.canvas }); } else { activeObject = items.first(); } mgr.canvas.setActiveObject(activeObject); mgr.canvas.requestRenderAll(); return activeObject; }); }); } }, _setSelectedItems: { value: function (selectedItems) { this.selectedItems.clear().addRange(selectedItems); } }, _onChangeSelectedItems: { value: function (e, selectedItems) { var mgr = this; var oldValue = mgr.selectedItems; var added = selectedItems.except(oldValue); var modified = oldValue.innerJoin(selectedItems); var removed = oldValue.except(selectedItems); return mgr._converter.getFeatures(selectedItems) .then(function (features) { var arg = { oldValue: oldValue, added: added, modified: modified, removed: removed, selectedItems: features, initiator: e instanceof MouseEvent ? "user" : "system" }; return mgr.trigger("change-selected-items", arg) .then(function () { return arg; }); }); } } }); return FeatureFabricManager; })("vectorfeatures"); var vectorfeatures = vectorfeatures || {}; vectorfeatures.geometryComponent = (function () { "use strict"; function GeometryViewModel(geoHelper) { Object.defineProperties(this, { _geoHelper: { value: geoHelper }, _geom: { writable: true }, onChange: { writable: true } }); } Object.defineProperties(GeometryViewModel.prototype, { geom: { get: function () { return this._geom; }, set: function (value) { this.setGeom(value); } }, geomType: { get: function () { if (this.geom == null) { return null; } return this.geom.type; }, enumerable: true }, isSimpleLine: { get: function () { return this.geomType === "LineString" && this._geoHelper.getFlatCoordinates(this._geom.coordinates).length === 2; }, enumerable: true }, wkt: { get: function () { if (this.geom == null) { return null; } return this.geom.wkt; }, set: function (value) { this.setGeom(value); }, enumerable: true }, pointX: { get: function () { if (this.geomType !== "Point") { return null; } return this.geom.coordinates[0]; }, set: function (value) { if (!parseFloat(value)) { return; } var input = this._geom.coordinates; input[0] = +value; this.setGeom(input); }, enumerable: true }, pointY: { get: function () { if (this.geomType !== "Point") { return null; } return this.geom.coordinates[1]; }, set: function (value) { if (!parseFloat(value)) { return; } var input = this._geom.coordinates; input[1] = +value; this.setGeom(input); }, enumerable: true }, startPointX: { get: function () { if (!this.isSimpleLine) { return null; } return this.geom.coordinates[0][0]; }, set: function (value) { if (!parseFloat(value)) { return; } var input = this._geom.coordinates; input[0][0] = +value; this.setGeom(input); }, enumerable: true }, startPointY: { get: function () { if (!this.isSimpleLine) { return null; } return this.geom.coordinates[0][1]; }, set: function (value) { if (!parseFloat(value)) { return; } var input = this._geom.coordinates; input[0][1] = +value; this.setGeom(input); }, enumerable: true }, endPointX: { get: function () { if (!this.isSimpleLine) { return null; } return this.geom.coordinates[1][0]; }, set: function (value) { if (!parseFloat(value)) { return; } var input = this._geom.coordinates; input[1][0] = +value; this.setGeom(input); }, enumerable: true }, endPointY: { get: function () { if (!this.isSimpleLine) { return null; } return this.geom.coordinates[1][1]; }, set: function (value) { if (!parseFloat(value)) { return; } var input = this._geom.coordinates; input[1][1] = +value; this.setGeom(input); }, enumerable: true }, reverse: { value: function () { var geoJson = this.geom.geoJson; var reversed = this._geoHelper.reverse(geoJson); this.setGeom(reversed); return this.handleChange(); } }, handleChange: { value: function (e) { var wkt = this.geom.wkt; var geoJson = this.geom.geoJson; var type = this.geom.type; console.debug("ON_GEOM_CHANGE", { event: e, wkt: wkt, geoJson: geoJson, type: type }); return this.onChange({ event: e, wkt: wkt, geoJson: geoJson, type: type }); } }, setGeom: { value: function (input) { if (!input) { this._geom = null; } else { this._geom = this._geoHelper.getGeom(input); } } } }); function geometryComponent(templateUrl) { return { controller: ["geoHelper", GeometryViewModel], bindings: { geom: " 0 || removed.length > 0) { removed.forEach(function (item) { currentSelection.remove(item); }); currentSelection.extend(added); return mgr._update(removed.concat(added)) .then(function () { return mgr._onChangeSelectedItems(null, selectedItems); }); } return { added: [], removed: [], selectedItems: selectedFeatures }; }); } }, add: { value: function (features) { var mgr = this; return Promise.resolve() .then(function () { //console.log("ADD_FEATURE", { features: features, mgr: mgr }); if (mgr._olLayer != null && features != null && features.length && mgr.layer != null) { return mgr._converter.createItems(features, mgr.layer) .then(function (items) { mgr._add(items); }); } return null; }); } }, update: { value: function (features) { var mgr = this; //console.log("FGM.UPDATE", { features: features, mgr: mgr }); if (mgr._olLayer != null && features != null && features.length) { return mgr._getItems(features) .then(function (items) { return mgr._update(items); }); } return Promise.resolve(); } }, remove: { value: function (features) { var mgr = this; if (mgr._olLayer == null || features == null || features.length === 0) { return Promise.resolve(); } return Promise.resolve() .then(function () { return mgr._getItems(features) .then(function (items) { return mgr._remove(items); }); //return mgr._featureManager.remove({ features: features, layer: mgr.layer }); }); } }, _add: { value: function (items) { var mgr = this; var src = mgr._olLayer.getSource(); src.addFeatures(items); mgr._syncItemsWithLayer(); } }, _update: { value: function (items) { var mgr = this; return Promise.all(items.select(function (item) { return mgr._converter.updateItem(item); })); } }, _remove: { value: function (items) { var mgr = this; var layerSource = mgr._olLayer.getSource(); var selectionFeatures = mgr._olSelection.getFeatures(); items.forEach(function (item) { layerSource.removeFeature(item); selectionFeatures.remove(item); }); return mgr._syncItemsWithLayer() .then(function () { mgr._syncSelectedItemsWithLayer(); }); } }, _onChangeItems: { value: function (e, items) { var mgr = this; var oldValue = mgr.items; return Promise .all([ mgr._converter.getFeatures(oldValue), mgr._converter.getFeatures(items.except(oldValue)), mgr._converter.getFeatures(oldValue.except(items)), mgr._converter.getFeatures(items) ]) .then(function (results) { return { oldValue: results[0], added: results[1], removed: results[2], items: results[3] } }) .then(function (arg) { if (arg.modified.length > 0 || arg.added.length > 0 || arg.removed.length > 0) { return mgr._syncSelectedItemsWithLayer(); } if (arg.added.length > 0 || arg.removed.length > 0) { return this.trigger(new Event("change-items", e), arg) .then(function () { return arg; }); } return arg; }); } }, _onChangeSelectedItems: { value: function (e, selectedItems) { var mgr = this; selectedItems = _.array(selectedItems || []); var oldValue = mgr.selectedItems; mgr._olModifyCollection.clear(); mgr._olModifyCollection.extend(mgr._olSelection.getFeatures().getArray().where(function (x) { var dataItem = x.get("data-item"); return !dataItem || !dataItem.properties || !dataItem.properties.readonly; })); //console.log("FGM.CHANGE_SELECTED", { selectedItems: selectedItems, mgr: mgr }); return Promise .all([ mgr._converter.getFeatures(oldValue), mgr._converter.getFeatures(selectedItems.except(oldValue)), mgr._converter.getFeatures(oldValue.except(selectedItems)), mgr._converter.getFeatures(selectedItems) ]) .then(function (results) { return { initiator: e != null ? e.initiator : "system", oldValue: results[0], added: results[1], removed: results[2], selectedItems: results[3] } }) .then(function (arg) { if (arg.added.length > 0 || arg.removed.length > 0) { return mgr._syncSelectedItemsWithLayer() .then(function () { return mgr.trigger(new Event("change-selected-items", e), arg); }) .then(function () { return arg; }); } return arg; }); } }, _onModify: { value: function (e, items) { var mgr = this; items = _.array(items || []); return mgr._converter.getFeatures(items) .then(function (features) { return mgr.trigger(new Event("modify-items", e), { modified: features }); }); } } }); return FeatureGisManager; })("vectorfeatures"); //var vectorfeatures = vectorfeatures || {}; //vectorfeatures.OlSelectionManager = (function () { // "use strict"; // function OlSelectionManager(gisViewer, featureHelper) { // var mgr = this; // Object.defineProperties(mgr, { // _viewer: { value: gisViewer }, // _helper: { value: featureHelper } // }); // gisViewer.on("map-load", function () { // var viewerInstance = gisViewer.element.data("geoitGisviewer"); // var map = viewerInstance._ol.map; // Object.defineProperties(mgr, { // _viewerInstance: { value: viewerInstance }, // _olMap: { value: map }, // _selectInteraction: { value: viewerInstance._ol.interactions.select } // }); // }); // } // Object.defineProperties(OlSelectionManager.prototype, { // scale: { // get:function() { // var resolution = this._olMap.view.getResolution(); // var inchesPerMeter = 39.3701; // var dpi = 96; // return resolution * inchesPerMeter * dpi; // } // }, // _selection: { // get: function () { return this._selectInteraction.getFeatures() } // }, // _setEvents: { // value: function () { // var mgr = this; // function getClickExtent(c, tolerance) { // return [[ // [Math.floor(c[0] - tolerance), Math.floor(c[1] - tolerance)], // [Math.floor(c[0] - tolerance), Math.ceil(c[1] + tolerance)], // [Math.ceil(c[0] + tolerance), Math.ceil(c[1] + tolerance)], // [Math.ceil(c[0] + tolerance), Math.floor(c[1] - tolerance)], // [Math.floor(c[0] - tolerance), Math.floor(c[1] - tolerance)] // ]]; // } // me._ol.interactions.select.on("select", function (e) { // console.log("OLV.SELECT_INTERACTION", { evt: e }); // var shiftKey = e.mapBrowserEvent.originalEvent.shiftKey; // var olSelected = e.selected;// me._ol.interactions.select.getFeatures().getArray(); // var olDeselected = e.deselected; // var selectedLayer; // function doSelect() { // if (olSelected.any()) { // //console.log("OL.SELECT", e, "olFeatures", olSelected, selectedLayer.get("lgLayer")); // me._refreshLayer(me._ol.layers.selection, function () { // me._setSelectedFeatures({ layer: selectedLayer, features: olSelected, initiator: "user" }, function (arg) { // me._onSelectionChanged(arg); // }); // }); // } else { // me.getScale(function (scale) { // var tolerance = Math.round(scale / 5) / 250; // var geom = getClickExtent(e.mapBrowserEvent.coordinate, tolerance); // me._geoHelper.GetWKT(geom, function (wkt) { // me._getSelectableLayers(function (layers) { // var mgLayers = layers.where(function (x) { return !x.Type.startsWith("F"); }); // //console.log("CLICK.SELECT", { layers: mgLayers.toDictionary(function (x) { return x.Code; }), wkt: wkt }); // me.setSelection({ geom: wkt, layers: mgLayers, multi: false, preserve: shiftKey, initiator: "user" }); // }); // }); // }); // } // } // //console.log("OL.SELECTING", { evt: e, target: e.target, selected: olSelected, deselected: olDeselected }); // if (olDeselected && olDeselected.any()) { // function setSelect() { // if (olSelected && olSelected.any()) { // selectedLayer = e.target.getLayer(olSelected.last()); // if (!selectedLayer.get("lgLayer")) { // //console.log("OL.SELECTING_IGNORE", { evt: e, selectedLayer: selectedLayer }); // return; // } // } // doSelect(); // } // if (olDeselected.any(function (x) { return !x.get("hidden"); })) { // me._updateFeatures({ // features: olDeselected.where(function (x) { return !x.get("hidden"); }) // .where(function (x) { return e.target.getLayer(x) && e.target.getLayer(x).get("lgLayer"); }) // .select(function (x) { return x.get("data-item"); }) // }, setSelect); // } else { // setSelect(); // } // } // }); // } // }, // getSelectedItems: { // value: function () { // return Promise.resolve(this._selection.getArray()); // } // }, // setSelectedItems: { // value: function (selectedItems) { // var mgr = this; // //console.log("FGM.SET_SELECTED", { features: selectedFeatures, mgr: mgr }); // var currentSelection = mgr._selection; // var added = selectedItems.except(mgr._selectedItems); // var removed = mgr._selectedItems.except(selectedItems); // if (added.length > 0 || removed.length > 0) { // removed.forEach(function (item) { // currentSelection.remove(item); // }); // currentSelection.extend(added); // return mgr._update(removed.concat(added)) // .then(function () { // return mgr._onChangeSelectedItems(null, selectedItems); // }); // } // return { added: [], removed: [], selectedItems: selectedFeatures }; // } // }, // isSelected: { // value: function (item) { // return this._selectInteraction.getFeatures().getArray().contains(item); // } // } // }); // return OlSelectionManager; //})(); var vectorfeatures = vectorfeatures || {}; vectorfeatures.OlStyleManager = (function () { "use strict"; function OlStyleManager(gisViewer, featureHelper) { var mgr = this; Object.defineProperties(mgr, { _viewer: { value: gisViewer }, _helper: { value: featureHelper } }); gisViewer.on("map-load", function () { Object.defineProperties(mgr, { _viewerInstance: { value: gisViewer.element.data("geoitGisviewer") } }); }); } Object.defineProperties(OlStyleManager.prototype, { getStyle: { value: function (item, resolution) { var mgr = this; var styles = []; if (mgr.isSelected(item)) { styles.addRange(mgr.getSelectedStyle(item, resolution)); } else { styles.addRange(mgr.getDefaultStyle(item, resolution)); } return styles; } }, getDefaultStyle: { value: function (item, resolution) { return this._viewerInstance._getOlStyles.call(this._viewerInstance, { feature: item, featureStyle: item.get("data-getStyle")(), resolution: resolution }); } }, getSelectedStyle: { value: function (item, resolution) { return this._viewerInstance._getOlStyles.call(this._viewerInstance, { feature: item, featureStyle: $.extend({}, this._viewerInstance._ol.styles.selection, item.get("data-getSelectionStyle")() || {}), baseFeatureStyle: item.get("data-getStyle")(), resolution: resolution }); } }, isSelected: { value: function (item) { return this._viewerInstance._ol.interactions.select.getFeatures().getArray().contains(item); } } }); return OlStyleManager; })(); var vectorfeatures = vectorfeatures || {}; vectorfeatures.FeatureHelper = (function () { "use strict"; function FeatureHelper(defaults) { Object.defineProperties(this, { gis: { value: new GeoHelper() }, _defaults: { value: defaults || { crsName: "EPSG:31370", transparency: 0, radius: 5, fontSize: 10, labelColor: "#333", lineColor: "#333", lineWidth: 2, lineType: "solid", fillColor: "#bbb" } } }); } Object.defineProperties(FeatureHelper.prototype, { defaults: { get: function () { return this._defaults; }, enumerable: true }, getProperty: { value: function (item, prop) { if (!item.properties) { return null; } return item.properties[prop]; } }, setProperty: { value: function (item, prop, value) { item.properties[prop] = value; } }, getStyle: { value: function (item) { var style = this.getProperty(item, "style") || {}; return style; } }, //geometry getGeometry: { value: function (item) { return item.geometry; } }, setGeometry: { value: function (item, geometry) { item.geometry = geometry; } }, getRotation: { value: function (item) { return this.getStyle(item).rotation || 0; } }, getOpacity: { value: function (item) { var style = this.getStyle(item); return typeof (style.opacity) !== "undefined" ? style.opacity : (100 - style.transparency) / 100; } }, calcScaleFactor: { value: function (item, scale, d) { var style = this.getStyle(item); var itemScale = 0; if (this.isImage(item)) { if (d) { itemScale = style.image['scale' + d.toUpperCase()]; } if (!itemScale) { itemScale = style.image.scale; } } else if (this.isLabel(item)) { itemScale = style.label.scale; } return itemScale / scale; } }, calcHeightUnits: { value: function (item, scale, unitsPerPixel) { var me = this; var heightPixels = me.calcAbsoluteHeightPixels(item, scale); var heightUnits = me.roundDimension(heightPixels * unitsPerPixel); //console.log('feature', item.properties.id, 'calcHeightUnits', heightUnits); return heightUnits; } }, calcPixelsFromUnits: { value: function (units, unitsPerPixel) { return units / unitsPerPixel; } }, calcAbsoluteHeightPixels: { value: function (item, scale) { var heightPixels = 0; var style = this.getStyle(item); if (this.isImage(item)) { var imgScale = style.image.scale; heightPixels = style.image.height * ((imgScale || 1) / scale); } if (this.isLabel(item)) { heightPixels = this.defaults.fontSize * ((style.label.scale || 1) / scale); } return heightPixels; } }, calcWidthUnits: { value: function (item, scale, unitsPerPixel) { var me = this; var widthPixels = me.calcAbsoluteWidthPixels(item, scale); var widthUnits = me.roundDimension(widthPixels * unitsPerPixel); //console.log('feature', item.properties.id, 'calcWidthUnits', widthUnits); return widthUnits; } }, calcAbsoluteWidthPixels: { value: function (item, scale) { var widthPixels = 0; var style = this.getStyle(item); if (this.isImage(item)) { var imgScale = style.image.scale; widthPixels = style.image.width * ((imgScale || 1) / scale); } return widthPixels; } }, _createFeature: { value: function (style, geometry, crs) { return { type: "Feature", properties: { style: style }, geometry: geometry || { coordinates: [], type: null }, crs: { type: "name", properties: { name: crs || this.defaults.crsName } } }; } }, // point createPoint: { value: function (options, geometry, crs) { var style = { color: options.color || this.defaults.lineColor, fillColor: options.fillColor || this.defaults.fillColor, transparency: options.transparency || this.defaults.transparency }; return this._createFeature(style, geometry, crs); } }, // image createImage: { value: function (options, geometry, crs) { var style = { image: { iconUrl: options.url, width: options.width, height: options.height, scale: options.scale }, transparency: +options.transparency || this.defaults.transparency }; return this._createFeature(style, geometry, crs); } }, getImageUrl: { value: function (item) { var style = this.getStyle(item); return style != null && style.image != null ? (style.image.resizedUrl || style.image.iconUrl) : null; } }, getTransformedIconUrl: { value: function (item) { var style = this.getStyle(item); return style != null && style.image != null ? style.image.transformedIconUrl : null; } }, calcTransformedIconSize: { value: function (item) { var style = this.getStyle(item); if (!style || !style.image) { return null; } var imgStyle = style.image; var width = imgStyle._imgEl.width; var height = imgStyle._imgEl.height; if (item.properties && item.properties.resizeByScale && item.properties.originalSize) { width = item.properties.originalSize.width * (96 / 25.4); height = item.properties.originalSize.height * (96 / 25.4); return [width, height]; } //TOOD-rik #8399: de oude berekening verandert de ratio, seems to be the problem? fixen met calculateNewSize te gebruiken //maar dan worden de features in de kaart plots zeer groot //var newSize = new ImageHelper().calculateNewSize({ // width, // height, // targetWidth: 100, // targetHeight: 100 //}) //return [newSize.width, newSize.height]; var originalRatio = imgStyle._imgEl.width / imgStyle._imgEl.height; var newRatio = style.width / style.height; //console.log('FeatureResize', item.properties.title, new Date().toISOString(), 'calcTransformedIconSize', 'style', JSON.stringify(style), 'originalRatio', originalRatio, 'newRatio', newRatio); if (!newRatio || originalRatio === newRatio) { //console.log('FeatureResize', item.properties.title, new Date().toISOString(), 'calcTransformedIconSize', 'ratio unchanged, return null'); return null; } var landscape = imgStyle._imgEl.width > imgStyle._imgEl.height; var baseValue = landscape ? imgStyle._imgEl.width : imgStyle._imgEl.height; var otherValue = baseValue / newRatio; var newWidth = landscape ? baseValue : otherValue; var newHeight = landscape ? otherValue : baseValue; var newSize = [newWidth, newHeight]; //console.log('FeatureResize', item.properties.title, new Date().toISOString(), 'calcTransformedIconSize', 'ratio changed', 'newSize', newSize); return newSize; } }, calcImageSize: { value: function (item, scale) { var style = this.getStyle(item); var imgStyle = style.image; var imgSize = [imgStyle.width, imgStyle.height]; console.log('Feature', item.properties.id, 'calcImageSize', 'style.image.size', imgSize); if (item.properties && item.properties.resizeByScale && item.properties.originalSize) { imgSize = [item.properties.originalSize.width * (96 / 25.4), item.properties.originalSize.height * (96 / 25.4)]; console.log('Feature', item.properties.id, 'calcImageSize', 'style.image.size (resizedByScale)', imgSize); } var factor = this.calcScaleFactor(item, scale); console.log('Feature', item.properties.id, 'calcImageSize', 'scaleFactor', factor); var newSize = imgSize.select(function (x) { return x * factor; }); console.log('Feature', item.properties.id, 'calcImageSize', 'newSize', newSize); return newSize; } }, //label createLabel: { value: function (options, geometry, crs) { var style = { color: options.color || this.defaults.labelColor, label: { fontSize: options.fontSize || this.defaults.fontSize, text: null, scale: options.scale }, transparency: +options.transparency || this.defaults.transparency }; var feature = this._createFeature(style, geometry, crs); if (options.height != null) { style.height = options.height; this.updateItems([feature], style, options.scale, options.upp, true); // set text to empty string after updateItems (or label will be removed) style.label.text = ""; } return feature; } }, getLabelText: { value: function (item) { var style = this.getStyle(item); return style != null && style.label != null ? style.label.text : null; } }, getLineCount: { value: function (item) { var labelText = this.getLabelText(item) || ""; return labelText.split("\n").length; } }, //LineString createLineString: { value: function (options, geometry, crs) { var style = { color: options.color || this.defaults.lineColor, stroke: { width: options.width || this.defaults.lineWidth, type: options.type || this.defaults.lineType }, transparency: +options.transparency || this.defaults.transparency }; return this._createFeature(style, geometry, crs); } }, //Polygon createPolygon: { value: function (options, geometry, crs) { var style = { color: options.color || this.defaults.lineColor, fillColor: options.fillColor || this.defaults.fillColor, stroke: { width: options.width || this.defaults.lineWidth, type: options.type || this.defaults.lineType }, transparency: +options.transparency || this.defaults.transparency }; return this._createFeature(style, geometry, crs); } }, updateValues: { value: function (src, target) { var me = this; Object.keys(src).forEach(function (key) { if (src[key] != null) { if (!(src[key] instanceof Date) && typeof (src[key]) === "object" && Object.keys(src[key]).length) { if (!(key in target)) { target[key] = $.extend({}, src[key]); } else { me.updateValues(src[key], target[key]); } } else { if (key !== "iconUrl" && (target[key] == null || !(Object.keys(target[key]).length && typeof (target[key]) !== "string")) && (!"height,width,rotation,transparency".split(",").contains(key) || src[key] >= 0)) { target[key] = src[key]; } } } }); } }, updateItems: { value: function (items, style, mapScale, upp, keepRatio) { var me = this; console.log('size updateItems', items, style); var scale = style.scale || mapScale; console.log("FH.UPDATE_ITEMS", { items: items, style: style, scale: mapScale }); items.each(function (item) { var targetStyle = me.getStyle(item); var geom = me.getGeometry(item); var original = Object.create(null, { width: { value: targetStyle.width || me.calcWidthUnits(item, mapScale, upp) }, height: { value: targetStyle.height || me.calcHeightUnits(item, mapScale, upp) }, widthHeightRatio: { get: function() { return this.width / this.height; } } }); me.updateValues(style, targetStyle); //console.log('feature', item.properties.id, 'original.widthXheight', original.width, 'x', original.height, 'targetStyle.widthXheight', targetStyle.width, 'x', targetStyle.height); var lineRotation = me.isSimpleLine(item) ? me.gis.getLineRotation(geom) : -1; // rotation if (style.rotation && style.rotation !== -1) { if (me.isSimpleLine(item)) { if ("rotation" in style && style.rotation !== -1) { if (Math.abs(lineRotation - style.rotation) > 1 / 10000) { var rotatedLine = me.gis.rotateLine(geom, style.rotation); //geom.coordinates = rotatedLine.coordinates; me.setGeometry(item, rotatedLine.geoJson); } } } //console.debug("NEW_LINE_ANGLE", style.rotation, { item: item, rotation: style.rotation }); } // length if (style.length && style.length !== -1 && me.isSimpleLine(item)) { var lineLength = me.gis.getDistance.apply(null, geom.coordinates); if (Math.abs(style.length - lineLength) > 1 / 10000) { var newLine = me.gis.createLine(geom.coordinates[0], style.length, lineRotation); //geom.coordinates = newLine.coordinates; me.setGeometry(item, newLine.geoJson); } } // height if (style.height && targetStyle.label && (style.height !== targetStyle.height || style.label.scale !== scale)) { if (targetStyle.label && targetStyle.label.text) { var pixels = me.calcPixelsFromUnits(style.height, upp); var factor; if (!targetStyle.label.baseline) { targetStyle.label.baseline = "middle"; } factor = pixels / me.defaults.fontSize; targetStyle.label.scale = scale * factor; } } // width & height if (targetStyle.image && targetStyle.image.iconUrl && (((style.height && style.height !== -1) || style.image.scale !== scale) || ((style.width && style.width !== -1) || style.image.scale !== scale))) { var calcNewOrKeepOriginal = { width: function () { return keepRatio ? me.roundDimension((targetStyle.height || me.calcHeightUnits(item, scale, upp)) * original.widthHeightRatio) : original.width; }, height: function () { return keepRatio ? me.roundDimension((targetStyle.width || me.calcWidthUnits(item, scale, upp)) / original.widthHeightRatio) : original.height; } } var target = { width: (style.width > 0 ? style.width : null) || calcNewOrKeepOriginal.width(), height: (style.height > 0 ? style.height : null) || calcNewOrKeepOriginal.height() } var changed = { width: target.width !== original.width, height: target.height !== original.height } if (keepRatio) { if (changed.width && !changed.height) { target.height = calcNewOrKeepOriginal.height(); } else if (changed.height && !changed.width) { target.width = calcNewOrKeepOriginal.width(); } } targetStyle.width = target.width; targetStyle.height = target.height; console.log('size setStyle width/height', item.properties.title, targetStyle.width, targetStyle.height); //console.log('FEATURE.UPDATEIMAGE', 'upp', upp, 'scale', scale); //console.log('size FEATURE.UPDATEIMAGE', item.properties.title, 'style.widthXheight', style.width, 'x', style.height, 'updated targetStyle.widthXheight', targetStyle.width, 'x', targetStyle.height); var widthPixels = me.calcPixelsFromUnits(target.width, upp); //console.log('FEATURE.UPDATEIMAGE', item.properties.id, 'pixels.widthXheight', widthPixels, 'x', heightPixels); //targetStyle.image.scale = style.scale || widthPixels / targetStyle.image.width * scale; targetStyle.image.scale = style.scale || widthPixels / targetStyle.image.width * scale; //console.log('FH.FEATURE.GIS.STYLE', 'mapScale', scale, 'width', targetStyle.width, 'height', targetStyle.height, 'imgWidth', targetStyle.image.width, 'imgHeight', targetStyle.image.height, 'imgScale', targetStyle.image.scale); } if (targetStyle.stroke && ["dotted", "alternating"].contains(targetStyle.stroke.type) && !targetStyle.stroke.lineDash) { targetStyle.stroke.lineDash = targetStyle.stroke.width * 2; } //clean up if ("rotation" in targetStyle && targetStyle.rotation !== -1 && (!targetStyle.rotation || !me.isPoint(item))) { delete targetStyle.rotation; } if (targetStyle.image) { if (!targetStyle.image.iconUrl) { delete targetStyle.image; } } if (targetStyle.label) { if (!("text" in targetStyle.label) || targetStyle.label.text === "") { delete targetStyle.label; } } if (targetStyle.stroke) { if (!["dotted", "alternating"].contains(targetStyle.stroke.type)) { delete targetStyle.stroke.lineDash; } if (!targetStyle.stroke.type === "alternating") { delete targetStyle.alternatingColor; } if (targetStyle.stroke.measure === 1) { delete targetStyle.label; } } }); return items; } }, setSortOrder: { value: function (items) { var me = this; items.forEach(function (item, i) { var style = me.getStyle(item); style.zIndex = i; }); } }, isPoint: { value: function (item) { var geom = this.getGeometry(item); if (geom == null) { console.log("ERROR", { item: item }); return false; } return geom.type.endsWith("Point"); } }, isLineString: { value: function (item) { var geom = this.getGeometry(item); return geom.type.endsWith("LineString"); } }, isPolygon: { value: function (item) { var geom = this.getGeometry(item); return geom.type.endsWith("Polygon"); } }, isSimpleLine: { value: function (item) { function getFlatCoordinates(coordinates) { if (!_.isArray(coordinates.first())) { return [coordinates]; } else if (_.isArray(coordinates.first().first())) { return getFlatCoordinates(coordinates.selectMany()); } return coordinates; } var geom = this.getGeometry(item); if (!geom.type.endsWith("LineString")) { return false; } return getFlatCoordinates(geom.coordinates).length === 2; } }, isImage: { value: function (item) { var style = this.getStyle(item); return this.isPoint(item) && style != null && style.image != null && style.image.iconUrl != null; } }, isLabel: { value: function (item) { var style = this.getStyle(item); return this.isPoint(item) && style != null && style.label != null && style.label.text != null && !this.isImage(item); } }, isSimplePoint: { value: function (item) { return this.isPoint(item) && !this.isImage(item) && !this.isLabel(item); } }, isMeasure: { value: function (item) { var style = this.getStyle(item); return this.isLineString(item) && style.stroke.measure === 1; //|| this.isPolygon(item) && style.; } }, hasLabel: { value: function (item) { var style = this.getStyle(item); return this.isLabel(item) || (style.label != null && style.label.text != null && !this.isMeasure(item)); } }, roundDimension: { value: function (value) { return Math.round(value * 100) / 100; } } }); return FeatureHelper; })(); var vectorfeatures = vectorfeatures || {}; vectorfeatures.FeatureHtmlController = (function () { "use strict"; function FeatureHtmlController(featureHtmlManager) { Object.defineProperties(this, { _manager: { value: featureHtmlManager } }); } Object.defineProperties(FeatureHtmlController.prototype, { viewerScale: { get: function () { return this._viewer.scale; } }, selectedItems: { get: function () { return this._manager.selectedItems; }, enumerable: true }, handleResize: { value: function (e, item, size) { return this._manager.resizeItem(e, item, size); } }, handleDrag: { value: function (e, item, pixel, isCloned) { if (isCloned) { return this._manager.copy(e, item, pixel); } return this._manager.positionItem(e, item, pixel); } }, handleRotate: { value: function (e, item, rotation) { return this._manager.rotateItem(e, item, rotation); } }, getLabelHtml: { value: function (item) { return (item.labelText || "").replaceAll("\n", "
    "); } } }); return FeatureHtmlController; })("vectorfeatures"); var vectorfeatures = vectorfeatures || {}; vectorfeatures.FeatureHtmlConverter = (function () { "use strict"; function FeatureHtmlConverter(featureHelper, gisViewerManager, imageHelper) { Object.defineProperties(this, { _helper: { value: featureHelper }, _viewer: { value: gisViewerManager }, _imageHelper: { value: imageHelper } }); } Object.defineProperties(FeatureHtmlConverter.prototype, { viewerScale: { get: function () { return this._viewer.scale; }, enumerable: true }, unitsPerPixel: { get: function () { return this._viewer.unitsPerPixel; }, enumerable: true }, fromFeatures: { value: function (features) { var cv = this; return Promise.all(_.array(features) .select(function (feature) { var htmlItem = { feature: feature, id: cv._helper.getProperty(feature, "id") }; return cv.update(htmlItem); })); } }, update: { value: function (item) { var cv = this; return cv._getFeature(item) .then(function (feature) { item.rotation = cv._helper.getRotation(feature); item.opacity = cv._helper.getOpacity(feature); item.type = cv._helper.isImage(feature) ? "image" : cv._helper.isLabel(feature) ? "label" : null; item.resizeByScale = feature.properties && feature.properties.resizeByScale; return cv._viewer.getPixelFromCoordinate(feature.geometry.coordinates) .then(function (pixel) { item.left = pixel[0]; item.top = pixel[1]; item.imageUrl = cv._helper.getImageUrl(feature); if (cv._helper.isImage(feature)) { // image console.log('Feature', feature.properties.id, 'calcImageSize', 'start', { geometry: feature.geometry }); return Promise.resolve(cv._helper.calcImageSize(feature, cv.viewerScale)) .then(function(size) { if (size[0] === 0 || size[1] === 0) { // correct image dimensions when necessary return cv._imageHelper.getImageFromUrl(item.imageUrl) .then(function(image) { if (image != null) { var imgStyle = cv._helper.getStyle(feature).image; imgStyle.width = image.width; imgStyle.height = image.height; return cv._helper.calcImageSize(feature, cv.viewerScale); } return size; }); } return size; }) .then(function (size) { item.width = size[0]; item.height = size[1]; console.log('Feature', feature.properties.id, 'calcImageSize', 'end', { size }); return item; }); } // label item.height = cv._helper.calcAbsoluteHeightPixels(feature, cv.viewerScale); item.lineCount = cv._helper.getLineCount(feature); item.labelText = cv._helper.getLabelText(feature); return item; }); }) .then(function() { return item; }); } }, getFeatures: { value: function (items) { return Promise.all(_.array(items).select(this._getFeature)); } }, _getFeature: { value: function (item) { return Promise.resolve(item.feature); } } }); return FeatureHtmlConverter; })(); var vectorfeatures = vectorfeatures || {}; vectorfeatures.FeatureHtmlManager = (function () { "use strict"; function FeatureHtmlManager(featureHtmlConverter) { Object.defineProperties(this, { _items: { value: [], enumerable: true }, _selectedItems: { value: [], enumerable: true }, _enabled: { value: false, writable: true }, _converter: { value: featureHtmlConverter } }); } EventHandler.injectInto(FeatureHtmlManager.prototype); Object.defineProperties(FeatureHtmlManager.prototype, { enabled: { get: function () { return this._enabled; }, enumerable: true }, items: { get: function () { return this._items; }, enumerable: true }, selectedItems: { get: function () { return this._selectedItems; }, enumerable: true }, init: { value: function (o) { o = o || {}; var mgr = this; var promise = Promise.resolve(); if ("enabled" in o) { promise = promise.then(function () { return mgr.enable(o.enabled); }); } if (_.isArray(o.items)) { promise = promise.then(function () { return mgr.setItems(o.items); }); } if (_.isArray(o.selectedFeatures)) { promise = promise.then(function () { return mgr.setSelectedItems(o.selectedFeatures); }); } return mgr.trigger("init", {}) .then(promise); } }, enable: { value: function (value) { var enabled = !!value; var arg = { enabled: enabled }; var promise = Promise.resolve(); if (this._enabled !== enabled) { this._enabled = enabled; promise = this.trigger("change-enabled", arg); } return promise .then(function () { return arg; }); } }, resizeItem: { value: function (e, item, size) { //console.log("FHM.RESIZE", { item: item, mgr: this }); var mgr = this; return mgr._converter.getFeatures(item) .then(function (features) { return mgr.trigger(new Event("resize-item", e), { item: features.first(), type: item.type, originalSize: [item.width, item.height], size: size }); }); } }, positionItem: { value: function (e, item, pixel) { //console.log("FHM.POSITION", { item: item, mgr: this }); var mgr = this; return mgr._converter.getFeatures(item) .then(function (features) { return mgr.trigger(new Event("move-item", e), { item: features.first(), originalPixel: [item.left, item.top], pixel: pixel }); }); } }, rotateItem: { value: function (e, item, rotation) { //console.log("FHM.ROTATE", { item: item, mgr: this }); var mgr = this; return mgr._converter.getFeatures(item) .then(function (features) { return mgr.trigger(new Event("rotate-item", e), { item: features.first(), originalRotation: item.rotation, rotation: rotation }); }); } }, copy: { value: function (e, item, pixel) { var mgr = this; return mgr._converter.getFeatures(item) .then(function (features) { var arg = { item: features.first(), pixel: pixel }; return mgr.trigger("copy-item", arg) .then(function () { return arg; }); }); } }, update: { value: function (items) { var mgr = this; return mgr._converter.getFeatures(items) .then(function (features) { return mgr.setItems(features); }); } }, remove: { value: function (features) { var mgr = this; features = _.array(features); return mgr._getItems(features) .then(function (items) { var arg = { items: items }; mgr.items.remove(features); return this.trigger("remove-items", arg) .then(function () { return arg; }); }); } }, setItems: { value: function (features) { var mgr = this; return mgr._converter.fromFeatures(features) .then(function (items) { return mgr._getArg(mgr.items.select(), items) .then(function (arg) { arg.items = features; mgr.items.clear().addRange(items); //console.log("FHM.SETitems", { items: items, arg: arg, mgr: this }); return Promise.resolve() .then(function () { if (arg.added.length > 0 || arg.removed.length > 0) { return mgr.trigger("change-items", arg); } return true; }) .then(function () { return arg; }); }); }); } }, setSelectedItems: { value: function (selectedFeatures) { var mgr = this; return mgr._getItems(selectedFeatures) .then(function (selectedItems) { return mgr._getArg(mgr.selectedItems.select(), selectedItems) .then(function (arg) { arg.selectedItems = selectedFeatures; mgr._selectedItems.clear().addRange(selectedItems); return Promise.resolve() .then(function () { if (arg.added.length > 0 || arg.removed.length > 0) { return mgr.trigger("change-selected-items", arg); } return true; }) .then(function () { return arg; }); }); }); } }, _getArg: { value: function (currentItems, newItems) { var mgr = this; return mgr._converter.getFeatures(currentItems) .then(function (currentFeatures) { return mgr._converter.getFeatures(newItems) .then(function (newFeatures) { return { oldValue: currentFeatures, added: newFeatures.except(currentFeatures), modified: currentFeatures.innerJoin(newFeatures), removed: currentFeatures.except(newFeatures) }; }); }); } }, _getItems: { value: function (features) { var mgr = this; features = _.array(features || []); return mgr.items .aggregate(function (p, item) { return mgr._converter.getFeatures(item) .then(function (itemFeatures) { var feature = itemFeatures.first(); if (feature == null) { return mgr._converter.fromFeatures(feature); } return feature; }) .then(function (feature) { return p.then(function (items) { if (features.contains(feature)) { items.push(item); } return items; }); }); }, Promise.resolve([])); } } }); return FeatureHtmlManager; })("vectorfeatures"); var vectorfeatures = vectorfeatures || {}; vectorfeatures.FeatureStyleController = (function () { function FeatureStyleController(featureStyleManager) { var ctrl = this; Object.defineProperties(ctrl, { _manager: { value: featureStyleManager } }); } Object.defineProperties(FeatureStyleController.prototype, { items: { get: function () { return this._manager.items; }, enumerable: true }, originalStyle: { get: function () { return this._manager.originalStyle; }, enumerable: true }, geomType: { get: function () { return this._manager.geomType; }, enumerable: true }, style: { get: function () { return this._manager.style; }, enumerable: true }, visibilities: { get: function () { return this._manager.visibilities; }, enumerable: true }, onChange: { value: function (prop, keepRatio) { return this._manager.triggerModifyStyle({ prop: prop, keepRatio: keepRatio }); } } }); return FeatureStyleController; })(); var vectorfeatures = vectorfeatures || {}; vectorfeatures.FeatureStyleManager = (function () { "use strict"; var STYLE_COMPONENTS = "rotation,length,transparency,image,labelText,scale,height,width,color,fillColor,lineWidth,lineType,lineDash,colorPicker,alternatingColorPicker,fillColorPicker,measureLength,measureArea,strokeArrowLocation,strokeLabelLocation".split(","); //var DEFAULT_HEIGHT = 1; function FeatureStyleManager(featureHelper, imageHelper, gisViewerManager, geoHelper) { Object.defineProperties(this, { canEdit: { writable: true, enumerable: true }, _enabled: { value: false, writable: true }, _items: { value: [], writable: true }, _featureHelper: { value: featureHelper }, _imageHelper: { value: imageHelper }, _viewer: { value: gisViewerManager }, _geoHelper: { value: geoHelper }, visibilities: { value: this.defaultVisibilities, writable: true, enumerable: true }, geomType: { writable: true, enumerable: true }, style: { writable: true, enumerable: true } }); } EventHandler.injectInto(FeatureStyleManager.prototype); Object.defineProperties(FeatureStyleManager.prototype, { enabled: { get: function () { return this._enabled; }, enumerable: true }, defaultVisibilities: { get: function () { return $.extend(STYLE_COMPONENTS.toDictionary(function (x) { return x; }, function () { return false; }), { transparency: true }); }, enumerable: true }, defaultStyle: { get: function () { return { visible: {}, fontSize: 10, defaultAlternatingStyle: { stroke: { "type": "alternating" }, color: "#78f20d", alternatingColor: "#261de0" } }; } }, items: { get: function () { return this._items; }, enumerable: true }, viewerScale: { get: function () { return this._viewer.scale; }, enumerable: true }, unitsPerPixel: { get: function () { return this._viewer.unitsPerPixel; }, enumerable: true }, //init init: { value: function (o) { o = o || {}; this.canEdit = !!o.canEdit; this._items = o.items || []; //console.log("FSM.INIT", { o: o, mgr: this }); if (this._items != null) { this.geomType = this.getCommonGeomType(this._items); this.visibilities = this.getVisibilities(this._items); var propHasBeenSet = this.style ? this.style.propHasBeenSet : null; var style = this.getCommonStyle(this._items); if (propHasBeenSet) { for (var prop in propHasBeenSet) { if (propHasBeenSet.hasOwnProperty(prop)) { if (style[prop] !== -1) { style.propHasBeenSet[prop] = true; } } } } this.style = style; this.originalStyle = $.extend(true, {}, this.style); } else { this.geomType = null; this.style = {}; this.visibilities = {}; } return Promise.resolve(); } }, enable: { value: function (value) { var enabled = !!value; var arg = { enabled: enabled }; var promise = Promise.resolve(); if (this._enabled !== enabled) { this._enabled = enabled; promise = this.trigger("change-enabled", arg); } return promise .then(function () { return arg; }); } }, getCommonGeomType: { value: function (items) { var mgr = this; var geomTypes = items .select(function (item) { var geomType = mgr._featureHelper.getGeometry(item).type; return geomType.replace("Multi", ""); }) .distinct(); if (geomTypes.length === 1) { return geomTypes.first(); } return null; } }, getCommonStyle: { value: function (items) { var mgr = this; var style = { rotation: 0, transparency: 25, image: {}, label: {}, stroke: {}, propHasBeenSet: {} }; var itemsWithStyles = items.select(function (x) { return { item: x, style: mgr._featureHelper.getStyle(x), properties: x.properties || {} }; }); var styles = itemsWithStyles.select(function (x) { return x.style; }); //console.log("STYLES", { mgr: mgr, styles: styles, upp: mgr.unitsPerPixel, scale: mgr.viewerScale }); // scale var scales = itemsWithStyles .where(function (x) { return x.style.image != null && x.properties.resizeByScale; }) .select(function (x) { return x.style.image.scale; }); if (scales.length === styles.length) { style.scale = (scales.distinct().length === 1) ? mgr._featureHelper.roundDimension(scales.first()) : -1; } // width var widths = itemsWithStyles .where(function (x) { return x.style.image != null && !x.properties.resizeByScale; }) .select(function (x) { return x.item.width || x.item.properties.style.width || mgr._featureHelper.calcWidthUnits(x.item, mgr.viewerScale, mgr.unitsPerPixel); }); if (widths.length === styles.length) { style.width = (widths.distinct().length === 1) ? mgr._featureHelper.roundDimension(widths.first()) : -1; } // height var heights = itemsWithStyles .where(function (x) { return (x.style.label != null || x.style.image != null) && !x.properties.resizeByScale; }) .select(function (x) { return x.item.height || x.item.properties.style.height || mgr._featureHelper.calcHeightUnits(x.item, mgr.viewerScale, mgr.unitsPerPixel); }); if (heights.length === styles.length) { style.height = (heights.distinct().length === 1) ? mgr._featureHelper.roundDimension(heights.first()) : -1; } // rotation if (mgr.isVisible('rotation')) { var rotations = itemsWithStyles .select(function (x) { // point item if (x.style.rotation) { return ((x.style.rotation || 0) + 360) % 360; } else if (mgr._featureHelper.isPoint(x.item)) { return 0; } // simple line style var geom = mgr._featureHelper.getGeometry(x.item); return mgr._geoHelper.getLineRotation(geom); }) .select(function (x) { return Math.round(x * 10000) / 10000; }); //console.debug("FSM.ROTATION", { rotations: rotations, items: items }); if (rotations.length === styles.length) { style.rotation = rotations.distinct().length === 1 ? rotations.first() : -1; } } else { style.rotation = null; } // length if (mgr.isVisible('length')) { var lengths = items .select(function (x) { var geom = mgr._featureHelper.getGeometry(x); return mgr._geoHelper.getDistance.apply(null, geom.coordinates); }) .select(function (x) { return Math.round(x * 10000) / 10000; }); if (lengths.length === styles.length) { style.length = lengths.distinct().length === 1 ? lengths.first() : -1; } } else { style.length = null; } // transparency var transparencies = styles .where(function (x) { return x.opacity != null || x.transparency != null; }) .select(function (x) { return x.opacity ? ((1 - x.opacity) * 100) : x.transparency; }); if (transparencies.length === styles.length) { style.transparency = transparencies.distinct().length === 1 ? transparencies.first() : -1; } // image var iconUrls = items .where(function (x) { return mgr._featureHelper.isImage(x); }) .select(function (x) { return mgr._featureHelper.getTransformedIconUrl(x); }); if (iconUrls.length === styles.length) { style.image.iconUrl = iconUrls.distinct().length === 1 ? iconUrls.first() : null; } // text var texts = styles .where(function (x) { return x.label != null }) .select(function (x) { return x.label.text; }); if (texts.length === styles.length) { style.label.text = texts.distinct().length === 1 ? texts.first() : null; } // strokeWidth var strokeWidths = styles .where(function (x) { return x.stroke && x.stroke.width != null; }) .select(function (x) { return x.stroke.width; }); if (strokeWidths.length === styles.length) { style.stroke.width = strokeWidths.distinct().length === 1 ? strokeWidths.first() : null; } // strokeType var strokeTypes = styles .where(function (x) { return x.stroke && x.stroke.type != null; }) .select(function (x) { return x.stroke.type; }); if (strokeTypes.length) { style.stroke.type = strokeTypes.length === styles.length && strokeTypes.distinct().length === 1 ? strokeTypes.first() : null; } // lineDash var lineDashes = styles .where(function (x) { return x.stroke && ["dotted", "alternating"].contains(x.stroke.type); }) .select(function (x) { return x.stroke.lineDash; }); if (lineDashes.length === styles.length) { style.stroke.lineDash = lineDashes.distinct().length === 1 ? lineDashes.first() : -1; } // measureLength var measureLengths = styles .where(function (x) { return x.stroke && "measure" in x.stroke; }) .select(function (x) { return x.stroke.measure || 0; }); if (measureLengths.length) { style.stroke.measure = measureLengths.length === styles.length && measureLengths.distinct().length === 1 ? measureLengths.first() : -1; } // strokeArrowLocation var strokeArrowLocations = styles .where(function (x) { return x.stroke && x.stroke.arrowLocation != null; }) .select(function (x) { return x.stroke.arrowLocation; }); if (strokeArrowLocations.length) { style.stroke.arrowLocation = strokeArrowLocations.length === styles.length && strokeArrowLocations.distinct().length === 1 ? strokeArrowLocations.first() : -1; } // strokeLabelLocation var strokeLabelLocations = styles .where(function (x) { return x.stroke && x.stroke.labelLocation != null; }) .select(function (x) { return x.stroke.labelLocation; }); if (strokeLabelLocations.length) { style.stroke.labelLocation = strokeLabelLocations.length === styles.length && strokeLabelLocations.distinct().length === 1 ? strokeLabelLocations.first() : null; } // color var colors = styles .where(function (x) { return x.color != null; }) .select(function (x) { return x.color; }); if (colors.length === styles.length) { style.color = colors.distinct().length === 1 ? colors.first() : null; } // alternatingColor var alternatingColors = styles .where(function (x) { return x.alternatingColor != null; }) .select(function (x) { return x.alternatingColor; }); if (alternatingColors.length === styles.length) { style.alternatingColor = alternatingColors.distinct().length === 1 ? alternatingColors.first() : null; } // fillColor var fillColors = styles .where(function (x) { return x.fillColor != null; }) .select(function (x) { return x.fillColor; }); if (fillColors.length === styles.length) { style.fillColor = fillColors.distinct().length === 1 ? fillColors.first() : null; } //console.log("FSM.COMMON_STYLE", { items: items, style: $.extend(true, {}, style), styles: styles, mgr: mgr }); return style; } }, isVisible: { value: function (component) { return this.visibilities[component]; } }, getVisibilities: { value: function (items) { var mgr = this; //console.log("FSM.GET_VISIBILITIES", { mgr: mgr }); var allAreImagesOrLabels = items.all(function (x) { return mgr._featureHelper.isImage(x) || mgr._featureHelper.isLabel(x); }); var allAreImages = allAreImagesOrLabels && items.all(function (x) { return mgr._featureHelper.isImage(x); }); var allAreResizableByScale = items.all(function (x) { return x.properties && x.properties.resizeByScale; }); var allArePolygonOrLineString = items.all(function (x) { return mgr._featureHelper.isLineString(x) || mgr._featureHelper.isPolygon(x); }); var allAreLineString = allArePolygonOrLineString && items.all(function (x) { return mgr._featureHelper.isLineString(x); }); var allAreSimpleLine = allAreLineString && items.all(function (x) { return mgr._featureHelper.isSimpleLine(x); }); var allArePolygons = items.all(function (x) { return mgr._featureHelper.isPolygon(x); }); var visibilities = $.extend(mgr.defaultVisibilities, { rotation: items.all(function (x) { return mgr._featureHelper.isImage(x) || mgr._featureHelper.isLabel(x) || mgr._featureHelper.isSimpleLine(x); }), length: allAreSimpleLine, image: allAreImages, scale: allAreResizableByScale, labelText: items.all(function (x) { return !(mgr._featureHelper.isImage(x) || mgr._featureHelper.isMeasure(x)); }), height: allAreImagesOrLabels && !allAreResizableByScale, width: allAreImages && !allAreResizableByScale, color: !allAreImages, fillColor: allArePolygons, lineWidth: allArePolygonOrLineString, lineType: allArePolygonOrLineString, lineDash: allArePolygonOrLineString, measureLength: allAreLineString, measureArea: allArePolygons, strokeArrowLocation: allArePolygonOrLineString, strokeLabelLocation: allAreLineString && items.all(function (x) { return mgr._featureHelper.isMeasure(x) || mgr._featureHelper.hasLabel(x); }) }); return visibilities; } }, processStyle: { value: function (style, scale) { var mgr = this; var imgStyle = style.image; return Promise.resolve() .then(function () { if (imgStyle && imgStyle.iconUrl) { if (!imgStyle.scale) { imgStyle.scale = scale; } return Promise.resolve() .then(function () { if (!imgStyle.width || !imgStyle.height) { return mgr._imageHelper.getImageFromUrl(imgStyle.iconUrl) .then(function (img) { imgStyle.width = img.width; imgStyle.height = img.height; }) .catch(function () { // ignore }); } return true; }); } return true; }) .then(function () { return style; }); } }, triggerModifyStyle: { value: function (arg) { var mgr = this; return this.processStyle(mgr.style, mgr.viewerScale) .then(function (processedStyle) { return mgr.trigger("change-style", { prop: arg.prop, style: processedStyle, items: mgr.items, scale: mgr.viewerScale, upp: mgr.unitsPerPixel, keepRatio: arg.keepRatio }); }); } } }); return FeatureStyleManager; })(); var vectorfeatures = vectorfeatures || {}; vectorfeatures.stylingComponent = (function () { "use strict"; function StylingViewModel() { Object.defineProperties(this, { keepRatio: { value: true, enumerable: true, writable: true }, visibilities: { writable: true }, geomType: { writable: true }, featureStyle: { writable: true }, originalStyle: { writable: true }, features: { writable: true }, onChange: { writable: true }, onClose: { writable: true } }); } Object.defineProperties(StylingViewModel.prototype, { getPropValue: { value: function(item, prop) { if (prop) { var parts = prop.split('.'); if (parts.length === 1) { return item[prop]; } return this.getPropValue(item[parts[0]], parts.skip(1).join('.')); } return item; } }, handleChange: { value: function (e, prop) { var propValue = this.getPropValue(this.featureStyle, prop); if (propValue == null || propValue === -1 || propValue === "") { return null; } if (["width", "height"].contains(prop)) { //console.debug("SC.RESIZE", prop, { evt: e, vm: this }); if (this.originalStyle[prop] === -1 && propValue === 0) { this.featureStyle[prop] = 1; //console.log('SC.RESIZE', prop, 'set value to 1'); } } else if (prop === "rotation") { if (propValue === 360) { this.featureStyle[prop] = 0; } } else if (prop === "stroke.width") { if (propValue < 1) { this.featureStyle.stroke.width = 1; } } if (!this.featureStyle.propHasBeenSet) { this.featureStyle.propHasBeenSet = {}; } this.featureStyle.propHasBeenSet[prop] = true; return this.onChange({ event: e, prop: prop, style: this.featureStyle, keepRatio: this.keepRatio }); } }, handleClose: { value: function (e) { return this.onClose({ event: e }); } }, isVisible: { value: function (component) { return this.visibilities[component]; } } }); function stylingComponent(templateUrl) { return { controller: StylingViewModel, bindings: { visibilities: "<", geomType: "<", featureStyle: "<", originalStyle: "<", features: "<", onChange: "&", onClose: "&" }, transclude: { geom: "geom" }, templateUrl: ["config", function (config) { return config.baseUrl + "/" + templateUrl + "?v=" + config.version; }] } } return stylingComponent; })(); var viewer = viewer || {}; viewer.geometrySelectorComponent = (function () { "use strict"; function geometrySelectorComponent(templateUrl) { function GeometrySelectorViewModel(viewer, vectorManager, geoHelper) { Object.defineProperties(this, { _initialized: { value: false, writable: true }, _viewer: { value: viewer }, _vectorManager: { value: vectorManager }, _helper: { value: geoHelper }, _value: { writable: true }, _inputType: { writable: true }, _perpendicularGeom: { writable: true }, accuracy: { writable: true, enumerable: true }, geom: { writable: true, enumerable: true }, feature: { writable: true }, _layer: { value: { Code: "__GEOMETRY_SELECTOR__", ShowInLegend: false }, writable: true }, onSelect: { writable: true }, onChange: { writable: true } }); //console.log("GEOM_SELECTOR", { vm: this }); } Object.defineProperties(GeometrySelectorViewModel.prototype, { value: { get: function () { return this._value; }, set: function (value) { var vm = this; var oldValue = this._value; this._value = value; this._inputType = (typeof (value) === "string") ? "wkt" : (_.isArray(value) ? "array" : "geoJson"); if (this._initialized) { if (value != null) { if (!oldValue || !vm._helper.equals(value, oldValue, 8)) { //console.log("GSC.SET_VALUE", { value: value, oldValue: oldValue, vm: vm }); vm._setGeom(value); } } else { vm.clear(); } } }, enumerable: true }, layer: { get: function () { return this._layer; }, set: function (value) { if (value == null || value.Code == null) { return; } this._layer = value; }, enumerable: true }, geomType: { get: function () { if (this.geom == null || this.geom.geoJson == null) { return null; } return this.geom.geoJson.type; }, enumerable: true }, _getPerpendicularLine: { value: function (coordinates) { var vm = this; var length = vm._helper.getDistance.apply(null, coordinates); var start = coordinates[0]; return vm._viewer .getClosestFeatures({ geom: start, predicate: function (x) { var geometry = x.geometry; var isLineString = geometry.type === "LineString"; var coordinates = vm._helper.getFlatCoordinates(geometry.coordinates); var isSimpleLine = coordinates.length === 2; var distance = vm._viewer.getDistance(coordinates, start); return isLineString && isSimpleLine && distance < 1; } }) .then(function (closestFeatures) { var cursorCoordinate = vm._viewer.cursorPosition.coordinate; var endPoints = closestFeatures .selectMany(function (line) { var rotation = vm._helper.getLineRotation(line); return [-90, 90].select(function (extraRotation) { var end = vm._helper.getDestination(start, length, (rotation + extraRotation) % 360).coordinates; return end; }); }); //console.debug("ENDPOINTS", { endPoints: endPoints, cursorCoordinate: cursorCoordinate }); var closestEndPoint = endPoints .orderBy(function (perpendicularEnd) { return vm._viewer.getDistance(perpendicularEnd, cursorCoordinate); }) .first(); if (closestEndPoint) { return [start, closestEndPoint]; } return null; }); } }, handleDigitize: { value: function (e, type, extra) { var vm = this; extra = extra || {}; var onAddVertex = function (e, arg) { //console.log("GS.ADD_VERTEX", { evt: e, arg: arg }); if (extra.isSimpleLine && arg.type === "LineString" && arg.coordinates.length >= 2) { vm._viewer.finishDigitizing(); } } var perpendicularGeom = null; var onDigitize = F.debounce(function (e, arg) { //ToDo: show measure label when digitizing // perpendicular if (extra && extra.isPerpendicular) { //console.debug("ON_DIGITIZE", { evt: e, arg: arg }); var coordinates = arg.geom.coordinates; e.src.preventDefault(); vm._getPerpendicularLine(coordinates) .then(function (geom) { if (geom) { perpendicularGeom = geom; arg.setGeom(perpendicularGeom); } else { perpendicularGeom = null; } }); } }, 100); vm._viewer .on("digitizing", onDigitize) .on("add-vertex", onAddVertex); return Promise.resolve({ event: e, geom: null, type: null, action: "digitize" }) .then(function (arg) { return vm.digitize(type) .then(function (geom) { if (geom && extra.isPerpendicular && perpendicularGeom) { geom = vm._helper.getGeom(perpendicularGeom); } perpendicularGeom = null; return geom; }) .then(function (geom) { arg.geom = geom; var type = null; if (geom != null) { type = geom.geoJson.type; } arg.type = type; return arg; }); }) .then(function (arg) { var extraKeys = Object.keys(extra); if (extraKeys.length) { extraKeys.forEach(function (key) { if (!arg.hasOwnProperty(key)) { arg[key] = extra[key]; } }); } vm.onSelect(arg); return arg; }) .finally(function () { vm._viewer .off("digitizing", onDigitize) .off("add-vertex", onAddVertex); }); } }, handleCopy: { value: function (e) { var vm = this; return vm._viewer.clearSelection() .then(function () { return vm._viewer.copyGeometry({ ignore: vm.layer }); }) .then(function (response) { if (response == null) { return false; } var geom = response.geom; var feature = response.source; if (geom == null || geom.type == null) { return false; } var type = geom.geoJson.type; var arg = { event: e, geom: geom, type: type, feature: feature, action: "copy" }; vm.onSelect(arg); return arg; }); } }, handleTrackLocation: { value: function (e) { var vm = this; return vm._viewer.getClientPosition() .then(function (gpsArg) { return vm._getGeom(gpsArg.coordinate) .then(function (geom) { console.log("GS.GPS", { arg: gpsArg, vm: vm }); return vm._viewer.zoom({ center: gpsArg.coordinate, scale: 500 }) .then(function () { var arg = { event: e, geom: geom, type: "Point", accuracy: gpsArg.accuracy, action: "clientLocation" }; vm.onSelect(arg); }); }); }); } }, digitize: { value: function (type) { return this._viewer["digitize" + type](); } }, _setGeom: { value: function (input) { var vm = this; var promise; if (input == null) { promise = Promise.resolve(null); } else { promise = vm._getGeom(input); } return promise .then(function (geom) { //console.log("GSC.SET_GEOM", { geom: geom, vm: vm }); vm.geom = geom; return vm._drawGeom(vm.geom) .then(function () { return geom; }); }); } }, _getGeom: { value: function (input) { return Promise.resolve(this._helper.getGeom(input)); //var vm = this; //return new Promise(function (resolve) { // vm._helper.GetGeometryObject(input, function (geoJson) { // vm._helper.GetWKT(input, function (wkt) { // resolve({ geoJson: geoJson, wkt: wkt }); // }); // }); //}); } }, _drawGeom: { value: function (geom) { var vm = this; //console.log("GSC.DRAW_GEOM", { geom: geom, vm: vm }); if (geom == null) { return Promise.resolve(); } return vm._vectorManager.layer.createIfNotExists(vm.layer) .then(function (layer) { return Promise.resolve() .then(function () { if (vm.feature != null) { return vm._vectorManager.feature.remove({ layer: layer, feature: vm.feature }); } return false; }) .then(function () { //console.log("GSC.LAYER", { layer: layer, args: arguments, vm: vm }); return vm._vectorManager.feature.addGeometry({ geom: geom.geoJson, layer: layer }); }) .then(function (arg) { vm.feature = arg.added.first(); //select feature in map return vm._vectorManager.feature.select({ features: [vm.feature], /*preserve: true,*/ layer: layer }) //make feature updatable .then(function () { return vm._vectorManager.feature.setEditMode(true); }) .then(function () { return { layer: layer, feature: vm.feature }; }); }); }); } }, clear: { value: function () { var vm = this; return Promise.resolve() .then(function () { if (vm.layer != null) { return vm._vectorManager.layer.remove(vm.layer); } return false; }) .then(function () { return vm._vectorManager.feature.setEditMode(false); }); } }, _onFeatureChange: { value: function (e, arg) { var vm = this; if (vm.value == null || !arg.layers.any(function (l) { return l.Code === vm.layer.Code; })) { return; } vm._getGeom(arg.features.first().geometry) .then(function (geom) { //console.log("GSC.FEATURE_CHANGE", { evt: e, arg: arg, wkt: geom.wkt, vm: vm }); vm._geom = geom; if (vm._inputType === "wkt") { vm._value = geom.wkt; } else if (vm._inputType === "geoJson") { vm._value = geom.geoJson; } vm.onChange({ event: e, geom: geom, type: geom.geoJson.type, action: "modify" }); }); } }, init: { value: function () { var vm = this; vm._initialized = true; //console.log("GSC.INIT", { vm: this }); vm._viewer.on("feature-change", { callback: vm._onFeatureChange, scope: vm }); if (vm.value != null) { vm._setGeom(vm.value) .then(function () { if (typeof (vm.onInit) === "function") { vm.onInit({ value: vm.value, accuracy: vm.accuracy, geom: vm.geom }); } }); } } }, dispose: { value: function () { var vm = this; vm._viewer.off("feature-change", vm._onFeatureChange); vm.geom = null; if (typeof (vm.onDispose) === "function") { vm.onDispose({ value: vm.value, accuracy: vm.accuracy, geom: vm.geom }); } vm.clear(); } } }); Object.defineProperties(GeometrySelectorViewModel.prototype, { $onInit: { value: function () { return this.init(); } }, $onDestroy: { value: function () { return this.dispose(); } } }); return { controller: ["gisViewerManager", "gisVectorManager", "geoHelper", GeometrySelectorViewModel], bindings: { value: "<", accuracy: "<", layer: "<", onSelect: "&", onChange: "&" }, templateUrl: ["config", function (config) { return config.baseUrl + "/" + templateUrl + "?v=" + config.version; }] }; } return geometrySelectorComponent; })(); var viewer = viewer || {}; viewer.GisDependencyInjector = (function () { "use strict"; function GisDependencyInjector() { } GisDependencyInjector.injectInto = function (target, config, gisViewer) { //check first (function checkTargetController(ctrl) { var missing = "load,show".split(",").where(function (x) { return !(x in ctrl); }); if (missing.any()) { console.error("Cannot inject GisDependencies in target controller", { missing: missing, ctrl: ctrl }); throw new Error("Cannot inject GisDependencies in target controller\nMissing properties: " + missing.join(", ")); } })(target); var _layerName; var _layerNames; function getLayerNames() { return new Promise(function (resolve) { //layerNames ophalen wanneer map geladen is if (_layerNames == null) { gisViewer.on("map-load", function (e, arg) { //console.log("GDI.MAP_LOAD", { config: config, ctrl: target }); var layerNameTerms = _.array(config.layerName || config.layerNames); _layerNames = arg.layers .where(function (x) { return layerNameTerms.any(function (layerNameTerm) { if (layerNameTerm.startsWith("*") && layerNameTerm.endsWith("*")) { return x.Code.contains(layerNameTerm.trim("*")); } else if (layerNameTerm.endsWith("*")) { return x.Code.startsWith(layerNameTerm.trim("*")); } else if (layerNameTerm.startsWith("*")) { return x.Code.endsWith(layerNameTerm.trim("*")); } else { return x.Code === layerNameTerm; } }); }) .select(function (x) { return x.Code; }); //console.log("GDI.LAYERNAMES", _layerNames); resolve(_layerNames); }); } else { resolve(_layerNames); } }); } //zo snel mogelijk _layerNames opvullen getLayerNames(); //origineel opslaan anders max stack exceeded var originalShow = target.show; Object.defineProperties(target, { layerName: { get: function () { return _layerName; }, set: function (value) { _layerName = value; }, enumerable: true }, layerNames: { get: function () { return _layerNames; }, enumerable: true }, getLayerNames: { value: function () { var vm = this; if (vm.layerNames != null) { return Promise.resolve(vm.layerNames); } return getLayerNames(); }, configurable: true }, getFeatureLayerName: { value: function (id) { return gisViewer.getFeatureLayerName({ filter: "{id} = " + id, layerNameTerm: config.layerName }) .then(function (featureLayerName) { return featureLayerName; }); }, configurable: true }, show: { value: function (id, display, defaults) { var vm = this; vm.layerName = null; return ((id > 0 && config.layerName) ? vm.getFeatureLayerName(id) : Promise.resolve(null)) .then(function (layerName) { vm.layerName = layerName; }) .then(function () { return originalShow.call(vm, id, display, defaults); }); }, configurable: true }, loadListMap: { value: function (filter) { var vm = this; filter = filter || vm.filter; //console.log("GDI.LOADING_LIST_MAP", { filter: filter }); return vm.load(filter) .then(function (items) { return vm.loadMap({ items: items }) .then(function () { return items; }); }) .catch(function () { console.error("GDI.ERROR", { action: "loadListMap", ctrl: vm, arg: arguments }); }); }, configurable: true }, loadMap: { value: function (o) { var vm = this; var gisFilter = vm.getGisFilter(o); return vm.getLayerNames() .then(function (layerNames) { var mapFilter = layerNames.aggregate(function (r, x) { r[x] = gisFilter; return r; }, {}); //console.log("GDI.FILTERING", { o: o, gisFilter: gisFilter, mapFilter: mapFilter }); return gisViewer.filter({ filter: mapFilter }); }); }, configurable: true }, updateView: { value: function (returnValue) { var vm = this; return vm.loadMap({ items: vm.items }) .then(function () { return (("countTotal" in vm) ? vm.countTotal() : null); }) .then(function () { return returnValue; }); }, configurable: true }, getExtent: { value: function (items) { var vm = this; //var ids = (items || vm.items).select(function (x) { return x.id; }); //var gisFilter = (vm.totalCount && vm.totalCount === ids.length) ? "" : ids.length ? "{id} IN (" + ids.join(",") + ")" : ""; var gisFilter = vm.getGisFilter({ items: items || vm.items }); return vm.getLayerNames() .then(function (layerNames) { return Promise.all( layerNames.select(function (x) { return gisViewer.getFeaturesExtent({ layerName: x, filter: gisFilter }); }) ); }); }, configurable: true }, getGisFilter: { value: function (o) { o = o || {}; var items = o.items || (_.isArray(o) ? o : null); var ids = items ? items.select(function (x) { return x.id; }).join(",") : []; var gisFilter = o.filter || ((typeof (o) === "string") ? o : (ids.length ? "{id} IN (" + ids + ")" : "")); return gisFilter; }, configurable: true } }); if ("save" in target) { //origineel opslaan anders max stack exceeded var originalSave = target.save; Object.defineProperty(target, "save", { value: function ( /*arguments*/) { var vm = this; vm.layerName = null; return originalSave.apply(vm, arguments) .then(function (saved) { if (!vm.hasErrors) { return vm.getFeatureLayerName(saved.id) .then(function (layerName) { vm.layerName = layerName; return vm.updateView(saved); }); } return arguments[0]; }) .catch(function (error) { console.error("GDI.ERROR", { action: "save", ctrl: vm, arg: arguments }); throw error; }); }, configurable: true }); } if ("remove" in target) { //origineel opslaan anders max stack exceeded var originalRemove = target.remove; Object.defineProperty(target, "remove", { value: function ( /*arguments*/) { var vm = this; return originalRemove.apply(vm, arguments) .then(function (removed) { return vm.updateView(removed); }) .catch(function (error) { console.error("GDI.ERROR", { action: "remove", ctrl: vm, arg: arguments }); throw error; }); }, configurable: true }); } }; return GisDependencyInjector; })("viewer"); (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD define([], factory); } else if (typeof exports === 'object') { // Node, CommonJS-like module.exports = factory(); } else { root.viewer = root.viewer || {}; root.viewer.SnappingController = factory("viewer"); } }(this, function () { "use strict"; function SnappingController(snappingManager) { Object.defineProperties(this, { _mgr: { value: snappingManager } }); } Object.defineProperties(SnappingController.prototype, { layers: { get: function () { return this._mgr.layers; }, enumerable: true }, selected: { get: function () { return this._mgr.selected; }, set: function (value) { this._mgr.selected = value; }, enumerable: true }, snapEdges: { get: function () { return this._mgr.snapEdges; }, set: function (value) { this._mgr.snapEdges = value; }, enumerable: true } }); return SnappingController; })); var viewer = viewer || {}; viewer.GeometrySelectorDirective = (function (moduleName) { "use strict"; function GeometrySelectorDirective(config, gisViewerManager, gisVectorManager, geoHelper, geoHandler, $translate, $timeout) { return { restrict: "EA", scope: { display: "@display", geom: "=", accuracy: "=", multi: "=", showGeom: "=", onSelect: "&", onError: "&", onChange: "&", ctrl: "=", onGeomSelect: "&", onGeomChange: "=" }, templateUrl: config.baseUrl + "/Content/modules/" + moduleName + "/directives/geometry-selector-buttons.html?v=" + config.version, link: function ($scope, $el, $attr) { //console.log(moduleName.toUpperCase() + "_GEOMETRY_SELECTOR", { attr: $attr, scope: $scope }); //format var geomFormat = $attr.format || "wkt"; $scope.handleError = function (error) { if ($scope.onError) { $scope.onError.call($scope.ctrl || $scope, error); } else { throw error; } }; $scope.changed = function () { if ($scope.onChange) { $scope.onChange.apply($scope.ctrl || $scope, { geom: $scope.geom, accuracy: $scope.accuracy }); } }; $scope.handleGeomSelect = function (geom, accuracy) { if (typeof ($scope.onGeomSelect) === "function") { $scope.onGeomSelect({ geom: geom, accuracy: accuracy }); } }; $scope.handleGeomChange = function (geom, accuracy) { if (typeof ($scope.onGeomChange) === "function") { $scope.onGeomChange({ geom: geom, accuracy: accuracy }); } }; //geomType $scope.geomType = null; //show on Map var tempLayerName = "__GEOMETRY_SELECTOR__", tempLayer, tempFeature; $scope.showOnMap = function (geom) { if ($scope.display !== "form") { return Promise.resolve(null); } //console.log("GS.SHOWING_ON_MAP", geom); //remove templayer (if exists) return (tempLayer ? gisVectorManager.layer.remove({ layerName: tempLayerName }) : Promise.resolve()) //create templayer .then(function () { return gisVectorManager.layer.createIfNotExists({ Code: tempLayerName, ShowInLegend: false }); }) .then(function (vectorLayer) { tempLayer = vectorLayer; //add feature geometry //console.log("GS.ADDING_GEOMETRY", { geom: geom, vectorLayer: vectorLayer }); return gisVectorManager.feature.addGeometry({ geom: geom, layer: vectorLayer }) .then(function (arg) { //console.log("GS.ADDED_GEOMETRY", arg); tempFeature = arg.features.first(); //select feature in map return gisVectorManager.feature.select({ features: [tempFeature], layer: vectorLayer }) //make feature updatable .then(function () { return gisVectorManager.feature.setEditMode(true); }) .then(function () { return { layer: vectorLayer, feature: tempFeature }; }); }); }); }; //geom updated gisViewerManager.on("feature-change", function (e, arg) { //console.log("GS.FEATURE_CHANGE", { e: e, arg: arg, tempFeature: tempFeature }); var geom = arg.features.select(function (x) { return x.geometry; }).first(); if (geom) { geoHelper.getGeometryObject(geom, function (geoJson) { geoHelper.getWKT(geom, function (wkt) { return $timeout(function () { switch (geomFormat) { case "geoJson": $scope.geom = geoJson; break; default: //case "wkt": $scope.geom = wkt; break; } $scope.changed(); $scope.handleGeomChange({ wkt: wkt, geoJson: geoJson }, null); //$scope.accuracy = null; }); }); }); } }); //watch display $scope.$watch(function () { return $scope.display; }, function (newVal, oldVal) { if (newVal) { //console.log("GS.NEW_DISPLAY", { newVal: newVal, oldVal: oldVal }); if (newVal !== oldVal) { if (newVal === "form") { if ($scope.geom) { $scope.showOnMap($scope.geom); } } else { //console.log("GS.REMOVE_LAYER", tempLayerName); gisVectorManager.layer.remove(tempLayerName) .then(function () { return gisVectorManager.feature.setEditMode(false); }); } } } }); //watch geom $scope.$watch(function () { return $scope.geom; }, function (newVal, oldVal) { if (newVal) { console.log("GS.NEW_GEOM", { newVal: newVal, oldVal: oldVal, showGeom: $scope.showGeom, display: $scope.display, scope: $scope }); if (newVal !== oldVal) { geoHelper.getGeometryObject(newVal, function (geoJson) { $timeout(function () { $scope.geomType = geoJson.type.replace("Multi", ""); }); }); } } else { $timeout(function () { $scope.geomType = null; }); } }); //Buttons (function () { var buttons = "Point,LineString,Polygon,Copy,MyLocation,Remove".split(","); var showButtons = (($attr.excludes ? buttons.except($attr.excludes.split(",")) : $attr.includes ? $attr.includes.split(",").innerJoin(buttons) : [])); if (!showButtons.any()) { showButtons = buttons; } $timeout(function () { showButtons.forEach(function (x) { $scope["show" + x] = true; }); }); })(); //ToDo: refactor the angular-way var oldScope = (function () { var scope = $scope; while (!scope.modules && scope !== scope.$parent) { scope = scope.$parent; } return scope.gis; })(); $scope.setGeometry = function (o) { return new Promise(function (resolve) { function setGeom(arg) { if (!arg.geom) { resolve(); return; } //console.log("GS.SET_GEOM", { o: o, geom: arg.geom }); //MultiGeom if ($scope.multi && !arg.geom.geoJson.type.startsWith("Multi", true)) { geoHandler.getMulti(arg.geom.wkt, function (wkt) { geoHelper.getGeometryObject(wkt, function (geoJson) { setGeom({ geom: { geoJson: geoJson, wkt: wkt, type: geoJson.type } }); }); }); return; } //use $timeout to force update view $timeout( function () { switch (geomFormat) { case "geoJson": $scope.geom = arg.geom.geoJson; break; default: //case "wkt": $scope.geom = arg.geom.wkt; break; } $scope.accuracy = arg.accuracy; //setGeomType(arg.geom.geoJson); $scope.changed(); var geom = { wkt: arg.geom.wkt, geoJson: arg.geom.geoJson }; $scope.handleGeomChange(geom, arg.accuracy); $scope.handleGeomSelect(geom, arg.accuracy); return arg.geom; }) //vectorLayer .then(function (geom) { return $scope.showOnMap(geom.geoJson) .then(function () { //onSelect if ($scope.onSelect) { return Promise.resolve($scope.onSelect.call($scope.ctrl || $scope, { geom: geom })) //make sure to send 'geom' and ignore return type of $scope.onSelect .then(function () { return geom; }) .catch($scope.handleError); } return geom; }); }) //resolve .then(function () { //console.log("GEOM", arg, $scope.geom); resolve(arg); }); } switch (o.type) { case "LineString": case "MultiLineString": $translate("global.DigitizeLine") .then(function (message) { oldScope.digitize.line({ message: message }, function (geom) { setGeom({ geom: geom }); }); }) .catch($scope.handleError); break; case "Polygon": case "MultiPolygon": $translate("global.DigitizePolygon") .then(function (message) { oldScope.digitize.polygon({ message: message }, function (geom) { setGeom({ geom: geom }); }); }) .catch($scope.handleError); break; case "Copy": $translate("global.CopyGeometry") .then(function (message) { oldScope.digitize.copy({ message: message }, function (geom) { setGeom({ geom: geom }); }); }) .catch($scope.handleError); break; case "MyLocation": $translate("global.MyLocation") .then(function (message) { oldScope.digitize.myLocation({ message: message }, function (geom, accuracy) { gisViewerManager.zoom({ center: geom.geoJson.coordinates, scale: 500 }) .then(function () { setGeom({ geom: geom, accuracy: accuracy }); }); }); }) .catch($scope.handleError); break; default: //"Point" $translate("global.DigitizePoint") .then(function (message) { oldScope.digitize.point({ message: message }, function (geom) { setGeom({ geom: geom }); }); }) .catch($scope.handleError); break; } }); }; } }; } GeometrySelectorDirective.$inject = ["config", "gisViewerManager", "gisVectorManager", "geoHelper", "geoHandler", "$translate", "$timeout"]; return GeometrySelectorDirective; })("viewer"); var viewer = viewer || {}; viewer.ZoomDirective = (function () { function ZoomDirective(gisViewerManager, geoHelper) { return { restrict: "EA", scope: { ctrl: "=", item: "=item",//entity that has a geometry getGeom: "=getGeom",//function that must return wkt/geoJson/coordinate-array minScale: "=minScale", onError: "=" }, replace: true, template: '', link: function ($scope, $el) { $el.on("click", function () { //wrap $scope.getGeom incase it doesn't return a promise Promise.resolve($scope.getGeom.call($scope.ctrl || $scope, $scope.item)) .then(function (geom) { //console.log("ZD.ZOOMING", { item: $scope.item, geom: geom }); if (_.isArray(geom) && geom.length === 4 && geom.all(function (x) { return !isNaN(parseFloat(x)); })) { return geom; } return new Promise(function(resolve) { //get boundaries geoHelper.getBounds(geom, function (bounds) { resolve(bounds); }); }); }).then(function (bounds) { //zoom to extent if (bounds) { gisViewerManager.zoomToExtent({ bounds: bounds, minScale: $scope.minScale || 250 }); } else { console.warn('No extents found'); } }).catch(function (error) { if ($scope.onError) { $scope.onError.apply($scope.ctrl || $scope, arguments); } else { throw error; } }); }); } } } ZoomDirective.$inject = ["gisViewerManager", "geoHelper"]; return ZoomDirective; })("viewer"); var viewer = viewer || {}; viewer.IndexController = (function () { "use strict"; function IndexController(config, $scope, $timeout, $translate, layerTree, infoManager) { //console.log("INDEX", this, $.extend(true, {}, $scope), $scope); //console.log("SCREEN", screen.width + " x " + screen.height, "OUTER:", window.outerWidth + " x " + window.outerHeight, "INNER:", window.innerWidth + " x " + window.innerHeight); var contentContainer = $(".content-container"); var viewerContainer = contentContainer.children(".viewer-container"); ExtendBasicScope({ scope: $scope, config: config }, $timeout, infoManager) .createMultiLanguageScope({ scope: $scope, timeout: $timeout, translate: $translate }) .createGisScope({ scope: $scope, viewer: viewerContainer, commands: config.commands, layerTree: layerTree }); if (config.niscode) { $("body").addClass("niscode-" + config.niscode); } $scope.config = config; $scope.application = new ApplicationHelper(); $scope.panels = new PanelManager(contentContainer); window.mm.InitializeScope($scope); NavigationManager.Initialize($scope); if (config.sessionId) { $scope.gis.addEvents({ mapload: function (/*e, arg*/) { //mapInitialisingOverlay.remove(); //console.info("MAP_LOADED", arg, $.extend(true, {}, $scope), $scope.gis.viewer.gisviewer("getMapOffset"), arg.layers.toDictionary(function (x) { return x.Code; })); //layerTree.tree = arg.layers; var viewerSize = [viewerContainer.width(), viewerContainer.height()]; viewerContainer.on("resize", function (e, arg) { var el = this; var newSize = [$(el).width(), $(el).height()]; if (newSize[0] !== viewerSize[0] || newSize[1] !== viewerSize[1]) { $.delay("viewerresize", function () { //console.log("UPDATE_MAP_SIZE", { size: newSize, oldSize: viewerSize, el: el, evt: e, arg: arg }); viewerSize = newSize; viewerContainer.gisviewer("updateSize"); }, 200); } }); //TEST $compile //var el = $("TestCompile") // .appendTo($scope.gis.viewer); //$compile(el)($scope); } }, "index-controller"); } $scope.onProjectSelect = function (infoEl) { console.log("VC.PROJECT_SELECT", { scope: $scope, infoEl: infoEl, args: arguments }); if ($(infoEl).is(":visible")) { $(".viewer-container,.panels-container").css({ "margin-top": "calc(" + infoEl.height() + "px + .15em)", "height": "calc(100% - " + infoEl.height() + "px + .15em)" }); } else { $(".viewer-container,.panels-container").css({ "margin-top": "inherit", "height": "inherit" }); } }; } IndexController.$inject = ["config", "$scope", "$timeout", "$translate", "layerTree", "infoContainerManager"]; return IndexController; })(); var viewer = viewer || {}; viewer.ViewerInfoController = (function () { "use strict"; function ViewerInfoController(manager, gisViewer) { var me = this; var panelManager = new PanelManager($(".content-container")); var currentMessage; Object.defineProperties(me, { data: { value: {} }, canToggleUi: { get: function() { var message = manager.message; return message && message.extra && message.extra.toggleUi; }, enumerable: true }, toggleUi: { value: function () { if (me.data.ui) { return me.showUi(); } return me.hideUi(); } }, hideUi: { value: function () { me.data.ui = panelManager.hideAllPanels(); currentMessage = manager.message; currentMessage.on("closing", function () { currentMessage = null; return me.showUi(); }); return gisViewer.updateSize(); } }, showUi: { value: function () { if (me.data.ui) { me.data.ui.restore(); me.data.ui = null; if (currentMessage) { currentMessage.off("closing"); } return gisViewer.updateSize(); } return Promise.resolve(); } } }); } return ViewerInfoController; })("viewer"); var viewer = viewer || {}; viewer.LayerTree = (function () { "use strict"; function LayerTree() { return { tree: null, getAll: function () { return (this.tree || []).where(function (x) { return x.Type.endsWith("L"); }); }, getVisible: function () { return this.getAll().where(function (x) { return x.IsVisible; }); }, getSelectable: function () { return this.getAll().where(function (x) { return x.IsSelectable; }); }, findLayer: function (layerName) { return this.getAll().first(function (x) { return x.Code === layerName; }) } }; } return LayerTree; })(); var viewer = viewer || {}; viewer.GisFeatureManager = (function () { "use strict"; function GisFeatureManager(gisViewerManager) { var sv = this; Object.defineProperties(sv, { _viewer: { value: gisViewerManager }, autoRetrieve: { value: true, writable: true, enumerable: true }, featureCount: { writable: true, enumerable: true }, selection: { value: {}, writable: true, enumerable: true }, features: { writable: true, enumerable: true } }); sv.init(); } EventHandler.injectInto(GisFeatureManager.prototype); Object.defineProperties(GisFeatureManager.prototype, { _getSelectedFeatures: { value: function (o) { return this._viewer.getSelectedFeatures(angular.extend({}, o || {}, { propertiesBitmask: o.propertiesBitmask || 7 })); } }, _onSelectionChange: { value: function (e, arg) { var sv = this; var oldSelection = sv.selection; sv.featureCount = arg.featureCount; sv.selection = arg.selection; sv.features = (arg.selection ? arg.selection.features : null) || []; var newArg = angular.extend({ deselected: oldSelection, features: sv.features, getSelectionIds: function (layerNames) { if (!arg.selection || arg.featureCount === 0) { return Promise.resolve({}); } layerNames = layerNames ? _.array(layerNames) : []; if (sv.autoRetrieve) { if (!layerNames.any()) { return Promise.resolve(angular.extend({}, sv.selection)); } return Promise.resolve(layerNames.aggregate(function (r, x) { r[x] = sv.selection[x]; return r; }, {})); } return sv.getSelection(layerNames); }, getSelectionDetails: function (layerNames) { if (!arg.selection || arg.featureCount === 0) { return Promise.resolve({}); } return sv._getSelectedFeatures(layerNames ? { layerNames: layerNames } : null); } }, arg); //console.log("GFS.SELECTION_CHANGE", { gvmArg: $.extend(true, {}, arg), svArg: newArg, service: sv }); if (sv.autoRetrieve && arg.featureCount > 0) { return sv.getSelection(Object.keys(arg.selection)) .then(function (selection) { sv.selection = selection; newArg.selection = selection; return sv.trigger(e, newArg); }); } return sv.trigger(e, newArg); } }, _onFeatureChange: { value: function (e, arg) { this.trigger(e, arg); } }, init: { value: function () { this._viewer .on("selection-change", { scope: this, callback: this._onSelectionChange }) .on("feature-change", { scope: this, callback: this._onFeatureChange }); } }, getSelection: { value: function (layerName) { var sv = this; var layerNames = layerName ? _.array(layerName) : null; return sv._getSelectedFeatures({ layerNames: layerNames, propertiesBitmask: 1 }) .then(function (selection) { Object.keys(selection).forEach(function (k) { selection[k] = selection[k].select(function (x) { return _.toArray(x).first().value; }); }); return selection; }); } }, _getFeatures: { //{ layer | layerName, filter, wktContainer, propertiesBitmask } value: function (o, bitmask) { return this._viewer.getFeatures(angular.extend({}, o || {}, { propertiesBitmask: bitmask })); } }, getFeatureIds: { //{ layer | layerName, filter, wktContainer } value: function (o) { return this._getFeatures(o, 1); } }, getFeatureList: { //{ layer | layerName, filter, wktContainer } value: function (o) { return this._getFeatures(o, 5); } }, getFeatureGeoms: { //{ layer | layerName, filter, wktContainer } value: function (o) { return this._getFeatures(o, 2); } }, getFeatureDetails: { //{ layer | layerName, filter, wktContainer } value: function (o) { return this._getFeatures(o, 7); } }, dispose: { value: function () { this._viewer .off("selection-change", this._onSelectionChange) .off("feature-change", this._onFeatureChange); } } }); GisFeatureManager.$inject = ["gisViewerManager"]; return GisFeatureManager; })("viewer"); var viewer = viewer || {}; viewer.GisLayerManager = (function () { "use strict"; function GisLayerManager(gisViewerManager) { var sv = this; Object.defineProperties(sv, { _viewer: { value: gisViewerManager } }); } return GisLayerManager; })("viewer"); (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD define([], factory); } else if (typeof exports === 'object') { // Node, CommonJS-like module.exports = factory(); } else { root.viewer = root.viewer || {}; root.viewer.SnappingManager = factory("viewer"); } }(this, function () { "use strict"; function SnappingManager(gisViewerManager, layerTree) { Object.defineProperties(this, { _gisViewer: { value: gisViewerManager }, _layerTree: { value: layerTree }, _layers: { value: [], writable: true }, _selected: { value: null, writable: true }, _snapEdges: { value: true, writable: true } }); }; EventHandler.injectInto(SnappingManager.prototype); Object.defineProperties(SnappingManager.prototype, { layers: { get: function () { return this._layers; }, enumerable: true }, selected: { get: function () { return this._selected; }, set: function (value) { this.setSelected(value); }, enumerable: true }, snapEdges: { get: function () { return this._snapEdges; }, set: function (value) { //console.debug("SNAP_EDGES", { mgr: this, value: value }); this.setSnapOptions({ snapEdges: value }); }, enumerable: true }, list: { value: function (scale) { var mgr = this; var originalLayers = mgr._layers.select(); mgr._layers = mgr._layerTree.getSelectable() .where(function (layer) { return layer.ShowInLegend && layer.IsVisible && layer.CanBeVisible(scale); }); var arg = { items: mgr._layers, original: originalLayers }; return mgr.trigger("change-items", arg) .then(function () { return Promise.resolve() .then(function () { if (mgr.selected != null && !mgr.layers.contains(mgr.selected)) { return mgr.setSelected(null); } return false; }) .then(function () { return arg; }); }); } }, isSelected: { value: function (layer) { return this.selected != null && this.selected.Code === layer.Code; } }, setSelected: { value: function (value) { var original = this._selected; if (value == null) { this._selected = null; } else { this._selected = this._layers.first(function (layer) { return layer.Code === value.Code; }); } var options = { snapEdges: this._snapEdges }; var arg = { item: this._selected, original: original, options: options }; return this.trigger("change-snapping change-selected", arg) .then(function () { return arg; }); } }, setSnapOptions: { value: function (options) { var originalOptions = { snapEdges: this._snapEdges }; this._snapEdges = options.snapEdges; var arg = { options: options, original: originalOptions }; return this.trigger("change-snapping change-snap-options", arg) .then(function () { return arg; }); } } }); return SnappingManager; })); var viewer = viewer || {}; viewer.GisVectorFeatureManager = (function () { "use strict"; function GisVectorFeatureManager(gisViewerManager) { var sv = this; viewer.GisFeatureManager.call(sv, gisViewerManager); } GisVectorFeatureManager.prototype = Object.create(viewer.GisFeatureManager.prototype, { constructor: { value: GisVectorFeatureManager }, getSelection: { value: function (layerName) { var sv = this; return sv.features[layerName]; } } }); return GisVectorFeatureManager; }); var viewer = viewer || {}; viewer.GisVectorLayerManager = (function () { "use strict"; function GisVectorLayerManager(gisViewerManager) { var sv = this; viewer.GisLayerManager.call(sv, gisViewerManager); } GisVectorLayerManager.prototype = Object.create(viewer.GisLayerManager.prototype, { constructor: { value: GisVectorLayerManager } }); return GisVectorLayerManager; }); var viewer = viewer || {}; viewer.GisVectorManager = (function () { "use strict"; function LayerManager(layerTree, gisViewerManager) { Object.defineProperties(this, { _layerTree: { value: layerTree }, _viewer: { value: gisViewerManager }, _defaultLayer: { get: function () { return { Code: "feature-layer", Title: "Features", Type: "FL", IsVisible: true, IsSelectable: true, CanBeSelectable: true, ShowInLegend: true }; } }, _defaultGroup: { get: function () { return { Code: "feature-group", Title: "Features", Type: "FG", IsVisible: true, IsSelectable: true, CanBeSelectable: true, ShowInLegend: true }; } } }); } Object.defineProperties(LayerManager.prototype, { createIfNotExists: { //{ Code, Type[, Title, ParentCode, group, groupName] } value: function (o) { var lm = this; var code = o.Code || o; var type = o.Type; //console.log("lmS.CHECKING_LAYER", code, type); return lm.find({ layerName: code, type: type }) .then(function (item) { if (!item) { if (o.group) { //console.log("lmS.CREATING_GROUP", o.group); var group = typeof o.group === "string" ? { Code: o.group } : o.group; group.Type = "FG"; return lm.createIfNotExists(group) .then(function (arg) { //console.log("lmS.GROUP_CREATED", arg); delete o.group; o.ParentCode = arg.Code; return lm.createIfNotExists(o) .then(function (arg) { //console.log("lmS.LAYER_CREATED", arg); return arg; }); }); } else { return lm.add(o) .then(function (arg) { //console.log("lmS.LAYER_CREATED", arg); return arg; }); } } else { return item; } }); } }, find: { value: function (o) { var lm = this; var layerName = o.Code || o.layerName || o; var type = o.type; var layer = lm._layerTree.tree.first(function (x) { return layerName === x.Code && (!type || x.Type.endsWith(type)); }); return Promise.resolve(layer); } }, add: { value: function (o) { var lm = this; if (typeof o === "string") o = { Code: o, Title: o }; function add(layer) { return lm._viewer.addLayer({ layer: layer, position: o.position }) .then(function (arg) { return arg.added.first(); }); } function createLayer(layer) { layer = $.extend({}, (!layer.Type || layer.Type.endsWith("L")) ? lm._defaultLayer : lm._defaultGroup, layer); //layer already exists (ToDo: better check needed) if (layer.Type.endsWith("L")) { return lm._viewer.createVectorLayer({ layer: layer }) .then(function (vectorLayer) { return add(vectorLayer); }); } else { return add(layer); } } var parentCode = o.group ? o.group.Code : (o.groupName || o.ParentCode); var parentTitle = (o.group ? o.group.Title : null) || parentCode; var promise; if (parentCode) { promise = lm.find({ layerName: parentCode, type: "G" }) .then(function (parent) { if (!parent) { return createLayer({ Code: parentCode, Title: parentTitle, Type: "FG" }) .then(function (parent) { //console.log("lmS.PARENT_CREATED", parent); return createLayer($.extend({}, o, { ParentCode: parent.Code })); }); } else { o.ParentCode = parentCode; return createLayer(o); } }); } else { promise = createLayer(o); } return promise; } }, refresh: { value: function (o) { return this._viewer.refreshVectorLayer({ layerNames: _.array(o.layerNames || o.layerName || o) }); } }, remove: { value: function (o) { var lm = this; var layerName = typeof o === "string" ? o : (o.layerName || o.Code); var groupName = o.groupName; //Alleen verwijderen als laag/group bestaat (ToDo: anders kan verkeerde item verwijderd worden -> bug) return lm.find(layerName || groupName) .then(function (item) { if (item) { return lm._viewer[layerName ? "removeLayer" : "removeGroup"](layerName ? { layer: item } : { group: item }); } return Promise.resolve({ layer: {}, layers: [], result: false }); }); } } }); function FeatureManager(layerManager, gisViewerManager, gisFeatureService, geoHelper) { var fm = this; Object.defineProperties(this, { _lm: { value: layerManager }, _viewer: { value: gisViewerManager }, _geoHelper: { value: geoHelper }, selectedFeatures: { writable: true, enumerable: true } }); gisFeatureService.on("selection-change", function (e, arg) { fm.selectedFeatures = arg.features; //console.log("FM.SELECTION", { featureManager: fm, evt: e, arg: arg, selection: $.extend(true, {}, arg.features) }); }); } Object.defineProperties(FeatureManager.prototype, { _findLayer: { value: function (layer) { if (typeof (layer) === "string") { return this._lm.find(layer); } return Promise.resolve(layer); } }, _getFeatures: { value: function (o) { if (o.layer == null) { return Promise.resolve([]); } if (o.features || o.feature) { return Promise.resolve(_.array(o.features || o.feature)); } return this.find(o); } }, clearSelection: { value: function () { //ToDo: fix error for VectorLayers return this._viewer.clearSelection(); } }, find: { value: function (o) { var fm = this; return fm._findLayer(o.layer) .then(function (layer) { return fm._viewer.getFeatures({ layer: layer, filter: o.filter }); }); } }, select: { value: function (o) { var fm = this; var features = _.array(o.features || o.feature); if (features && !features.any()) { return fm.clearSelection() .then(function () { return { selected: [] } }); } else { return fm._findLayer(o.layer) .then(function (layer) { return fm._viewer.setSelectedFeatures({ layer: layer, preserve: o.preserve, features: features, filter: o.filter }) .then(function (arg) { //console.log("GVM.SELECT", { layer: layer, features: features, o: o, arg: arg }); if (!arg.selection) { return { selected: [] }; } return { selected: arg.selection[layer.Code] }; }); }); } } }, add: { value: function (o) { var fm = this; var features = _.array(o.features || o.feature); var projection = o.projection; features.each(function (x, i) { if (!x.properties || !x.properties.style || x.properties.style.zIndex == undefined) { $.extend(true, x, { properties: { style: { zIndex: features.length + i } } }); } //if (featureStyle) { // $.extend(true, x, featureStyle ? { properties: { style: featureStyle } } : {}); //} }); return fm._findLayer(o.layer) .then(function (layer) { if (features.length) { return fm._viewer.addFeatures({ layer: layer, features: features, projection: projection }) .then(function (arg) { return { added: arg.features, features: arg.features }; }); } return { added: [], features: features }; }); } }, addGeometry: { value: function (o) { var fm = this; return new Promise(function (resolve) { fm._geoHelper.getGeometryObject(o.geom, function (geom) { var feature = { geometry: geom }; if (o.style) { feature["properties"] = { style: o.style }; } //console.log("GV.ADD", feature); fm.add({ features: [feature], layer: o.layer }) .then(function (arg) { resolve(arg); }); }); }); } }, setSortOrder: { value: function (items) { items.forEach(function (x, i) { if (!x.properties) x.properties = {}; if (!x.properties.style) x.properties.style = {}; x.properties.style.zIndex = i; }); } }, update: { value: function (o) { var fm = this; o = o || {}; if (o.layer == null) { return Promise.resolve({ features: [], layer: null }); } return fm._findLayer(o.layer) .then(function (layer) { return fm._getFeatures(o) .then(function (features) { return fm._viewer.updateFeatures({ layer: layer, features: features }); }); }); } }, remove: { value: function (o) { var fm = this; var clearSelection = (typeof (o.clearSelection) === "undefined") ? true : !!o.clearSelection; if (o.layer == null) { return Promise.resolve({ features: [], layer: null }); } return fm._findLayer(o.layer) .then(function (layer) { return fm._getFeatures(o) .then(function (features) { //console.log("GVM.REMOVE", { features: features, layer: layer, o: o }); if (features.length) { return fm._viewer.removeFeatures({ layer: layer, features: features, clearSelection: clearSelection }); } return { features: [], layer: layer }; }); }); } }, hide: { value: function (o) { var fm = this; return fm._findLayer(o.layer) .then(function (layer) { return fm._getFeatures(o) .then(function (features) { return fm._viewer.hideFeatures({ layer: layer, features: features }); }); }); } }, show: { value: function (o) { var fm = this; return fm._findLayer(o.layer) .then(function (layer) { return fm._getFeatures(o) .then(function (features) { return fm._viewer.showFeatures({ layer: layer, features: features }); }); }); } }, zoom: { value: function (o) { var fm = this; var features = _.array(o.features || o.feature || o); return new Promise(function (resolve) { //console.log("FM.ZOOM", features); fm._geoHelper.getBounds(features.select(function (x) { return x.geometry; }), function (bounds) { fm._viewer.zoomToExtent({ bounds: bounds, minScale: 250, refresh: false }) .then(function (arg) { resolve(arg); }); }); }); } }, setEditMode: { value: function (updatable) { return this._viewer.setFeaturesEditMode(updatable); } }, getFeaturesEditMode: { value: function () { return this._viewer.getFeaturesEditMode(); } } }); function GisVectorManager(layerTree, gisViewer, gisFeatureService, geoHelper) { var layerManager = new LayerManager(layerTree, gisViewer); var featureManager = new FeatureManager(layerManager, gisViewer, gisFeatureService, geoHelper); Object.defineProperties(this, { layer: { value: layerManager, enumerable: true }, feature: { value: featureManager, enumerable: true } }); } GisVectorManager.$inject = ["layerTree", "gisViewerManager", "gisFeatureService", "geoHelper"]; return GisVectorManager; })("viewer"); var viewer = viewer || {}; viewer.GisViewerManager = (function () { "use strict"; function GisViewerManager(mapElement, layerTree, gisHandler, geoHelper, geoHandler) { var sv = this; Object.defineProperties(this, { element: { value: mapElement, enumerable: true }, _layerTree: { value: layerTree }, _gisHandler: { value: gisHandler }, _geoHelper: { value: geoHelper }, _geoHandler: { value: geoHandler }, _events: { value: {} } }); //console.log("GV", sv.element); sv.element //pre-load .on("gisviewerpreload", function (e, arg) { var eventDefinition = { event: new Event("pre-load", e), args: arg }; Object.defineProperties(sv._events, { preLoad: { value: eventDefinition } }); sv.trigger(eventDefinition.event, eventDefinition.args); }) //map-load .on("gisviewermapload", function (e, arg) { var eventDefinition = { event: new Event("map-load", e), args: arg }; Object.defineProperties(sv._events, { mapLoad: { value: eventDefinition } }); layerTree.tree = arg.layers; //console.log("GV.MAP-LOAD", { me: sv, layerTree: sv._layerTree, evt: e, arg: $.extend(true, {}, arg) }); sv.trigger(eventDefinition.event, eventDefinition.args); }) //map-load-error .on("gisviewermaploaderror", function (e, arg) { var eventDefinition = { event: new Event("map-load-error", e), args: arg }; Object.defineProperties(sv._events, { mapLoadError: { value: eventDefinition } }); sv.trigger(eventDefinition.event, eventDefinition.args); }) //map-update .on("gisviewermapupdated", function (e, arg) { sv.trigger(new Event("map-update", e), arg); }) .on("gisviewermapcomposed", function (e, arg) { sv.trigger(new Event("map-composed", e), arg); }) //resize-map .on("gisviewerresizemap", function (e, arg) { sv.trigger(new Event("resize-map", e), arg); }) //scale-change .on("gisviewerscalechanged", function (e, arg) { sv.trigger(new Event("scale-change", e), arg); }) //center-change .on("gisviewercenterchanged", function (e, arg) { sv.trigger(new Event("center-change", e), arg); }) //selection-change .on("gisviewerselectionchanged", function (e, arg) { var evt = new Event("selection-change", e); evt.initiator = arg.initiator || "system"; sv.trigger(evt, { featureCount: arg.count, layerCount: arg.layerCount, selection: arg.selection, initiator: arg.initiator }); }) //layer-change .on("gisviewervisibilitychanged", function (e, arg) { //console.log("GVM.VISIBILITY", { e: e, arg: arg }); sv.trigger(new Event("layer-change", e), { action: "visibility", layers: arg.layers, visible: arg.visible }); }) .on("gisviewerselectabilitychanged", function (e, arg) { //console.log("GVM.SELECTABILITY", { e: e, arg: arg }); sv.trigger(new Event("layer-change", e), { action: "selectability", layers: arg.layers, selectable: arg.selectable }); }) .on("gisviewerlayeradded", function (e, arg) { //console.log("GVM.LAYER_ADDED", { e: e, arg: arg }); sv.trigger(new Event("layer-change", e), { action: "added", layers: arg.layers }); }) .on("gisviewerlayerremoved", function (e, arg) { //console.log("GVM.LAYER_REMOVED", { e: e, arg: arg }); sv.trigger(new Event("layer-change", e), { action: "removed", layers: arg.layers }); }) .on("gisviewerrefreshlayers", function (e, arg) { sv.trigger(new Event("layers-refresh", e), { tree: arg.tree }); }) //feature-change .on("gisviewerfeaturechange", function (e, arg) { //console.log("GV.FEATURE_CHANGE", e, arg); sv.trigger(new Event("feature-change", e), arg); }) //digitizing .on("gisviewerstartdigitize", function (e, arg) { sv.trigger(new Event("start-digitize", e), arg); }) .on("gisviewerdigitizing", function (e, arg) { sv.trigger(new Event("digitizing", e), arg); }) .on("gisviewervertexadded", function (e, arg) { sv.trigger(new Event("add-vertex", e), arg); }) .on("gisviewerenddigitize", function (e, arg) { sv.trigger(new Event("end-digitize", e), arg); }) //request-select // -> triggered in copyGeometry function //mousemove .on("gisviewermousemove", function (e, arg) { sv.trigger(new Event("mousemove", e), arg); }); } EventHandler.injectInto(GisViewerManager.prototype); var originalOn = GisViewerManager.prototype.on; var originalOnce = GisViewerManager.prototype.once; Object.defineProperties(GisViewerManager.prototype, { initialExtent: { get: function () { return this._loadedArgs.extent; }, enumerable: true }, initialScale: { get: function () { return this._loadedArgs.scale; }, enumerable: true }, initialCenter: { get: function () { return this._loadedArgs.center; }, enumerable: true }, scale: { get: function () { return this.element.gisviewer("getScale"); }, enumerable: true }, center: { get: function () { return this.element.gisviewer("getCenter"); }, enumerable: true }, cursorPosition: { get: function () { return this.element.gisviewer("getCursorPosition"); }, enumerable: true }, extent: { get: function () { return this.element.gisviewer("getBounds"); } }, unitsPerPixel: { get: function () { return this.element.gisviewer("getUnitsPerPixel"); } }, //override "on" to catch mapload when the map is already loaded on: { value: function (e, callback) { var sv = this; if (sv._events.preLoad && (e === sv._events.preLoad.event.type || e.type === sv._events.preLoad.event.type)) { //als pre-load al uitgevoerd is callback(sv._events.preLoad.event, sv._events.preLoad.args); return sv; } if (sv._events.mapLoad && (e === sv._events.mapLoad.event.type || e.type === sv._events.mapLoad.event.type)) { //als map al geladen is callback(sv._events.mapLoad.event, sv._events.mapLoad.args); return sv; } if (sv._events.mapLoadError && (e === sv._events.mapLoadError.event.type || e.type === sv._events.mapLoadError.event.type)) { //als mapladen als mislukt is callback(sv._events.mapLoadError.event, sv._events.mapLoadError.args); return sv; } return originalOn.apply(sv, arguments); } }, once: { value: function (e, callback) { var sv = this; if (sv._events.preLoad && (e === sv._events.preLoad.event.type || e.type === sv._events.preLoad.event.type)) { //als pre-load al uitgevoerd is callback(sv._events.preLoad.event, sv._events.preLoad.args); return sv; } if (sv._events.mapLoad && (e === sv._events.mapLoad.event.type || e.type === sv._events.mapLoad.event.type)) { //als map al geladen is callback(sv._events.mapLoad.event, sv._events.mapLoad.args); return sv; } if (sv._events.mapLoadError && (e === sv._events.mapLoadError.event.type || e.type === sv._events.mapLoadError.event.type)) { //als mapladen als mislukt is callback(sv._events.mapLoadError.event, sv._events.mapLoadError.args); return sv; } return originalOnce.apply(sv, arguments); } }, //Map getMapInfo: { value: function () { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("getMapInfo", resolve); }); } }, zoom: { //{ center, scale, refresh } value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("zoom", o, resolve); }); } }, zoomToExtent: { value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("zoomToExtent", { bounds: o.extent || o.bounds, refresh: o.refresh, minScale: o.minScale }, resolve); }); } }, rotateMap: { value: function (rotation, coordinate) { return this.element.gisviewer("setRotate", rotation, coordinate); } }, refreshMap: { value: function () { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("refreshMap", resolve); }); } }, updateSize: { value: function () { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("updateSize", resolve); }); } }, //Layers getLayers: { value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("getLayers", o || {}, resolve); }); } }, refreshVectorLayer: { value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("refreshVectorLayer", o, resolve); }); } }, refreshLayers: { value: function () { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("refreshLayers", resolve); }); } }, findLayer: { value: function (o) { var layerName = o.Code || o.layerName || o; var type = o.type; var layer = this._layerTree.tree.first(function (x) { return x === o || (layerName === x.Code && (!type || x.Type.endsWith(type))); }); return Promise.resolve(layer); } }, addLayers: { value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("addLayers", o, resolve); }); } }, addLayer: { value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("addLayer", o, resolve); }); } }, createVectorLayer: { value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("createVectorLayer", o, resolve); }); } }, removeLayer: { value: function (o) { return this.removeLayers(o); } }, removeLayers: { value: function (o) { var sv = this; if (Array.isArray(o.layers)) { return Promise.all(o.layers.select(function (x) { return new Promise( function (resolve) { sv.element.gisviewer("removeLayer", { layer: x }, resolve); }); })); } return new Promise( function (resolve) { sv.element.gisviewer("removeLayer", o, resolve); }); } }, removeGroup: { value: function (o) { var sv = this; return new Promise( function (resolve) { sv.element.gisviewer("removeGroup", o, resolve); }) .then(function (arg) { //return sv.refreshLegend().then(function () { return arg; //}); }); } }, setLayerVisibility: { value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("setLayerVisibility", o, resolve); }); } }, setLayerSelectability: { value: function (o) { var sv = this; return sv.findLayer(o.layer || { layerName: o.layerName }) .then(function (layer) { if (layer && layer.Type.endsWith("G")) { var nodes = sv._layerTree.tree.getNodes(layer); var offspring = sv._layerTree.tree.getOffspring(nodes).where(function (x) { return x.value.CanBeSelectable && x.value.IsSelectable !== o.selectable; }); var layers = [layer].concat(offspring.select(function (x) { return x.value; })); o = { layers: layers, selectable: o.selectable }; } return new Promise(function (resolve) { sv.element.gisviewer("setLayerSelectability", o, resolve); }); }); } }, updateLayer: { value: function (layer) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("updateLayer", layer, resolve); }); } }, getLayerExtent: { value: function (o) { var sv = this; return sv.element.gisviewer("getLayerExtent", o); } }, //Features getFeatureLayerName: { value: function (o) { return this._gisHandler.get("getfeaturelayername", { filter: o.filter, layers: o.layerNames, layer: o.layerNameTerm }); } }, getFeatures: { //{ layer | layerName, filter, geom, propertiesBitmask } value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("getFeatures", o, resolve); }); } }, getOlFeatures: { value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("getOlFeatures", o || {}, function (features) { resolve(features.select(function (f) { return f.get("data-item"); })); }); }); } }, createOlFeature: { value: function (feature, o) { var sv = this; return new Promise(function (resolve) { resolve(sv.element.gisviewer("createOlFeature", feature, o)); }); } }, updateOlFeatures: { value: function (features, layer) { var sv = this; return new Promise(function (resolve) { resolve(sv.element.gisviewer("updateOlFeatures", features, layer)); }); } }, getFeaturesExtent: { //{ layerName, filter, geom } value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("getFeaturesExtent", o, resolve); }); } }, getDistance: { value: function (geom1, geom2) { return this.element.gisviewer("getDistance", geom1, geom2); } }, getClosestFeatures: { //{ layers, geom|pixel } value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("getClosestFeatures", o, resolve); }); } }, filter: { //{ [layerName]: filter, geom } value: function (o) { var sv = this; //console.log("GVM.FILTER", { filter: o.filter }); return new Promise(function (resolve) { sv.element.gisviewer("filter", o, resolve); }); } }, clearFilters: { value: function () { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("clearFilters", resolve); }); } }, addFeatures: { value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("addFeatures", o, resolve); }); } }, updateFeatures: { value: function (o) { var sv = this; return new Promise(function (resolve) { if (_.isArray(o.features) && o.features.length) { sv.element.gisviewer("updateFeatures", o, resolve); } return { layer: o.layer, features: [] }; }); } }, removeFeatures: { value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("removeFeatures", o, function (arg) { if (o.clearSelection) { sv.clearSelection() .then(function () { resolve(arg); }); } else { resolve(arg); } }); }); } }, hideFeatures: { value: function (o) { var sv = this; return new Promise(function (resolve) { if (_.isArray(o.features) && o.features.length) { sv.element.gisviewer("hideFeatures", o, resolve); return; } resolve({ layer: o.layer, features: [] }); }); } }, showFeatures: { value: function (o) { var sv = this; return new Promise(function (resolve) { if (_.isArray(o.features) && o.features.length) { sv.element.gisviewer("showFeatures", o, resolve); return; } resolve({ layer: o.layer, features: [] }); }); } }, setFeaturesEditMode: { value: function (updatable) { this.element.gisviewer("setFeaturesModifiable", updatable); } }, getFeaturesEditMode: { value: function () { return this.element.gisviewer("getFeaturesModifiable"); } }, setFeaturesTransformMode: { value: function (updatable) { this.element.gisviewer("setFeaturesTransformable", updatable); } }, getFeaturesTransformMode: { value: function () { return this.element.gisviewer("getFeaturesTransformable"); } }, //setSnappable: { // value: function (layer, features) { // return this.element.gisviewer("setSnappable", layer, features); // } //}, addSnappable: { value: function (features, options) { return this.element.gisviewer("addSnappable", features, options); } }, removeSnappable: { value: function (features) { return this.element.gisviewer("removeSnappable", features); } }, clearSnappable: { value: function () { return this.element.gisviewer("clearSnappable"); } }, //Selection clearSelection: { value: function () { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("clearSelection", resolve); }); } }, getSelectedFeatures: { //{ layerName, properties, propertiesBitmask } value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("getSelectedItems", o, resolve); }); } }, setSelectedFeatures: { value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("setSelection", o, resolve); }); } }, //selectMultiple: { // value: function (o) { // var me = this; // o = o || {}; // return me.digitizePolygon() // .then(function (geom) { // console.log("SELECT_MULTIPLE", { geom: geom, o: o }); // o.multi = true; // o.geom = geom.geoJson; // o.zoomToSelection = false; // o.initiator = "user"; // if (!("layers" in o)) { // o.layers = me._layerTree.getAll().where(function (x) { return x.Type.endsWith("L") && x.IsVisible; }); // } // return me.setSelectedFeatures(o); // }); // } //}, //MapGuide getResourceIds: { value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("getResourceIds", o, resolve); }); } }, //Digitizing digitizePoint: { value: function () { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("digitizePoint", resolve); }); } }, digitizeLine: { value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("digitizeLine", o, resolve); }); } }, digitizePolygon: { value: function () { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("digitizePolygon", resolve); }); } }, digitizeCircle: { value: function () { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("digitizeCircle", resolve); }); } }, digitizeSquare: { value: function () { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("digitizeSquare", resolve); }); } }, digitizeRectangle: { value: function () { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("digitizeRectangle", resolve); }); } }, cancelDigitizing: { value: function () { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("cancelDigitizing", resolve); }); } }, finishDigitizing: { value: function () { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("finishDigitizing", resolve); }); } }, copyGeometry: { value: function (options) { var v = this; options = options || {}; return v.getSelectedFeatures({ propertiesBitmask: 2 }) .then(function (items) { _.array(options.ignore || []) .forEach(function (l) { if (l in items) { delete items[l]; } }); var groupedByLayer = _.toArray(items); //console.log("GV.COPY_SELECTED", { selected: items, grouped: groupedByLayer }); if (!(groupedByLayer.length === 1 && groupedByLayer.first().value.length === 1)) { var cancelCopy; var copyArgs = { cancel: function () { if (typeof (cancelCopy) !== "function") { console.warn("Cancel copy-geometry failed"); } cancelCopy(); } }; v.trigger(new Event("start-copy-geom"), copyArgs); return new Promise(function (resolve) { cancelCopy = function () { v.trigger(new Event("end-copy-geom"), { canceled: true }); resolve(/*{ geoJson: null, wkt: null, coordinates: null, type: null }*/); }; v.once("selection-change", function (e, arg) { v.trigger(new Event("end-copy-geom", e), arg); cancelCopy = null; resolve(v.copyGeometry(options)); }); }); } var input; var firstFeature = groupedByLayer.first().value.first(); //console.log("GEOM.COPY", { firstFeature: firstFeature }); if (firstFeature.type === "Feature") { input = firstFeature.geometry; } else { input = _.toArray(firstFeature).first().value; if (input != null && input.contains("XYZ")) { var prefix = input.substring(0, input.indexOf('(') - 1).replace('XYZ', '').trim(); var arr2d = input.substring(input.indexOf('(') + 1, input.length - 1).split(', ').select(function (c) { return c.split(' ').take(2); }); input = prefix + " (" + arr2d.select(function (c) { return c.join(' '); }).join(',') + ")"; //return new Promise(function (resolve) { // v._geoHandler.force2d(input, resolve); //}); } } var result = { source: firstFeature, geom: input != null ? v._geoHelper.getGeom(input) : null }; return result; }); } }, //Transform getCoordinateFromPixel: { value: function (pixel) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("getCoordinateFromPixel", pixel, resolve); }); } }, getPixelFromCoordinate: { value: function (coordinate) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("getPixelFromCoordinate", coordinate, resolve); }); } }, getMapOffset: { value: function () { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("getMapOffset", resolve); }); } }, getMapDimensions: { value: function () { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("getMapDimensions", resolve); }); } }, //Position getClientPosition: { value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("getClientPosition", o || {}, resolve); }); } }, //Print getBlob: { // { type, dpi, quality } value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("getBlob", o, resolve); }); } }, getDataUrl: { // { type, dpi, quality } value: function (o) { var sv = this; return new Promise(function (resolve) { sv.element.gisviewer("getDataUrl", o, resolve); }); } } }); return GisViewerManager; })(); var viewer = viewer || {}; viewer.Bootstrapper = (function (moduleName) { "use strict"; function Bootstrapper(config, viewer, $translate, $timeout, $compile, $scope) { var bs = this; var copyOptions; var digitizingOptions; var digitizingMessage; this.initSnapping = function (snappingManager, geoHelper) { var prevSnappable = []; function setSnappable() { return snappingManager.list(viewer.scale) .then(function () { if (prevSnappable.length > 0) { return viewer.removeSnappable(prevSnappable); } return false; }) .then(function () { var layer = snappingManager.selected; if (layer != null) { var geom = geoHelper.getBoundPolygon(viewer.extent); var wkt = geoHelper.getWKT(geom); return viewer.getFeatures({ layer: layer, geom: wkt, propertiesBitmask: 3 }) .then(function (features) { if (layer.Type === "L") { var geomColumnName = layer.MetaData.Geom; var geometries = features.select(function (f) { return f[geomColumnName]; }); return geometries.select(function (geom) { return { type: "Feature", properties: { layerName: layer.Code }, geometry: geoHelper.getGeometryObject(geom) }; }); } return features; }) .then(function (features) { var snapOptions = { snapEdges: snappingManager.snapEdges }; //console.log("VBS.SNAP_FEATURES", { features: features, layer: layer, options: snapOptions }); prevSnappable = features; return viewer.addSnappable(features, snapOptions); }); } return false; }); } var debouncedSetSnappable = F.debounce(setSnappable, 250); viewer .on("map-load", function () { debouncedSetSnappable(); }) .on("scale-change center-change", function () { debouncedSetSnappable(); }); snappingManager .on("change-snapping", function () { return debouncedSetSnappable(); }) .on("change-snapping change-items change-selected", $timeout); return Promise.resolve(bs); }; this.initCommands = function (commandBag) { commandBag.add([{ name: "Refresh", content: "", title: function () { return $translate("global.RefreshMap"); }, callback: function () { viewer.clearSelection() .then(function () { return viewer.clearFilters(); }) .then(function () { return viewer.refreshMap(); }); } }, { name: "InitialExtent", content: "", title: function () { return $translate("global.InitialExtent"); }, callback: function () { viewer.zoom({ scale: viewer.initialScale, center: viewer.initialCenter }); //viewer.zoomToExtent({ bounds: viewer.initialExtent.bounds }); } }, { name: "ZoomOut", content: "", title: function () { return $translate("global.ZoomOut"); }, callback: function () { viewer.zoom({ scale: viewer.scale * 2 }); } }, { name: "ZoomIn", content: "", title: function () { return $translate("global.ZoomIn"); }, callback: function () { viewer.zoom({ scale: viewer.scale / 2 }); } }, { name: "SelectPolygonMode", content: '', callback: function () { $(viewer.element).gisviewer("digitizePolygon", function (arg) { $(viewer.element).gisviewer("getLayerTree", function (tree) { var layers = tree.where(function (x) { return x.Type === "L" && x.IsVisible && x.IsSelectable; }); $(viewer.element).gisviewer("setSelection", { geom: arg.wkt, layers: layers, multi: true, zoomToSelection: false }); }); }); } }]); return Promise.resolve(bs); }; this.initInfo = function (infoManager) { viewer .on("start-copy-geom", function (e, arg) { copyOptions = { info: "global.CopyGeometry", cancel: function () { arg.cancel(); }, extra: { toggleUi: true } }; return infoManager.push(copyOptions) .then($timeout); }) .on("end-copy-geom", function () { infoManager.submit() .then($timeout); }) .on("start-digitize", function (e, arg) { //console.log("VBS.START_DIGITIZE", { evt: e, arg: arg }); var info; switch (arg.type) { case "Point": info = "global.DigitizePoint"; break; case "LineString": info = "global.DigitizeLine"; break; case "Polygon": info = "global.DigitizePolygon"; break; case "Circle": info = "global.DigitizeCircle"; break; case "Square": info = "global.DigitizeSquare"; break; case "Rectangle": info = "global.DigitizeRectangle"; break; default: info = "global.DigitizeStartPoint"; } digitizingOptions = { info: info, cancel: function () { viewer.cancelDigitizing(); }, extra: { toggleUi: true } }; if (arg.infoMessageOptions) { digitizingOptions = $.extend(digitizingOptions, arg.infoMessageOptions); } return infoManager.push(digitizingOptions) .then(function (msg) { digitizingMessage = msg; return $timeout(); }); }) .on("digitizing", function (e, arg) { if (arg.geom == null) { return; } var geom = arg.geom.geoJson; //console.log("VBS.DIGITIZING", { arg: arg }); if (digitizingMessage != null && (geom.type === "LineString" && geom.coordinates.length > 1) || (geom.type === "Polygon" && geom.coordinates[0].length > 2)) { digitizingMessage.submit = function () { viewer.finishDigitizing(); }; $timeout(); } }) .on("end-digitize", function () { //console.log("VBS.END_DIGITIZE"); return infoManager.submit() .then($timeout); }); return Promise.resolve(bs); }; this.initToolbar = function (toolbarManager) { return toolbarManager .buildTree(["ZoomIn", "ZoomOut", "InitialExtent"]) .then(function () { return bs; }); }; this.initCss = function () { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); return Promise.resolve(bs); }; this.initElements = function () { var infoContainer = $('
    ') .appendTo(viewer.element); $compile(infoContainer)($scope); if (config.showZoomToolbar) { $('.gis-zoom-toolbar').show(); } return Promise.resolve(bs); }; this.initMap = function () { return new Promise( function (resolve, reject) { viewer.on("map-load", resolve); viewer.on("map-load-error", function(e, arg) { reject(arg); }); }) .then(function () { return bs; }); }; } return Bootstrapper; })("viewer"); var aansluitingen = aansluitingen || {}; aansluitingen.module = (function (moduleName) { "use strict"; return angular.module("geoit.aansluitingen", ["geoit.basic", "geoit.projects", "geoit.notities", "geoit.dwf", "geoit.schetsen"]) //config .factory("aansluitingenConfig", ["config", function (config) { var aansluitingenBaseUrl = config.baseUrl + "/aansluitingen/Handlers/Aansluitingen/"; var previewsUrl = config.baseUrl + "/content/modules/aansluitingen/images/stuk_previews/{code}.png"; return { version: config.version, baseUrl: config.baseUrl, securityEnabled: config.securityEnabled, user: config.user, userRoles: config.roles, aansluitingenBaseUrl: aansluitingenBaseUrl, previewsUrl: previewsUrl, niscode: config.niscode, taalcode: config.taalcode, clientSession: config.clientSession, layers: { aansluitingen: "aansluitingen", aansluitingStukken: "aansluiting_stukken", aansluitingLines: "aansluiting_lines", aansluitingEigenProfielen: "aansluiting_eigen_profielen", aansluitingRioolDocumenten: "aansluitingen_riolering", aansluitingFunderingDocumenten: "aansluitingen_fundering", aansluitingTssDocumenten: "aansluitingen_tss", aansluitingOmhullingDocumenten: "aansluitingen_omhulling", aansluitingBijlagen: "aansluitingen_bijlagen", dummyPoints: "dummy_points", constructionPoints: "schetsen_punt", projectLogos: "project_logos" } }; }]) //module .service("aansluitingenModuleService", ["aansluitingenConfig", "$http", "$translate", "projectManager", "aansluitingenService", "aansluitingenDiameterService", "aansluitingenMateriaalService", "aansluitingenBestemmingService", "aansluitingenCategorieService", "aansluitingenSoortService", "securityManager", aansluitingen.ModuleService]) .directive("aansluitingenDirective", aansluitingen.ModuleDirective) .directive("aansluitingenDiameterControlDirective", aansluitingen.DiameterControlDirective) .directive("straatSelector", aansluitingen.StraatSelectorDirective) //aansluitingen .service("aansluitingenService", aansluitingen.AansluitingenService) //aansluiting .service("aansluitingenAansluitingService", aansluitingen.AansluitingService) .controller("aansluitingenAansluitingContainerController", aansluitingen.AansluitingContainerController) .directive("aansluitingFormDirective", aansluitingen.AansluitingFormDirective) //aansluiting-stuk .service("aansluitingenAansluitingStukService", aansluitingen.AansluitingStukService) .controller("aansluitingenAansluitingStukContainerController", aansluitingen.AansluitingStukContainerController) .directive("aansluitingStukListDirective", aansluitingen.AansluitingStukListDirective) .directive("aansluitingStukFormDirective", aansluitingen.AansluitingStukFormDirective) //aansluitingprintsetting .service("aansluitingenAansluitingPrintSettingService", aansluitingen.AansluitingPrintSettingService) .controller("aansluitingenAansluitingPrintSettingContainerController", aansluitingen.AansluitingPrintSettingContainerController) .directive("aansluitingPrintSettingFormDirective", aansluitingen.AansluitingPrintSettingFormDirective) .directive("aansluitingPrintSettingContainerDirective", aansluitingen.AansluitingPrintSettingContainerDirective) //bestemming .service("aansluitingenBestemmingService", aansluitingen.BestemmingService) //categorie .service("aansluitingenCategorieService", aansluitingen.CategorieService) //diameter .service("aansluitingenDiameterService", aansluitingen.DiameterService) //dummypoint .service("aansluitingenDummyPointService", aansluitingen.DummyPointService) //materiaal .service("aansluitingenMateriaalService", aansluitingen.MateriaalService) //overview .service("aansluitingenOverviewService", aansluitingen.OverviewService) .directive("aansluitingOverviewDirective", aansluitingen.AansluitingOverviewDirective) .controller("aansluitingenOverviewController", aansluitingen.OverviewController) //project .provider("projectService", function () { this.$get = ["aansluitingenConfig", "$http", function (config, $http) { return new aansluitingen.ProjectService(config, $http); }]; }) .service("projectManager", ["projectService", projects.ProjectManager]) .service("projectGisManager", ["aansluitingenConfig", "$translate", "gisViewerManager", "layerTree", "geoHelper", "geoHandler", "aansluitingenService", function (config, $translate, gisViewer, layerTree, geoHelper, geoHandler, aansluitingenService) { return new aansluitingen.ProjectGisManager({ layerNames: [config.layers.aansluitingen, config.layers.aansluitingLines, config.layers.aansluitingStukken, config.layers.dummyPoints] }, $translate, gisViewer, layerTree, geoHelper, geoHandler, aansluitingenService); }]) .controller("projectController", ["config", "aansluitingenConfig", "projectService", "projectManager", "projectGisManager", "commandBag", "$timeout", "$translate", "aansluitingenModuleService", "crabService", "aansluitingenService", "securityUserService", "gisViewerManager", "panelManager", "featureInfoBag", "printManager", aansluitingen.ProjectController]) .directive("aansluitingenProjectSelectDirective", aansluitingen.ProjectSelectDirective) //soort .service("aansluitingenSoortService", aansluitingen.SoortService) //stuk .service("aansluitingenStukService", aansluitingen.StukService) .controller("aansluitingenStukContainerController", aansluitingen.StukContainerController) // security .service("projectSecurityService", ["projectSecurityServiceFactory", "aansluitingenConfig", "aansluitingenService", function (factory, config, aansluitingenService) { var securityConfig = $.extend({}, config); securityConfig.saveProjectUsers = function (o) { return aansluitingenService.saveProjectUsers(o); }; securityConfig.getProjectUsers = function (project) { return aansluitingenService.getProjectUsers({ projectId: project.id }); }; return factory.create(securityConfig, moduleName); }]) .service("projectSecurityManager", ["projectSecurityManagerFactory", function (factory) { return factory.create(moduleName); }]) .controller("projectSecurityController", ["projectSecurityManager", function (manager) { return new projects.ProjectSecurityController(manager); }]) //utils .service('printManager', aansluitingen.PrintManager) // module bootstrapper .service(moduleName + "NgBootstrapper", ["projectManager", "projectGisManager", "gisViewerManager", "projectSecurityManager", "securityUserManager", "indexService", "aansluitingenModuleService", "aansluitingenOverviewService", "commandBag", "toolbarService", "infoContainerManager", "locationHashHelper", "printService", "$translate", "$timeout", "$compile", "$rootScope", function (projectManager, projectGisManager, gisViewer, projectSecurityManager, userManager, indexService, aansluitingenModuleService, aansluitingenOverviewService, commandBag, toolbarService, infoContainerManager, locationHashHelper, printService, $translate, $timeout, $compile, $rootScope) { var bootstrapper; this.init = function (config) { console.log(moduleName + '.init'); bootstrapper = new aansluitingen.Bootstrapper(config, projectManager, infoContainerManager, $timeout, $rootScope); return Promise.resolve(bootstrapper) // css .then(function (bs) { return bs.initCss(); }) // language //.then(function (bs) { // return bs.initLanguage(aansluitingenModuleService); //}) // project data .then(function (bs) { return bs.initProjectData(indexService, aansluitingenModuleService, aansluitingenOverviewService); }) // project gis .then(function (bs) { return bs.initProjectGis(gisViewer, projectGisManager); }) // security .then(function (bs) { return bs.initSecurity(projectSecurityManager, userManager); }) // commands .then(function (bs) { return bs.initCommands(commandBag, $translate); }) // print .then(function (bs) { return bs.initPrint(printService); }); }; // o: { projectId || projectCode } this.load = function () { console.log(moduleName + '.load'); return Promise.resolve(bootstrapper) // toolbar .then(function (bs) { return bs.initToolbar(toolbarService); }) // elements .then(function (bs) { return bs.initElements(commandBag, projectManager, $compile); }) // panels - navigation .then(function (bs) { return bs.initPanels(commandBag); }) // hash events .then(function (bs) { return bs.initHashEvents(locationHashHelper, commandBag); }) // aansluitingenModuleService .then(function (bs) { return aansluitingenModuleService.init() .then(function () { return bs; }); }); }; } ]) // load app .run(["config", moduleName + "NgBootstrapper", "globalNgBootstrapper", "basicviewerNgBootstrapper", "homeNgBootstrapper", "notitiesNgBootstrapper", "dwfNgBootstrapper", "schetsenNgBootstrapper", "viewerNgBootstrapper", "menuNgBootstrapper", "securityManager", "projectManager", "locationHashHelper", "$timeout", "$rootScope", "gisViewerManager", function (config, bs, globalBs, basicviewerBs, homeBs, notitiesBs, dwfBs, schetsenBs, viewerBs, menuBs, securityManager, projectManager, locationHashHelper, $timeout, $rootScope, gisViewerManager) { if (config.errorMessage) { return; } var overlay = $('body').spinnerOverlay(); var complete = function (type) { console.log('APP.' + type); overlay.remove(); } // set niscode on rootScope $rootScope.niscode = config.niscode; Promise.resolve() // 1. init global .then(function () { return globalBs.init(config); }) // 2. init viewer .then(function () { return viewerBs.init(config); }) // init navigation .then(function() { return menuBs.init(config); }) // 3. init basicviewer .then(function () { return basicviewerBs.init(); }) // 4. init home BS .then(function () { return homeBs.init({ baseUrl: config.baseUrl, application: config.application }); }) // 5. init notities BS .then(function () { return notitiesBs .init({ baseUrl: config.baseUrl, version: config.version, enableProjects: true, canEdit: !config.securityEnabled || securityManager.hasRole("global", "notities_editeren"), autoLoad: false }); }) // 6. init dwf BS .then(function () { return dwfBs .init({ baseUrl: config.baseUrl, version: config.version, enableProjects: true, canEdit: !config.securityEnabled || securityManager.hasRole("global", "dwf_editeren"), autoLoad: false }); }) // init schetsen .then(function () { return schetsenBs .init({ baseUrl: config.baseUrl, version: config.version, enableProjects: true, //canEdit: !config.securityEnabled || securityManager.hasRole("global", "schetsen_editeren"), autoLoad: false }); }) // 4. init BS .then(function () { return bs .init({ baseUrl: config.baseUrl, version: config.version }); }) // 8. load global .then(function () { return globalBs.load(); }) // 9. load viewer .then(function () { return viewerBs.load(); }) // load navigation .then(function() { return menuBs.load(); }) // 10. load basicviewer .then(function () { return basicviewerBs.load(); }) // load home .then(function () { return homeBs.load({ baseUrl: config.baseUrl, application: config.application }); }) // 13. load notities data .then(function () { return notitiesBs.load(); }) // 14. load dwf data .then(function () { return dwfBs.load(); }) // load schetsen .then(function () { return schetsenBs.load(); }) // 11. load aansluitingen .then(function () { return bs.load(); }) // activate project .then(function () { return projectManager.activateByQuery({ id: config.userLastProjectId }); }) // hash events .then(function () { //console.log("EXECUTING HASH EVENTS", { hashParams: H.query() }); locationHashHelper.executeHashchangeEvents(H.query()); }) .then(function () { //nodig voor schetsen return gisViewerManager.refreshMap(); }) // 17. trigger view update .then(function () { complete('LOADED'); return $timeout(); }).catch(function (err) { complete('FAILED'); G.handleError(err); }).then(function () { $rootScope.completeAppLoaded(); }); } ]); })("aansluitingen"); var basicviewer = basicviewer || {}; basicviewer.module = (function(moduleName) { "use strict"; return angular .module("geoit.basic", [ "geoit.global", "geoit.errors", "geoit.panels", "geoit.viewer", "geoit.measure", "geoit.redlining", "geoit.schetsen", "geoit.commands", "geoit.menu", "geoit.gislegend", "geoit.logon", "geoit.loadend", "geoit.beheer", "geoit.home", "geoit.print", //"geoit.projects", "geoit.featureInfo", "geoit.onlineState", //"geoit.notities", "geoit.crab", "geoit.mylocation", "geoit.dwf", "geoit.files", "geoit.security" ]) // toolbar .service("toolbarService", commands.CommandManager) .controller("toolbarController", ["commandBag", "toolbarService", "$timeout", commands.CommandsController]) .directive("toolbar", commands.ToolbarDirectiveFactory.create()) // context menu .service("contextMenuService", commands.CommandManager) .controller("contextMenuController", ["commandBag", "contextMenuService", "$timeout", commands.CommandsController]) .directive("contextMenu", commands.ContextMenuDirectiveFactory.create()) // bootstrapper .service("basicviewerNgBootstrapper", ["config", "gisViewerManager", "locationHashHelper", function (config, gisViewerManager, locationHashHelper) { var bootstrapper; this.init = function () { console.log(moduleName + '.init'); bootstrapper = new basicviewer.Bootstrapper({}, gisViewerManager); return Promise.resolve(bootstrapper); } this.load = function () { console.log(moduleName + '.load'); var pm = new PanelManager($(".content-container")); var nm = NavigationManager; return Promise.resolve(bootstrapper) .then(function (bs) { return bs.initHashEvents(locationHashHelper); }) .then(function (bs) { return bs.initPanels(pm, nm); }); }; } ]); })("basicviewer"); var beheer = beheer || {}; beheer.module = (function (moduleName) { "use strict"; return angular.module("geoit.beheer", ["geoit.basic", "geoit.commands", "geoit.loadend", "geoit.errors", "geoit.home"]) .controller("beheerController", beheer.BeheerController) .directive("translationsDirective", beheer.TranslationsDirective) .directive("settingsDirective", beheer.SettingsDirective) .directive("securityDirective", beheer.SecurityDirective) .directive("connectionstringsDirective", beheer.ConnectionstringsDirective) .directive("userFormDirective", beheer.UserFormDirective) .directive("organizationFormDirective", beheer.OrganizationFormDirective) .directive("roleListDirective", beheer.RoleListDirective) .directive("codepatchesDirective", beheer.CodepatchesDirective) .directive("beheerDirective", beheer.BeheerDirective) .service("beheerService", beheer.BeheerService) .run(["config", "toolbarService", "homeNgBootstrapper", function (config, tb, homeBs) { if (config.application === moduleName) { var bootstrapper = { initToolbar: function (toolbarService) { var bs = this; return toolbarService.buildTree([ "Home", "security.User", "separator", "security", "settings", "connectionstrings", "translations", "codepatches" ]) .then(function () { return bs; }); } }; var load = function (config) { console.log(moduleName + '.load'); return Promise.resolve(bootstrapper) .then(function (bs) { return bs.initToolbar(tb); }); } Promise.resolve() .then(function () { return homeBs.init(config); }) .then(function () { return homeBs.load(config); }) .then(function () { return load(config); }); } }]) .run(["config", function (config) { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); }]); })("beheer"); var bomen = bomen || {}; bomen.module = angular.module("geoit.bomen", ["geoit.global", "geoit.basic"]) //config .factory("bomenConfig", ["config", function (config) { var layerName = "trees"; return angular.merge({}, config, { layerName: layerName, url: "Handlers/BoomHandler.aspx?layerName=" + layerName }); }]) .service("soortService", bomen.SoortService) .service("boomService", bomen.BoomService) .controller("boomController", bomen.BoomController) .directive("bomenDirective", bomen.BomenDirective); var burgerloket = burgerloket || {}; burgerloket.module = (function (moduleName) { "use strict"; return angular.module("geoit.burgerloket", ["geoit.basic"]) .directive("burgerloketDirective", burgerloket.BurgerloketDirective) .run(["config", "gisViewerManager", "toolbarService", function (config, vm, toolbarService) { vm.on("map-load", function () { toolbarService.buildTree([ "Print", "measure.Measure", "crab.SearchAddress", "TrackMyLocation", "featureinfo.ShowSelection", "gislegend.Legend" ]); }); }]) // load app .run(["config", "globalNgBootstrapper", "basicviewerNgBootstrapper", "homeNgBootstrapper", "viewerNgBootstrapper", "menuNgBootstrapper", "locationHashHelper", "$timeout", "$rootScope", function (config, globalBs, basicviewerBs, homeBs, viewerBs, menuBs, locationHashHelper, $timeout, $rootScope) { if (config.errorMessage) { return; } var overlay = $('body').spinnerOverlay(); var complete = function (type) { console.log('APP.' + type); overlay.remove(); } // set niscode on rootScope $rootScope.niscode = config.niscode; Promise.resolve() // 1. init global .then(function () { return globalBs.init(config); }) // 2. init viewer .then(function () { return viewerBs.init(config); }) // init navigation .then(function () { return menuBs.init(config); }) // 3. init basicviewer .then(function () { return basicviewerBs.init(); }) // init home BS .then(function () { return homeBs.init({ baseUrl: config.baseUrl, application: config.application }); }) // 8. load global .then(function () { return globalBs.load(); }) // 10. load viewer .then(function () { return viewerBs.load(); }) // load navigation .then(function () { return menuBs.load(); }) // load basicviewer .then(function () { return basicviewerBs.load(); }) // load home .then(function () { return homeBs.load({ baseUrl: config.baseUrl, application: config.application }); }) .then(function () { //console.log("EXECUTING HASH EVENTS", { hashParams: H.query() }); locationHashHelper.executeHashchangeEvents(H.query()); }) // 17. trigger view update .then(function () { complete('LOADED'); return $timeout(); }).catch(function (err) { complete('FAILED'); G.handleError(err); }).then(function () { $rootScope.completeAppLoaded(); }); } ]); })("burgerloket"); var crab = crab || {}; crab.module = (function (moduleName) { "use strict"; return angular.module("geoit.crab", []) .service("crabService", crab.CrabService) .controller("crabController", crab.CrabController) .directive("crabDirective", crab.CrabDirective) .run(["commandBag","$translate",function(commandBag, $translate) { commandBag.add([{ name: "crab.SearchAddress", content: '', title: function () { return $translate("crab.SearchAddress"); } }]); }]) .run(["config", function (config) { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); }]); })("crab"); var dwf = dwf || {}; dwf.module = (function (moduleName) { "use strict"; return angular.module("geoit.dwf", ["geoit.global", "geoit.files", "geoit.viewer", "geoit.projects"]) .factory("dwfConfig", ["config", function (config) { var baseUrl = config.baseUrl + "/GeoRest/Dwf"; return { clientSession: config.clientSession, sessionId: config.sessionId, mapName: config.mapName, niscode: config.niscode, url: baseUrl, setProjectUrl: baseUrl + "/SetProject", saveUrl: baseUrl + "/SaveDwfFiles", deleteUrl: baseUrl + "/Delete" }; }]) .service("dwfService", ["dwfConfig", "fileHelper", "$http", dwf.DwfService]) .service("dwfManager", ["dwfService", dwf.DwfManager]) .service("dwfGisManager", ["gisViewerManager", "layerTree", dwf.DwfGisManager]) .controller("dwfController", ["config", "dwfManager", "fileHelper", "$timeout", dwf.DwfController]) .directive("dwfDirective", ["config", dwf.DwfDirective]) .component("dwfList", common.entityListComponent("Content/modules/" + moduleName + "/dwf-list.html")) // module bootstrapper .service("dwfNgBootstrapper", ["dwfManager", "dwfGisManager", "projectManager", "commandBag", "$translate", "$timeout", function DwfBootstrapper(dwfManager, dwfGisManager, projectManager, commandBag, $translate, $timeout) { var bootstrapper; this.init = function (config) { console.log(moduleName + '.init'); bootstrapper = new dwf.Bootstrapper(config, dwfManager, $timeout); return Promise.resolve(bootstrapper) // css .then(function (bs) { return bs.initCss(); }) // commands .then(function (bs) { return bs.initCommands(commandBag, $translate); }) // gis .then(function (bs) { return bs.initDwfGis(dwfGisManager, projectManager); }) // projects .then(function (bs) { if (config.enableProjects) { return bs.initProjects(projectManager, dwfGisManager); } return bs; }); }; this.load = function () { console.log(moduleName + '.load'); return Promise.resolve(bootstrapper) // elements .then(function (bs) { return bs.initElements(commandBag); }) // projects .then(function (bs) { if (config.enableProjects) { return bs; } return bs.loadProject(null); }); }; }]); })("dwf"); var errors = errors || {}; errors.module = (function (moduleName) { "use strict"; return angular.module("geoit.errors", ["pascalprecht.translate"]) .provider("errorService", function() { this.$get = function ($injector) { var sv = $injector.instantiate(errors.ErrorService); return sv; }; }) .directive("connectionToolbar", errors.ConnectionToolbarDirective) .run(["errorService", function (errorService) { //required for initialisation }]) .run(["config", function (config) { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); }]); })("errors"); var evacuatie = evacuatie || {}; evacuatie.module = (function (moduleName) { "use strict"; return angular.module("geoit.evacuatie", [ "geoit.basic", "geoit.projects", "geoit.vectorfeatures", "geoit.pictures", "geoit.dwf" ]) // config .factory("projectConfig", ["$translate", function ($translate) { var projectConfig = { moduleName: 'Evacuatie' }; return projectConfig; }]) .factory("picturesConfig", ["picturesConfigBase", function (picturesConfig) { picturesConfig.module = 'evacuatie'; picturesConfig.categoryUrl += '&module=evacuatie'; picturesConfig.pictureUrl += '&module=evacuatie'; return picturesConfig; }]) .factory("gislegendConfig", ["gislegendConfigBase", function (config) { config.templates = ["burgerloket-legend"]; return config; }]) .factory("evacuatieConfig", ["config", "$translate", function (config, $translate) { var evacuatieUrl = config.baseUrl + "/Handlers/EvacuatieHandler.aspx"; var group = { Code: moduleName, Title: "Evacuatie" }; $translate("evacuatie.Signalling") .then(function (translatedGroup) { group.Title = translatedGroup; }); var submitProjectUrl = Q.query("submit_project_url"); var returnValue = { version: config.version, baseUrl: config.baseUrl, securityEnabled: config.securityEnabled, niscode: config.niscode, user: config.user, userRoles: config.roles, projectenTitle: config.projectenTitle, evacuatieTitle: config.evacuatieTitle, symbolUrl: evacuatieUrl + "?type=symbol", categoryUrl: evacuatieUrl + "?type=category", projectUrl: evacuatieUrl + "?type=project", getProjectUsersUrl: evacuatieUrl + "?type=project/GetProjectUsers&projectId={projectId}", saveProjectUsersUrl: evacuatieUrl + "?type=project/SaveProjectUsers&projectId={projectId}", group: group, submitProjectUrl: submitProjectUrl, }; EventHandler.injectInto(returnValue); return returnValue }]) // Hotkeys .service("hotkeyService", function () { this.on = function (keys, callback) { return hotkeys(keys, callback); }; }) // Backup .service("evacuatieBackupManager", evacuatie.BackupManager) // category .service("evacuatieCategoryService", ["evacuatieConfig", "$http", "$translate", function (config, $http) { return new evacuatie.CategoryService({ niscode: config.niscode, baseUrl: config.baseUrl, url: config.categoryUrl }, $http); }]) // security .service("projectSecurityService", ["projectSecurityServiceFactory", "evacuatieConfig", function (factory, config) { return factory.create(config, moduleName); }]) .service("projectSecurityManager", ["projectSecurityManagerFactory", function (factory) { return factory.create(moduleName); }]) // project .provider("projectService", function () { this.$get = ["evacuatieConfig", "imageHelper", "featureHelper", "$http", "$translate", function (config, imageHelper, featureHelper, $http, $translate) { return new evacuatie.ProjectService({ niscode: config.niscode, baseUrl: config.baseUrl, url: config.projectUrl }, imageHelper, featureHelper, $http, $translate); }]; }) .service("projectManager", ["projectService", "gisdocumentConfig", evacuatie.ProjectManager]) .service("projectGisManager", ["evacuatieConfig", "gisViewerManager", "gisVectorManager", "geoHelper", function (config, gisViewer, vectorManager, geoHelper) { return new evacuatie.ProjectGisManager({ group: config.group }, gisViewer, vectorManager, geoHelper); }]) .controller("projectController", ["config", "projectManager", "projectSecurityManager", "fileHelper", "$timeout", "$translate", evacuatie.ProjectController]) .component("projectFilter", evacuatie.projectFilterComponent("Content/modules/" + moduleName + "/project/project-filter.html")) .component("projectList", projects.projectListComponent("Content/modules/" + moduleName + "/project/project-list.html")) .component("projectForm", evacuatie.projectFormComponent("Content/modules/" + moduleName + "/project/project-form.html")) .component("projectFormVlario", evacuatie.projectFormComponent("Content/modules/" + moduleName + "/project/project-form-vlario.html")) .component("projectAdmin", evacuatie.projectFormComponent("Content/modules/" + moduleName + "/project/project-admin.html")) .component("projectButtons", evacuatie.projectButtonsComponent("Content/modules/" + moduleName + "/project/project-buttons.html")) // features .service("evacuatieFeatureManager", ["featureManagerFactory", function (factory) { return factory.create(); }]) .service("evacuatieFeatureStyleManager", ["featureStyleManagerFactory", function (factory) { return factory.create(); }]) .service("evacuatieFeatureGisManager", ["featureGisManagerFactory", function (factory) { return factory.create(); }]) .service("evacuatieFeatureHtmlManager", ["featureHtmlManagerFactory", function (factory) { return factory.create(); }]) .service("evacuatieFeatureFabricManager", ["featureFabricManagerFactory", function (factory) { return factory.create($("#fabric-canvas")); }]) .controller("evacuatieFeatureController", ["evacuatieFeatureManager", "featureHelper", vectorfeatures.FeatureController]) .controller("evacuatieFeatureStyleController", ["evacuatieFeatureStyleManager", vectorfeatures.FeatureStyleController]) .controller("vectorfeaturesFeatureHtmlController", ["evacuatieFeatureHtmlManager", vectorfeatures.FeatureHtmlController]) .component("evacuatieFeatureList", vectorfeatures.featureListComponent("Content/modules/" + moduleName + "/feature/feature-list.html")) .component("evacuatieFeatureStyling", vectorfeatures.stylingComponent("Content/modules/" + moduleName + "/feature/feature-styling.html")) .component("evacuatieFeatureGeometry", vectorfeatures.geometryComponent("Content/modules/" + moduleName + "/feature/feature-geometry.html")) .component("evacuatieGeomSelector", viewer.geometrySelectorComponent("Content/modules/" + moduleName + "/feature/geom-selector.html")) .component("evacuatieAdvancedGeomSelector", viewer.geometrySelectorComponent("Content/modules/" + moduleName + "/feature/advanced-geom-selector.html")) // symbols .component("evacuatieSymbolList", pictures.pictureListComponent("Content/modules/" + moduleName + "/symbol/symbol-list.html")) // evacuatie .controller("evacuatieController", ["projectManager", "evacuatieFeatureManager", "evacuatieBackupManager", "featureHelper", "evacuatieFeatureHtmlManager", "evacuatieFeatureFabricManager", "imageHelper", "gisViewerManager", "$timeout", "evacuatieConfig", evacuatie.EvacuatieController]) .component("evacuatieButtons", evacuatie.buttonsComponent("Content/modules/" + moduleName + "/evacuatie-buttons.html")) .directive("evacuatieDirective", evacuatie.EvacuatieDirective) // module bootstrapper .service("evacuatieNgBootstrapper", ["evacuatieConfig", "evacuatieCategoryService", "projectManager", "evacuatieFeatureManager", "projectGisManager", "evacuatieFeatureGisManager", "evacuatieFeatureStyleManager", "evacuatieFeatureHtmlManager", "evacuatieFeatureFabricManager", "featureHelper", "evacuatieBackupManager", "gisSnappingManager", "gisViewerManager", "projectSecurityManager", "securityUserManager", "indexService", "printService", "hotkeyService", "pictureService", "commandBag", "toolbarService", "infoContainerManager", "onlineStateService", "locationHashHelper", "$translate", "$timeout", "$compile", "$rootScope", "$http", function (evacuatieConfig, categoryService, projectManager, featureManager, projectGisManager, featureGisManager, featureStyleManager, featureHtmlManager, featureFabricManager, featureHelper, backupManager, snappingManager, gisViewer, projectSecurityManager, userManager, indexService, printService, hotkeyService, pictureService, commandBag, toolbarService, infoContainerManager, onlineStateService, locationHashHelper, $translate, $timeout, $compile, $rootScope, $http) { var bootstrapper; this.init = function (config) { bootstrapper = new evacuatie.Bootstrapper(config, evacuatieConfig, categoryService, projectManager, infoContainerManager, $timeout, $rootScope, $http); return Promise.resolve(bootstrapper) // css .then(function (bs) { return bs.initCss(); }) // project data .then(function (bs) { return bs.initProjectData(indexService); }) // feature data .then(function (bs) { return bs.initFeatureData(featureManager, featureHelper, projectSecurityManager); }) // backup .then(function (bs) { return bs.initBackup(featureManager, backupManager); }) // feature style .then(function (bs) { return bs.initFeatureStyle(featureStyleManager, featureManager, featureHelper); }) // project gis .then(function (bs) { return bs.initProjectGis(projectGisManager, snappingManager, gisViewer); }) // security .then(function (bs) { return bs.initSecurity(projectSecurityManager, userManager); }) // feature gis .then(function (bs) { return bs.initFeatureGis(featureGisManager, featureManager, projectGisManager, snappingManager, gisViewer, featureHelper); }) // feature html .then(function (bs) { return bs.initFeatureHtml(featureHtmlManager, featureManager, featureHelper, featureGisManager, gisViewer); }) // pictures -> droppable viewer .then(function (bs) { return bs.initDroppableViewer(gisViewer, featureManager, pictureService); }) // commands .then(function (bs) { return bs.initCommands(commandBag, $translate); }) // print .then(function (bs) { return bs.initPrint(printService); }) // shortcuts .then(function (bs) { return bs.initShortCuts(hotkeyService, featureManager, featureHelper, gisViewer); }); }; //this.loadGipodConfig = function () { // return Promise.resolve(bootstrapper) // .then(function (bs) { // return bs.initGipodConfig(); // }); //} this.load = function () { return Promise.resolve(bootstrapper) // toolbar .then(function (bs) { return bs.initToolbar(toolbarService); }) .then(function (bs) { return bs.initOnlineState(onlineStateService); }) // elements .then(function (bs) { return bs.initElements(commandBag, featureManager, $compile); }) // panels - navigation .then(function (bs) { return bs.initPanels(commandBag, backupManager); }) // feature fabric .then(function (bs) { return bs.initFeatureFabric(featureFabricManager, featureManager, featureHelper, featureGisManager, gisViewer); }) // hash events .then(function (bs) { return bs.initHashEvents(locationHashHelper, commandBag); }); }; } ]) // load app .run(["config", "evacuatieConfig", "evacuatieNgBootstrapper", "globalNgBootstrapper", "basicviewerNgBootstrapper", "homeNgBootstrapper", "picturesNgBootstrapper", "dwfNgBootstrapper", "viewerNgBootstrapper", "menuNgBootstrapper", "securityManager", "projectManager", "locationHashHelper", "commandBag", "$timeout", "$rootScope", function (config, evacuatieConfig, evacuatieBs, globalBs, basicviewerBs, homeBs, picturesBs, dwfBs, viewerBs, menuBs, securityManager, projectManager, locationHashHelper, commandBag, $timeout, $rootScope) { if (config.errorMessage) { return; } var overlay = $('body').spinnerOverlay(); var complete = function (type) { console.log('APP.' + type); overlay.remove(); } // set niscode on rootScope $rootScope.niscode = config.niscode; //evacuatieConfig.gipodEnabled = securityManager.hasRole('evacuatie_gipod'); evacuatieConfig.layers = { WERKEN: "Werken", HINDER: "Hinder", GRONDWERKEN: "Grondwerken", EVENEMENT_INNAME: "EvenementInname", OMLEIDINGEN: "omleidingen_" }; evacuatieConfig.contactTypeIds = { AANNEMER: 'a55eb0a5-84fb-49f8-83c5-de669e4ae48e', DOSSIER_BEHEERDER: 'aad5e947-f7bf-4592-a84a-f591555b0b8b', AANVRAGER: '88888888-8888-8888-8888-888888888888' }; Promise.resolve() // 1. init global .then(function () { return globalBs.init(config); }) // 2. init viewer .then(function () { return viewerBs.init(config); }) // init navigation .then(function () { return menuBs.init(config); }) // 3. init basicviewer .then(function () { return basicviewerBs.init(); }) // 4. init evacuatie BS .then(function () { return evacuatieBs .init({ baseUrl: config.baseUrl, projectenTitle: config.projectenTitle, evacuatieTitle: config.evacuatieTitle, //gipodEnabled: evacuatieConfig.gipodEnabled, //gipodConfigApi: config.gipodConfigApi, //gipodApiBaseUrl: config.gipodApiBaseUrl, netelandNiscodes: config.netelandNiscodes, canEdit: true,//!config.securityEnabled || securityManager.hasRole(moduleName, "editeren"), version: config.version }); }) // init home BS .then(function () { return homeBs.init({ baseUrl: config.baseUrl, application: config.application }); }) // 5. init pictures BS .then(function () { return picturesBs .init({ baseUrl: config.baseUrl, version: config.version, canEdit: !config.securityEnabled || securityManager.hasRole("global", "pictures_editeren") }); }) // 7. init dwf BS .then(function () { return dwfBs .init({ baseUrl: config.baseUrl, version: config.version, enableProjects: true, canEdit: !config.securityEnabled || securityManager.hasRole("global", "dwf_editeren"), autoLoad: false, activateFirstOnProjectChange: true, zoomToFirstOnProjectChange: true }); }) // 8. load global .then(function () { return globalBs.load(); }) // 10. load viewer .then(function () { return viewerBs.load(); }) // load navigation .then(function () { return menuBs.load(); }) // 9. load basicviewer .then(function () { return basicviewerBs.load(); }) // load home .then(function () { return homeBs.load({ baseUrl: config.baseUrl, application: config.application }); }) // 14. load dwf data .then(function () { return dwfBs.load(); }) // 15. load pictures data .then(function () { return picturesBs.load(); }) // 11. load evacuatie .then(function () { return evacuatieBs.load(); }) // activate project .then(function () { return projectManager.activateByQuery({ id: config.userLastProjectId }); }) // hash events .then(function () { //console.log("EXECUTING HASH EVENTS", { hashParams: H.query() }); locationHashHelper.executeHashchangeEvents(H.query()); }) .then(function () { if (evacuatieConfig.submitProjectUrl) { commandBag.execute(moduleName + ".ShowEvacuatie"); } }) // 17. trigger view update .then(function () { complete('LOADED'); return $timeout(); }).catch(function (err) { complete('FAILED'); G.handleError(err); }).then(function () { $rootScope.completeAppLoaded(); }); } ]); })("evacuatie"); var featureInfo = featureInfo || {}; featureInfo.module = (function (moduleName) { "use strict"; return angular.module("geoit.featureInfo", ["geoit.viewer", "geoit.gisdocumenten"]) //.service("featureInfoManager", ["gisFeatureService", featureinfo.FeatureInfoManager]) .service("featureInfoBag", ["gisFeatureService", featureInfo.FeatureInfoBag]) .directive("featureInfoDirective", featureInfo.FeatureInfoDirective) .run(["config", "commandBag", "featureInfoBag", "$translate", function (config, commandBag, featureInfoBag, $translate) { var myCmd = { name: "featureinfo.ShowSelection", content: '', title: function () { return $translate("global.ShowInfo"); }, active: false, callback: function () { console.log("FID.SHOW", { disabled: featureInfoBag.disabled, listening: featureInfoBag.isListening }); //ignore when disabled if (!featureInfoBag.disabled) { //toggle isListening return (featureInfoBag.isListening ? featureInfoBag.stopListening() : featureInfoBag.startListening()) .then(function () { //call all registered actions in featureBag for current selection return featureInfoBag.execute(); }); } return Promise.resolve(false); } }; //register command commandBag.add([myCmd]); //enable/disable or stop/start listening featureInfoBag.on("change", function (e, arg) { myCmd.active = arg.isActive; if (arg.disabled) { console.log("FIM.DISABLE", { bag: featureInfoBag }); commandBag.disable(commandBag.items.where(function (x) { var toIgnore = "Menu,ChooseLanguage,languages.select-nl,languages.select-fr,gislegend.Legend,TrackMyLocation,crab.SearchAddress,ZoomIn,ZoomOut,InitialExtent".split(","); return !toIgnore.contains(x.name); })); } else { commandBag.enableAll(); } }); }]) .run(["config", function (config) { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); }]); })("featureinfo"); var files = files || {}; files.module = (function (moduleName) { "use strict"; return angular.module("geoit.files", ["ngFileUpload", "ui.sortable"]) .factory("filesConfig", ["config", function (config) { return angular.merge({}, config, { defaultUploadUrl: config.baseUrl + "/Upload/Html5Upload.aspx" }); }]) .service("fileHelper", FileHelper) .service("imageHelper", function () { return new ImageHelper(piexif); }) .controller("fileController", files.FileController) .directive("fileManager", files.FilesDirective) .run(["config", function (config) { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); }]); })("files"); var gipod = gipod || {}; gipod.module = angular.module("geoit.gipod", ["geoit.basic"]) .directive("gipodMeldingListDirective", gipod.GipodMeldingListDirective) .directive("gipodMeldingFormDirective", gipod.GipodMeldingFormDirective) .directive("gipodHandhavingDirective", gipod.GipodHandhavingDirective) .directive("gipodWerkopdrachtFormDirective", gipod.GipodWerkopdrachtFormDirective) .directive("gipodManifestatieFormDirective", gipod.GipodManifestatieFormDirective) .directive("gipodFilterDirective", gipod.GipodFilterDirective) .directive("gipodDirective", gipod.GipodDirective) .directive("gipodDocumentenDirective", gipod.GipodDocumentenDirective) .run(["commandBag", "$translate", function (commandBag, $translate) { commandBag.add([{ name: "ToggleGipodFilter", content: '', title: function () { return $translate("gipod.Filter"); } }]); commandBag.add([{ name: "Gipod.ShowHandhaving", content: '', title: function () { return $translate("gipod.Handhaving"); } }]); }]); var gisdocumenten = gisdocumenten || {}; gisdocumenten.module = (function (moduleName) { "use strict"; return angular.module("geoit.gisdocumenten", ["geoit.global", "geoit.files", "geoit.viewer"]) .factory("gisdocumentConfig", ["config", "securityManager", function (config, securityManager) { return { niscode: config.niscode, gisdocumentUrl: config.baseUrl + "/Handlers/GisDocumentHandler.aspx", canEdit: !config.securityEnabled || securityManager.hasRole("global", "documenten_editeren") }; }]) //online .service("gisdocumentService", gisdocumenten.GisDocumentService) .controller("gisdocumentController", gisdocumenten.GisDocumentController) .directive("gisdocumenten", gisdocumenten.GisDocumentFilesDirective) //offline .service("gisdocumentServiceFactory", gisdocumenten.GisDocumentServiceFactory) .controller("offlineGisdocumentController", gisdocumenten.OfflineGisDocumentController) .directive("offlineGisdocumenten", gisdocumenten.OfflineGisDocumentFilesDirective) //container //.directive("gisdocumentenDirective", gisdocumenten.GisDocumentDirective) //.run(["config", "gisdocumentService", "gisViewerManager", "gisFeatureService", function (config, documentService, viewer, gisFeatureService) { //var layerName = config.gisdocumentLayerName || "gisdocumenten"; //gisFeatureService.on("selection-change", function (e, arg) { // -> select owner feature layer instead of documentLayer //console.log("GDM.SELECTION", { evt: e, arg: arg, layerName: layerName }); //if (arg.selection && arg.selection[layerName] && arg.selection[layerName].length) { // var filter = "{id} IN (" + arg.selection[layerName].join(",") + ")"; // gisFeatureService.getFeatureList({ layerName: layerName, filter: filter }) // .then(function (features) { // var filter = features // .groupBy(function (x) { return x.laag; }) // .toDictionary( // function (x) { return x.key; }, // function (x) { // return "{id} IN (" + x.values.select(function (v) { return v.feature; }).join(",") + ")"; // }); // //console.log("GDM.SELECTION", { features: features, filter: filter }); // //setTimeout(function () { // viewer.setSelectedFeatures({ filter: filter, zoomToSelection: false, initiator: "user" }); // //}, 250); // }); //} //}); //}]) .run(["config", function (config) { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); }]); })("gisdocumenten"); var gislegend = gislegend || {}; gislegend.module = (function (moduleName) { "use strict"; return angular.module("geoit.gislegend", ["geoit.viewer", "geoit.commands"]) .factory("gislegendConfigBase", ["config", function (config) { return { baseUrl: config.baseUrl, version: config.version, //possible templates: default-legend, simple-legend, burgerloket-legend, base-layers-legend, base-layers-buttons templates: config.legendTemplates && config.legendTemplates.any() ? config.legendTemplates : ["default-legend"] }; }]) .factory("gislegendConfig", ["gislegendConfigBase", function (config) { return config; }]) .controller("gislegendController", gislegend.LegendController) .directive("gislegendLegend", gislegend.LegendDirective) .directive("gislegendDirective", gislegend.GisLegendDirective) .run(["commandBag", "$translate", function (commandBag, $translate) { commandBag.add([{ name: moduleName + ".Legend", content: '', title: function () { return $translate("global.Legend"); }//, //active: false }]); }]) .run(["gislegendConfig", function (config) { $.loadCss("Content/modules/" + moduleName + "/" + moduleName + ".css"); _.array(config.templates) .forEach(function (template) { $.loadCss(config.baseUrl + "/Content/modules/gislegend/" + template + ".css"); }); }]); })("gislegend"); var global = global || {}; global.module = (function (moduleName) { "use strict"; function getNgFilters() { return { reverse: function () { return function (items) { if (items) { return items.select().reverse(); } return []; }; }, stripHtml: function () { return function (text) { return String(text).replace(/<[^>]+>/gm, ""); }; }, htmlNewlines: function () { return function (text) { if (!text) { return text; } return text.replace(/\\n/g, "
    "); } }, formatFileSize: function () { return function (bytes) { var thresh = 1024; if (Math.abs(bytes) < thresh) { return bytes + " B"; } var units = ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; var u = -1; do { bytes /= thresh; ++u; } while (Math.abs(bytes) >= thresh && u < units.length - 1); return bytes.toFixed(1) + " " + units[u]; }; }, formatDate: ["dateFilter", "formatConfig", function (dateFilter, formatConfig) { return function (input, format) { return dateFilter(input, formatConfig[format || 'date']); }; }], truncate: function () { return function (s, maxLen) { if (!s) { return s; } return s.trunc(maxLen); } }, invertColor: function () { return function (hex) { return _.color.invert(hex); } }, grayscale: function () { return function (hex, type) { return _.color.grayscale(hex, type); } } }; } return angular.module("geoit.global", ["ngSanitize", "angularMoment", "mp.colorPicker", "ngCookies", "pascalprecht.translate", "geoit.directives", "geoit.languages", "geoit.sitesettings"]) .constant("formatConfig", { date: 'dd-MM-yyyy', dateTime: 'dd-MM-yyyy HH:mm', dateTimeFull: 'dd-MM-yyyy HH:mm:ss' }) // sitesettings .component("fontSizeAdmin", sitesettings.fontSizeComponent("Content/modules/" + moduleName + "/sitesettings/font-size.html")) .filter(getNgFilters()) .service("entityStateService", StateManagerFactory.getEntityStateService) .service("panelHelper", global.PanelHelper) .service("validationFactory", global.ValidationManagerFactory) .service("indexService", global.IndexService) .service("locationHashHelper", global.LocationHashHelper) .service("numberUtils", global.NumberUtils) .controller("configurationController", global.ConfigurationController) .directive("enterKey", global.EnterKey) .directive("escKey", global.EscKey) .directive("inputType", global.InputType) .directive("gAutocomplete", global.GAutocomplete) .directive("includeReplace", global.IncludeReplaceDirective) .directive("thSort", global.ThSort) .directive("fileList", global.FileList) .directive("containerButtons", global.ContainerButtonsDirective) .directive("listButtons", global.ListButtonsDirective) .directive("listButtonRemove", global.ListButtonRemoveDirective) .directive("checkboxButton", global.CheckboxButtonDirective) .directive("entityProgressOverlay", global.EntityProgressOverlayDirective) .directive("datetimepicker", global.DatetimepickerDirective) .directive("tabControl", global.TabControlDirective) .directive("helpInfo", global.HelpInfoDirective) .component("appHeader", global.applicationHeaderComponent("Content/modules/" + moduleName + "/components/application-header.html")) .component("loading", global.LoadingComponent("Content/modules/" + moduleName + "/components/loading.html")) .component("showInMapIcon", global.showInMapIconComponent()) // bootstrapper .service("globalNgBootstrapper", ["indexService", "siteSettingsManager", "commandBag", "$translate", "$http", "$rootScope", function (indexService, siteSettingsManager, commandBag, $translate, $http, $rootScope) { var bootstrapper; this.init = function (config) { console.log(moduleName + '.init'); bootstrapper = new global.Bootstrapper(config, $http, $rootScope); return Promise.resolve(bootstrapper) .then(function (bs) { return bs.initCss(); }) .then(function (bs) { return bs.initScope(); }) //.then(function (bs) { // return bs.initDefaultApp(); //}) .then(function (bs) { return bs.initLanguage(); }) .then(function (bs) { return bs.initFontSize(siteSettingsManager); }) .then(function (bs) { return bs.initCommands(commandBag, $translate); }); }; this.load = function () { console.log(moduleName + '.load'); // nothing (for now...) return Promise.resolve(bootstrapper); }; }]) //.config(["$locationProvider", function ($locationProvider) { // $locationProvider.hashPrefix(""); //}]) .config(["$locationProvider", function ($locationProvider) { $locationProvider.html5Mode({ enabled: true, requireBase: false, rewriteLinks: false }); }]); })("global"); var golfgis = golfgis || {}; golfgis.module = (function (moduleName) { "use strict"; return angular.module("geoit.golfgis", ["geoit.basic"]) .directive("golfgisDirective", golfgis.GolfGisDirective) .run(["config", function (config) { config.projection = "EPSG:28992"; config.proj4Defs = { "EPSG:28992": "+proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889 +k=0.9999079 +x_0=155000 +y_0=463000 +ellps=bessel +towgs84=565.417,50.3319,465.552,-0.398957,0.343988,-1.8774,4.0725 +units=m +no_defs" }; config.emsUrl = "https://api.emsgolf.eu/golfgis/object.php?niscode={niscode}&gis_identifier={id}"; }]) .run(["gisViewerManager", "toolbarService", function (vm, tb) { console.log("GOLFGIS.RUN", { toolbar: tb }); vm.on("map-load", function () { tb.buildTree([ { "Menu": ["Home", "ChooseLanguage", "Logout"] }, "gislegend.Legend", "Print", "TrackMyLocation", "notities.AddNotitie", "measure.Measure", "featureinfo.ShowSelection" ]); }); }]) .run(["config", function (config) { $.loadCss([ config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css", config.baseUrl + "/Handlers/CustomLoader.aspx?file=" + moduleName + "/" + moduleName + ".css" ]); }]); })("golfgis"); var home = home || {}; home.module = (function (moduleName) { "use strict"; return angular .module("geoit.home", ["geoit.basic", "geoit.logon", "geoit.security", "geoit.commands", "geoit.panels", "geoit.manuals"]) .factory("homeConfig", ["config", function () { return { baseUrl: config.baseUrl, application: config.application, version: config.version, niscode: config.niscode, taalcode: config.taalcode, errorMessage: config.errorMessage, authentication: config.authentication, gipodApiBaseUrl: config.gipodApiBaseUrl }; }]) .service("homeManager", home.HomeManager) .controller("homeController", ["homeConfig", "homeManager", home.HomeController]) .directive("homeDirective", ["homeConfig", home.HomeDirective]) // bootstrapper .service("homeNgBootstrapper", ["config", "homeManager", "commandBag", "securityManager", "toolbarService", "$translate", function (appConfig, homeManager, commandBag, securityManager, toolbarService, $translate) { var bootstrapper; this.init = function (config) { console.log(moduleName + '.init'); bootstrapper = new home.Bootstrapper({ baseUrl: config.baseUrl, application: config.application, niscode: config.niscode, version: config.version }, homeManager); return Promise.resolve(bootstrapper) // css .then(function (bs) { return bs.initCss(); }) // commands .then(function (bs) { return bs.initCommands(commandBag, securityManager, $translate); }) // data .then(function (bs) { return bs.initData(appConfig.roles); }); }; this.load = function (config) { console.log(moduleName + '.load'); return Promise.resolve(bootstrapper) // toolbar .then(function (bs) { return bs.initToolbar(toolbarService); }) // panels .then(function (bs) { return bs.initPanels(config.niscode, $translate); }) // elements .then(function (bs) { return bs.initElements(); }); } }]) // start app .run(["homeConfig", "homeNgBootstrapper", "globalNgBootstrapper", "manualsNgBootstrapper", "homeManager", function (config, homeBs, globalBs, manualsBs, homeMgr) { if (config.application !== moduleName) { return; } Promise.resolve() // init .then(function () { return globalBs.init(config); }) .then(function() { return homeBs.init(config); }) .then(function () { return manualsBs.init(); }) // load .then(function () { return globalBs.load(config); }) .then(function () { return homeBs.load(config); }) .then(function () { return manualsBs.load(["basis"].concat(homeMgr.moduleItems.select(function (x) { return x.roleName.substr(7); }))); }); }]); })("home"); var icons = icons || {}; icons.module = (function (moduleName) { "use strict"; return angular .module("geoit.icons", ["geoit.global", "geoit.panels"]) .directive("iconsDirective", icons.IconsDirective) .run(["config", function (config) { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); }]); })("home"); var languages = languages || {}; languages.module = (function (moduleName) { return angular.module("geoit.languages", []) .factory("langConfig", ["config", function (config) { return { baseUrl: config.baseUrl, taalcode: config.taalcode, languages: [ { code: "nl", title: "Nederlands" }, { code: "fr", title: "Français" } ] }; }]) //.service("languagesUserlanguageService", ["config", "$http", function (config, $http) { // this.saveLanguage = function (lang) { // $http.post(config.baseUrl + "/GeoRest/Index/SaveUserLanguage", { clientsession: config.clientSession, lang: lang }); // } //}]) .directive("languagesDirective", languages.LanguageDirective) .run(["langConfig", "commandBag", "indexService", "$translate", "$rootScope", function (config, commandBag, indexService, $translate, $rootScope) { //$rootScope.currentLanguage = $translate.preferredLanguage(config.taalcode || "nl"); var currentLanguage = $translate.preferredLanguage(config.taalcode || "nl"); commandBag.add( [{ name: "ChooseLanguage", content: '{{ $root.currentLanguage }}', title: function () { return $translate("languages.ChooseLanguage"); } }] .concat(config.languages.select(function (lang) { return { name: "languages.select-" + lang.code, content: '' + lang.code + '', title: lang.title, active: currentLanguage === lang.code, callback: function (arg) { arg.context.items .where(function (x) { return x !== arg.cmd && x.name.startsWith("languages.select-"); }) .forEach(function (x) { x.active = false; }); arg.cmd.active = true; $translate.use(lang.code); } }; })) ); //$rootScope.$on("$translateChangeEnd", function (e, arg) { // $rootScope.currentLanguage = arg.language || $rootScope.currentLanguage; // config.taalcode = $rootScope.currentLanguage; // indexService.saveUserLanguage(); //}); }]) .run(["langConfig", function (config) { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); }]); })("languages"); var loadend = loadend || {}; loadend.module = (function () { return angular.module("geoit.loadend", ["geoit.viewer", "geoit.commands"]) //.directive("loadendDirective", loadend.LoadendDirective) .run(["config", "gisViewerManager", "$rootScope", function (config, viewer, $rootScope) { //console.log("LOADEND_MODULE", { config: config, scope: $rootScope, viewer: viewer }); if (config.application === "home") { return; } function emit() { //console.log("LOAD ENDED", { arg: arg }); G.setup.async = null; $rootScope.$emit("application.loadend"); } if (config.sessionId) { viewer.on("map-load", emit); } else { //Beheer: wait till commands are registered setTimeout(emit, 500); } }]); })("loadend"); var logon = logon || {}; logon.module = (function (moduleName) { "use strict"; return angular.module("geoit.logon", ["geoit.basic"]) .directive("logonDirective", logon.LogonDirective) .run(["commandBag", "$translate", function (commandBag, $translate) { commandBag.add([{ name: "Logout", content: '', title: function () { return $translate("global.Logout"); } }]); }]) .run(["config", function (config) { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); }])//toolbar .run(["toolbarService", "langConfig", function (tb, langConfig) { //if (config.application === moduleName) { // setTimeout(function () { // tb.buildTree([ // { "ChooseLanguage": langConfig.languages.select(function (x) { return "languages.select-" + x.code; }) } // ]); // }, 250); //} }]); })("logon"); var manuals = manuals || {}; manuals.module = (function () { "use strict"; return angular.module("geoit.manuals", []) .factory("manualConfig", ["config", function (config) { return { listUrl: config.baseUrl + "/Handlers/ManualHandler.aspx", detailsUrl: config.baseUrl + "/Handlers/ManualHandler.aspx" }; }]) .service("manualService", ["manualConfig", "$http", manuals.ManualService]) .service("manualManager", ["manualService", manuals.ManualManager]) .controller("manualController", ["manualManager", manuals.ManualController]) .service("manualsNgBootstrapper", ["manualManager", function (manualManager) { this.init = function () { return Promise.resolve(); }; this.load = function (modules, lang) { return manualManager.list(modules, lang); }; }]); })("manuals"); var measure = measure || {}; measure.module = (function (moduleName) { "use strict"; return angular.module("geoit.measure", ["geoit.global"]) .directive("measureDirective", measure.MeasureDirective) .run(["commandBag", "$translate", function (commandBag, $translate) { commandBag.add([{ name: "measure.Measure", content: '', title: function () { return $translate("measure.Measure"); } }]); }]) .run(["config", function (config) { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); }]); })("measure"); var menu = menu || {}; menu.module = (function (moduleName) { "use strict"; return angular.module("geoit.menu", []) // module bootstrapper .service(moduleName + "NgBootstrapper", ["locationHashHelper", "panelHelper", function (locationHashHelper, panelHelper) { var bootstrapper; this.init = function (config) { console.log(moduleName + '.init'); bootstrapper = new menu.Bootstrapper(config, panelHelper); return Promise.resolve(bootstrapper); }; this.load = function () { console.log(moduleName + '.load'); return Promise.resolve(bootstrapper) // hash events .then(function (bs) { return bs.initHashEvents(locationHashHelper); }); }; } ]); })("menu"); var messages = messages || {}; messages.module = (function () { "use strict"; return angular.module("geoit.messages", []) .factory("infoManagerFactory", function () { return { create: function () { return new messages.InfoManager(); } }; }); })("messages"); var mylocation = mylocation || {}; mylocation.module = (function () { "use strict"; return angular.module("geoit.mylocation", ["geoit.global"]) .directive("myLocationDirective", mylocation.MyLocationDirective) .run(["commandBag", "$translate", function (commandBag, $translate) { commandBag.add([{ name: "TrackMyLocation", content: '', title: function () { return $translate("global.TrackMyLocation"); }, active: false }]); }]); })("mylocation"); var notities = notities || {}; notities.module = (function (moduleName) { "use strict"; return angular.module("geoit.notities", ["geoit.global", "geoit.viewer", "geoit.projects", "geoit.gisdocumenten"]) .factory("notitiesConfig", ["config", "securityManager", function (config, securityManager) { return angular.merge({}, config, { notitieUrl: config.baseUrl + "/Handlers/NotitiesHandler.aspx?type=notitie", categoryUrl: config.baseUrl + "/Handlers/NotitiesHandler.aspx?type=category", documentUrl: config.baseUrl + "/Handlers/GisDocumentHandler.aspx?action=preview&id={id}&rnd={rnd}&niscode={niscode}", canEdit: !config.securityEnabled || securityManager.hasRole("global", moduleName.toLowerCase() + "_editeren") }); }]) // category .service("notitiesCategoryService", notities.CategoryService) //notitie .provider("notitieService", function () { this.$get = ["notitiesConfig", "$http", function (config, $http) { return new notities.NotitieService(config, $http); }]; }) .service("notitieManager", ["notitieService", notities.NotitieManager]) .service("notitieGisManager", ["config", "gisViewerManager", "layerTree", "geoHelper", "geoHandler", function (config, gisViewer, layerTree, geoHelper, geoHandler) { return new notities.NotitieGisManager({ layerName: config.notitiesLayername, layerNames: config.notitiesLayerNames }, gisViewer, layerTree, geoHelper, geoHandler); }]) // controllers .controller("notitieController", ["config", "notitieManager", "notitieGisManager", "projectManager", "$timeout", "$translate", notities.NotitieController]) .controller("notitieDetailController", ["$timeout", notities.NotitieDetailController]) // components .component("notitieButtons", common.entityButtonsComponent("Content/modules/" + moduleName + "/notitie-buttons.html")) .component("notitieFilter", notities.notitieFilterComponent("Content/modules/" + moduleName + "/notitie/notitie-filter.html")) .component("notitieList", notities.notitieListComponent("Content/modules/" + moduleName + "/notitie/notitie-list.html")) .component("notitieForm", notities.notitieFormComponent("Content/modules/" + moduleName + "/notitie/notitie-form.html")) .component("notitieDetailList", common.entityListComponent("Content/modules/" + moduleName + "/notitiedetail/notitiedetail-list.html")) .component("notitieDetailForm", common.entityFormComponent("Content/modules/" + moduleName + "/notitiedetail/notitiedetail-form.html")) .component("notitieDocuments", notities.entityListComponent("Content/modules/" + moduleName + "/notitiedocument/notitiedocument-container.html")) .component("notitieGeomSelector", viewer.geometrySelectorComponent("Content/modules/" + moduleName + "/gis/geom-selector.html")) //container .directive("notitiesDirective", notities.NotitiesDirective) // module bootstrapper .service("notitiesNgBootstrapper", ["notitieManager", "notitiesCategoryService", "notitieGisManager", "projectManager", "gisFeatureService", "gisViewerManager", "commandBag", "featureInfoBag", "$translate", "$timeout", function NotitieBootstrapper(notitieManager, categoryService, notitieGisManager, projectManager, gisFeatureService, gisViewerManager, commandBag, featureInfoBag, $translate, $timeout) { var bootstrapper; this.init = function (config) { console.log(moduleName + '.init'); bootstrapper = new notities.Bootstrapper(config, categoryService, notitieManager, $translate, $timeout); return Promise.resolve(bootstrapper) // css .then(function (bs) { return bs.initCss(); }) // commands .then(function (bs) { return bs.initCommands(commandBag, gisViewerManager); }) // categories .then(function (bs) { return bs.initCategories(); }) // gis .then(function (bs) { return bs.initNotitieGis(notitieGisManager, gisFeatureService, projectManager); }) // projects .then(function (bs) { if (config.enableProjects) { return bs.initProjects(projectManager, notitieGisManager); } return bs; }) // selection .then(function (bs) { return bs.initFeatureInfo(projectManager, notitieGisManager, featureInfoBag, commandBag); }); }; this.load = function () { console.log(moduleName + '.load'); return Promise.resolve(bootstrapper) // elements .then(function (bs) { return bs.initElements(commandBag); }) // panels .then(function (bs) { var pm = new PanelManager($(".content-container")); return bs.initPanels(pm, commandBag); }) // projects .then(function (bs) { if (config.enableProjects) { return bs; } return bs.loadProject(null); }); }; }]); })("notities"); angular.module("geoit.onlineState", []) .service("onlineStateService", OnlineStateService); var panels = panels || {}; panels.module = (function () { "use strict"; return angular.module("geoit.panels", []) .factory("panelConfig", ["config", function (config) { var panels = {}; return { init: function (o) { if (typeof (o) !== "undefined") { angular.extend(panels, o); } function getDashedName(name) { var directiveKey = name[0]; for (var i = 1; i < name.length; i++) { if (name[i] === name[i].toUpperCase()) { directiveKey += "-"; } directiveKey += name[i]; } return directiveKey.toLowerCase(); } Object.keys(panels).forEach(function (panel) { $("#" + panel).append(panels[panel].select(function (module) { return ('
    ') .replaceAll("{modulename}", module.toLowerCase()) .replaceAll("{module-name}", getDashedName(module)); })); }); }, add: function (panel, module) { if (!(panel in panels)) { panels[panel] = []; } _.array(module).forEach(function (module) { panels[panel].push(module); }); } }; }]) .service("panelManager", panels.PanelManager) .controller("panelController", panels.PanelController) .directive("panelContainer", panels.PanelContainerDirective) .directive("panel", panels.PanelDirective); })("panels"); var pictures = pictures || {}; pictures.module = (function (moduleName) { "use strict"; return angular.module("geoit.pictures", ["geoit.global"]) .factory("picturesConfigBase", ["config", "securityManager", function (config, securityManager) { return { niscode: config.niscode, canEdit: !config.securityEnabled || securityManager.hasRole("global", moduleName.toLowerCase() + "_editeren"), module: 'signalisatie', categoryUrl: config.baseUrl + "/Handlers/PictureHandler.aspx?type=category", pictureUrl: config.baseUrl + "/Handlers/PictureHandler.aspx?type=picture" }; }]) .factory("picturesConfig", ["picturesConfigBase", function (picturesConfig) { return picturesConfig; }]) .service("picturesCategoryService", ["picturesConfig", "$http", function (config, $http) { return new pictures.CategoryService(config, $http); }]) .provider("pictureService",function() { this.$get = ["picturesConfig", "picturesCategoryService", "imageHelper", "$http", function (config, categoryService, imageHelper, $http) { return new pictures.PictureService(config, categoryService, imageHelper, $http); }]; }) .service("pictureManager", ["pictureService", pictures.PictureManager]) .controller("pictureController", ["pictureManager", "imageHelper", pictures.PictureController]) // bootstrapper .service("picturesNgBootstrapper", ["pictureManager", "picturesCategoryService", function PicturesBootstrapper(pictureManager, picCategoryService) { var bootstrapper; this.init = function (config) { bootstrapper = new pictures.Bootstrapper(config, picCategoryService, pictureManager); return Promise.resolve(bootstrapper) // css .then(function (bs) { return bs.initCss(); }) // categories .then(function(bs) { return bs.initCategories(); }); }; this.load = function () { return Promise.resolve(bootstrapper) // picture data .then(function (bs) { return bs.initPictureData(); }); }; }]); })("pictures"); var print = print || {}; print.module = (function (moduleName) { "use strict"; return angular.module("geoit.print", ["geoit.global", "geoit.commands"]) .directive("printDirective", print.PrintDirective) .service("printService", print.PrintService) .run(["commandBag", "$translate", function (commandBag, $translate) { commandBag.add([{ name: "Print", content: '', title: function () { return $translate("global.Legend"); } }]); }]) .run(["config", function (config) { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); }]); })("print"); var raadplegen = raadplegen || {}; raadplegen.module = (function (moduleName) { "use strict"; function ProjectManager() { projects.ProjectManager.apply(this, arguments); } ProjectManager.prototype = Object.create(projects.ProjectManager.prototype, { constructor: { value: ProjectManager } }); return angular.module("geoit.raadplegen", ["geoit.basic", "geoit.projects", "geoit.notities", "geoit.dwf"]) .directive("raadplegenDirective", raadplegen.RaadplegenDirective) .service("projectManager", ProjectManager) .controller("projectController", ["projectManager", "$timeout", "$translate", projects.ProjectController]) .run(["config", "gisViewerManager", "toolbarService", "commandBag", "$translate", function (config, vm, toolbarService, commandBag, $translate) { console.log("RAADPLEGEN.RUN", { toolbar: toolbarService, commandBag: commandBag }); config.enableProjects = false; vm.on("map-load", function () { var commands = [ { command: "Home", requireSecurity: true }, { command: "security.User", requireSecurity: true }, { command: "separator", requireSecurity: true }, //---------- //moduleName + ".Projects", "notities.Open", //"schetsen.Open", "dwf.Open", "separator", //---------- "Print", "measure.Measure", "crab.SearchAddress", "TrackMyLocation", "featureinfo.ShowSelection", "gislegend.Legend" ]; var commandKeys = commands.select(function (x) { if (typeof x === "string") { return x; } if (config.securityEnabled && x.requireSecurity) { return x.command; } return null; }).where(function (x) { return x; }); toolbarService.buildTree(commandKeys); }); }]) // load app .run(["config", "globalNgBootstrapper", "basicviewerNgBootstrapper", "homeNgBootstrapper", "notitiesNgBootstrapper", "dwfNgBootstrapper", "viewerNgBootstrapper", "menuNgBootstrapper", "securityManager", "locationHashHelper", "$timeout", "$rootScope", function (config, globalBs, basicviewerBs, homeBs, notitiesBs, dwfBs, viewerBs, menuBs, securityManager, locationHashHelper, $timeout, $rootScope) { if (config.errorMessage) { return; } var overlay = $('body').spinnerOverlay(); var complete = function (type) { console.log('APP.' + type); overlay.remove(); } // set niscode on rootScope $rootScope.niscode = config.niscode; Promise.resolve() // 1. init global .then(function () { return globalBs.init(config); }) // 2. init viewer .then(function () { return viewerBs.init(config); }) // init navigation .then(function () { return menuBs.init(config); }) // 3. init basicviewer .then(function () { return basicviewerBs.init(); }) // init home BS .then(function () { return homeBs.init({ baseUrl: config.baseUrl, application: config.application }); }) // 6. init notities BS .then(function () { return notitiesBs .init({ baseUrl: config.baseUrl, version: config.version, enableProjects: config.enableProjects, canEdit: !config.securityEnabled || securityManager.hasRole("global", "notities_editeren"), autoLoad: false }); }) // 7. init dwf BS .then(function () { return dwfBs .init({ baseUrl: config.baseUrl, version: config.version, enableProjects: config.enableProjects, canEdit: !config.securityEnabled || securityManager.hasRole("global", "dwf_editeren"), autoLoad: false }); }) // 8. load global .then(function () { return globalBs.load(); }) // 10. load viewer .then(function () { return viewerBs.load(); }) // load navigation .then(function () { return menuBs.load(); }) // load basicviewer .then(function () { return basicviewerBs.load(); }) // load home .then(function () { return homeBs.load({ baseUrl: config.baseUrl, application: config.application }); }) // load notities .then(function () { return notitiesBs.load(); }) // load dwf .then(function () { return dwfBs.load(); }) .then(function () { //console.log("EXECUTING HASH EVENTS", { hashParams: H.query() }); locationHashHelper.executeHashchangeEvents(H.query()); }) // 17. trigger view update .then(function () { complete('LOADED'); return $timeout(); }).catch(function (err) { complete('FAILED'); G.handleError(err); }).then(function () { $rootScope.completeAppLoaded(); }); } ]); })("raadplegen"); var redlining = redlining || {}; redlining.module = (function (moduleName) { "use strict"; return angular.module("geoit.redlining", ["geoit.global"]) .directive("redliningDirective", redlining.RedliningDirective) .run(["commandBag", "$translate", function (commandBag, $translate) { commandBag.add([{ name: "Redlining", content: '', title: function () { return $translate("redlining.Redlining"); } }]); }]) .run(["config", function (config) { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/" + moduleName + ".css?v=" + config.version); }]); })("redlining"); var schetsen = schetsen || {}; schetsen.module = (function (moduleName) { "use strict"; return angular.module("geoit.schetsen", ["geoit.global", "geoit.messages", "geoit.viewer", "geoit.projects"]) .directive("schetsenMarkerPointsCirclesDirective", schetsen.MarkerPointsCirclesDirective) .directive("schetsenMarkerPointsDirectionDirective", schetsen.MarkerPointsDirectionDirective) .directive("schetsenDirective", schetsen.SchetsenDirective) .service("schetsenService", ["config", "$http", schetsen.SchetsenService]) .service("schetsenManager", ["schetsenService", "gisViewerManager", schetsen.SchetsenManager]) .controller("schetsenController", ["projectManager", schetsen.SchetsenController]) // module bootstrapper .service("schetsenNgBootstrapper", ["schetsenManager", "projectManager", "commandBag", "$translate", "gisViewerManager", "panelHelper", function schetsenNgBootstrapper(schetsenManager, projectManager, commandBag, $translate, gisViewerManager, panelHelper) { var bootstrapper; this.init = function (config) { console.log(moduleName + '.init'); bootstrapper = new schetsen.Bootstrapper(config, schetsenManager); return Promise.resolve(bootstrapper) // css .then(function (bs) { return bs.initCss(); }) // commands .then(function (bs) { return bs.initCommands(commandBag, $translate); }) // projects .then(function (bs) { if (config.enableProjects) { return bs.initProjects(projectManager, gisViewerManager); } return bs; }); }; this.load = function () { console.log(moduleName + '.load'); return Promise.resolve(bootstrapper) // elements .then(function (bs) { return bs.initElements(commandBag, panelHelper); }) // loadLayers .then(function (bs) { return bs.initLayers(gisViewerManager); }); }; }]); })("schetsen"); var security = security || {}; security.module = (function (moduleName) { "use strict"; return angular.module("geoit.security", []) .factory("securityConfig", ["config", function (config) { return { baseUrl: config.baseUrl, niscode: config.niscode, taalcode: config.taalcode, clientSession: config.clientSession, user: config.user, userDisplay: config.userDisplay }; }]) .service("securityManager", security.SecurityManager) .service("securityUserService", ["securityConfig", "$http", security.UserService]) .service("securityUserManager", ["securityUserService", security.UserManager]) .controller("securityUserController", ["securityUserManager", security.UserController]) .component("securityUserSelector", security.userSelectorComponent("Content/modules/" + moduleName + "/user-selector/user-selector.html")) .directive("selectUserDirective", security.SelectUserDirective) .controller("selectUserController", security.SelectUserController) .directive("securityUserFormDirective", security.UserFormDirective) .controller("securityUserFormController", security.UserFormController) //css .run(["config", function (config) { $.loadCss(config.baseUrl + "/Content/modules/" + moduleName + "/module.css?v=" + config.version); }]) .run(["commandBag", "securityConfig", "$compile", "$rootScope", function (commandBag, config, $compile, $rootScope) { if (config.userDisplay) { commandBag.add([{ name: "security.User", content: '', callback: function () { var el = $('
    '); $compile(el)($rootScope.$new()); el.appendTo($('body')); } }]); } }]); })("security"); var signalisatie = signalisatie || {}; signalisatie.module = (function (moduleName) { "use strict"; return angular.module("geoit.signalisatie", ["geoit.basic", "geoit.projects", "geoit.vectorfeatures", "geoit.pictures", "geoit.notities", "geoit.dwf", "geoit.gipod"]) // config .factory("signalisatieConfig", ["config", "$translate", function (config, $translate) { var signalisatieUrl = config.baseUrl + "/Handlers/SignalisatieHandler.aspx"; var group = { Code: moduleName, Title: "Signalisatie" }; $translate("signalisatie.Signalling") .then(function (translatedGroup) { group.Title = translatedGroup; }); var submitProjectUrl = Q.query("submit_project_url"); var returnValue = { version: config.version, baseUrl: config.baseUrl, securityEnabled: config.securityEnabled, niscode: config.niscode, user: config.user, userRoles: config.roles, projectenTitle: config.projectenTitle, signalisatieTitle: config.signalisatieTitle, symbolUrl: signalisatieUrl + "?type=symbol", categoryUrl: signalisatieUrl + "?type=category", projectUrl: signalisatieUrl + "?type=project", getProjectUsersUrl: signalisatieUrl + "?type=project/GetProjectUsers&projectId={projectId}", saveProjectUsersUrl: signalisatieUrl + "?type=project/SaveProjectUsers&projectId={projectId}", group: group, submitProjectUrl: submitProjectUrl, }; EventHandler.injectInto(returnValue); return returnValue }]) // Hotkeys .service("hotkeyService", function () { this.on = function (keys, callback) { return hotkeys(keys, callback); }; }) // Backup .service("signalisatieBackupManager", signalisatie.BackupManager) // category .service("signalisatieCategoryService", ["signalisatieConfig", "$http", "$translate", function (config, $http) { return new signalisatie.CategoryService({ niscode: config.niscode, baseUrl: config.baseUrl, url: config.categoryUrl }, $http); }]) // security .service("projectSecurityService", ["projectSecurityServiceFactory", "signalisatieConfig", function (factory, config) { return factory.create(config, moduleName); }]) .service("projectSecurityManager", ["projectSecurityManagerFactory", function (factory) { return factory.create(moduleName); }]) // project .provider("projectService", function () { this.$get = ["signalisatieConfig", "imageHelper", "featureHelper", "$http", "$translate", function (config, imageHelper, featureHelper, $http, $translate) { return new signalisatie.ProjectService({ niscode: config.niscode, baseUrl: config.baseUrl, url: config.projectUrl }, imageHelper, featureHelper, $http, $translate); }]; }) .service("projectManager", ["projectService", "gisdocumentConfig", signalisatie.ProjectManager]) .service("projectGisManager", ["signalisatieConfig", "gisViewerManager", "gisVectorManager", "geoHelper", function (config, gisViewer, vectorManager, geoHelper) { return new signalisatie.ProjectGisManager({ group: config.group }, gisViewer, vectorManager, geoHelper); }]) .controller("projectController", ["config", "projectManager", "projectSecurityManager", "fileHelper", "$timeout", "$translate", signalisatie.ProjectController]) .component("projectFilter", signalisatie.projectFilterComponent("Content/modules/" + moduleName + "/project/project-filter.html")) .component("projectList", projects.projectListComponent("Content/modules/" + moduleName + "/project/project-list.html")) .component("projectForm", signalisatie.projectFormComponent("Content/modules/" + moduleName + "/project/project-form.html")) .component("projectFormVlario", signalisatie.projectFormComponent("Content/modules/" + moduleName + "/project/project-form-vlario.html")) .component("projectAdmin", signalisatie.projectFormComponent("Content/modules/" + moduleName + "/project/project-admin.html")) .component("projectButtons", signalisatie.projectButtonsComponent("Content/modules/" + moduleName + "/project/project-buttons.html")) // features .service("signalisatieFeatureManager", ["featureManagerFactory", function (factory) { return factory.create(); }]) .service("signalisatieFeatureStyleManager", ["featureStyleManagerFactory", function (factory) { return factory.create(); }]) .service("signalisatieFeatureGisManager", ["featureGisManagerFactory", function (factory) { return factory.create(); }]) .service("signalisatieFeatureHtmlManager", ["featureHtmlManagerFactory", function (factory) { return factory.create(); }]) .service("signalisatieFeatureFabricManager", ["featureFabricManagerFactory", function (factory) { return factory.create($("#fabric-canvas")); }]) .controller("signalisatieFeatureController", ["signalisatieFeatureManager", "featureHelper", vectorfeatures.FeatureController]) .controller("signalisatieFeatureStyleController", ["signalisatieFeatureStyleManager", vectorfeatures.FeatureStyleController]) .controller("vectorfeaturesFeatureHtmlController", ["signalisatieFeatureHtmlManager", vectorfeatures.FeatureHtmlController]) .component("signalisatieFeatureList", vectorfeatures.featureListComponent("Content/modules/" + moduleName + "/feature/feature-list.html")) .component("signalisatieFeatureStyling", vectorfeatures.stylingComponent("Content/modules/" + moduleName + "/feature/feature-styling.html")) .component("signalisatieFeatureGeometry", vectorfeatures.geometryComponent("Content/modules/" + moduleName + "/feature/feature-geometry.html")) .component("signalisatieGeomSelector", viewer.geometrySelectorComponent("Content/modules/" + moduleName + "/feature/geom-selector.html")) .component("signalisatieAdvancedGeomSelector", viewer.geometrySelectorComponent("Content/modules/" + moduleName + "/feature/advanced-geom-selector.html")) // symbols .component("signalisatieSymbolList", pictures.pictureListComponent("Content/modules/" + moduleName + "/symbol/symbol-list.html")) // signalisatie .controller("signalisatieController", ["projectManager", "signalisatieFeatureManager", "signalisatieBackupManager", "featureHelper", "signalisatieFeatureHtmlManager", "signalisatieFeatureFabricManager", "imageHelper", "gisViewerManager", "$timeout", "signalisatieConfig", signalisatie.SignalisatieController]) .component("signalisatieButtons", signalisatie.buttonsComponent("Content/modules/" + moduleName + "/signalisatie-buttons.html")) .directive("signalisatieDirective", signalisatie.SignalisatieDirective) // module bootstrapper .service("signalisatieNgBootstrapper", ["signalisatieConfig", "signalisatieCategoryService", "projectManager", "signalisatieFeatureManager", "projectGisManager", "signalisatieFeatureGisManager", "signalisatieFeatureStyleManager", "signalisatieFeatureHtmlManager", "signalisatieFeatureFabricManager", "featureHelper", "signalisatieBackupManager", "gisSnappingManager", "gisViewerManager", "projectSecurityManager", "securityUserManager", "indexService", "printService", "hotkeyService", "pictureService", "commandBag", "toolbarService", "infoContainerManager", "onlineStateService", "locationHashHelper", "$translate", "$timeout", "$compile", "$rootScope", "$http", function (signalisatieConfig, categoryService, projectManager, featureManager, projectGisManager, featureGisManager, featureStyleManager, featureHtmlManager, featureFabricManager, featureHelper, backupManager, snappingManager, gisViewer, projectSecurityManager, userManager, indexService, printService, hotkeyService, pictureService, commandBag, toolbarService, infoContainerManager, onlineStateService, locationHashHelper, $translate, $timeout, $compile, $rootScope, $http) { var bootstrapper; this.init = function (config) { bootstrapper = new signalisatie.Bootstrapper(config, signalisatieConfig, categoryService, projectManager, infoContainerManager, $timeout, $rootScope, $http); return Promise.resolve(bootstrapper) .then(function (bs) { return bs.initGipodConfig(); }) // css .then(function (bs) { return bs.initCss(); }) // project data .then(function (bs) { return bs.initProjectData(indexService); }) // feature data .then(function (bs) { return bs.initFeatureData(featureManager, featureHelper, projectSecurityManager); }) // backup .then(function (bs) { return bs.initBackup(featureManager, backupManager); }) // feature style .then(function (bs) { return bs.initFeatureStyle(featureStyleManager, featureManager, featureHelper); }) // project gis .then(function (bs) { return bs.initProjectGis(projectGisManager, snappingManager, gisViewer); }) // security .then(function (bs) { return bs.initSecurity(projectSecurityManager, userManager); }) // feature gis .then(function (bs) { return bs.initFeatureGis(featureGisManager, featureManager, projectGisManager, snappingManager, gisViewer, featureHelper); }) // feature html .then(function (bs) { return bs.initFeatureHtml(featureHtmlManager, featureManager, featureHelper, featureGisManager, gisViewer); }) // pictures -> droppable viewer .then(function (bs) { return bs.initDroppableViewer(gisViewer, featureManager, pictureService); }) // commands .then(function (bs) { return bs.initCommands(commandBag, $translate); }) // print .then(function (bs) { return bs.initPrint(printService); }) // shortcuts .then(function (bs) { return bs.initShortCuts(hotkeyService, featureManager, featureHelper, gisViewer); }); }; //this.loadGipodConfig = function () { // return Promise.resolve(bootstrapper) // .then(function (bs) { // return bs.initGipodConfig(); // }); //} this.load = function () { return Promise.resolve(bootstrapper) // toolbar .then(function (bs) { return bs.initToolbar(toolbarService); }) .then(function (bs) { return bs.initOnlineState(onlineStateService); }) // load gipod config //.then(function (bs) { // return bs.initGipodConfig(); //}) // elements .then(function (bs) { return bs.initElements(commandBag, featureManager, $compile); }) // panels - navigation .then(function (bs) { return bs.initPanels(commandBag, backupManager); }) // feature fabric .then(function (bs) { return bs.initFeatureFabric(featureFabricManager, featureManager, featureHelper, featureGisManager, gisViewer); }) // hash events .then(function (bs) { return bs.initHashEvents(locationHashHelper, commandBag); }); }; } ]) // load app .run(["config", "signalisatieConfig", "signalisatieNgBootstrapper", "globalNgBootstrapper", "basicviewerNgBootstrapper", "homeNgBootstrapper", "picturesNgBootstrapper", "notitiesNgBootstrapper", "dwfNgBootstrapper", "viewerNgBootstrapper", "menuNgBootstrapper", "securityManager", "projectManager", "locationHashHelper", "commandBag", "$timeout", "$rootScope", function (config, signalisatieConfig, signalisatieBs, globalBs, basicviewerBs, homeBs, picturesBs, notitiesBs, dwfBs, viewerBs, menuBs, securityManager, projectManager, locationHashHelper, commandBag, $timeout, $rootScope) { if (config.errorMessage) { return; } var overlay = $('body').spinnerOverlay(); var complete = function (type) { console.log('APP.' + type); overlay.remove(); } // set niscode on rootScope $rootScope.niscode = config.niscode; signalisatieConfig.gipodEnabled = securityManager.hasRole('signalisatie_gipod'); signalisatieConfig.layers = { WERKEN: "Werken", HINDER: "Hinder", GRONDWERKEN: "Grondwerken", EVENEMENT_INNAME: "EvenementInname", OMLEIDINGEN: "omleidingen_" }; signalisatieConfig.contactTypeIds = { AANNEMER: 'a55eb0a5-84fb-49f8-83c5-de669e4ae48e', DOSSIER_BEHEERDER: 'aad5e947-f7bf-4592-a84a-f591555b0b8b', AANVRAGER: '88888888-8888-8888-8888-888888888888' }; Promise.resolve() // 1. init global .then(function () { return globalBs.init(config); }) // 2. init viewer .then(function () { return viewerBs.init(config); }) // init navigation .then(function () { return menuBs.init(config); }) // 3. init basicviewer .then(function () { return basicviewerBs.init(); }) //// load gipod config //.then(function () { // return signalisatieBs.loadGipodConfig(); //}) // 4. init signalisatie BS .then(function () { return signalisatieBs .init({ baseUrl: config.baseUrl, projectenTitle: config.projectenTitle, signalisatieTitle: config.signalisatieTitle, gipodEnabled: signalisatieConfig.gipodEnabled, gipodConfigApi: config.gipodConfigApi, gipodApiBaseUrl: config.gipodApiBaseUrl, netelandNiscodes: config.netelandNiscodes, canEdit: true,//!config.securityEnabled || securityManager.hasRole(moduleName, "editeren"), version: config.version }); }) // init home BS .then(function () { return homeBs.init({ baseUrl: config.baseUrl, application: config.application }); }) // 5. init pictures BS .then(function () { return picturesBs .init({ baseUrl: config.baseUrl, version: config.version, canEdit: !config.securityEnabled || securityManager.hasRole("global", "pictures_editeren") }); }) // 6. init notities BS .then(function () { return notitiesBs .init({ baseUrl: config.baseUrl, version: config.version, enableProjects: true, canEdit: !config.securityEnabled || securityManager.hasRole("global", "notities_editeren"), autoLoad: false }); }) // 7. init dwf BS .then(function () { return dwfBs .init({ baseUrl: config.baseUrl, version: config.version, enableProjects: true, canEdit: !config.securityEnabled || securityManager.hasRole("global", "dwf_editeren"), autoLoad: false }); }) // 8. load global .then(function () { return globalBs.load(); }) // 10. load viewer .then(function () { return viewerBs.load(); }) // load navigation .then(function () { return menuBs.load(); }) // 9. load basicviewer .then(function () { return basicviewerBs.load(); }) // load home .then(function () { return homeBs.load({ baseUrl: config.baseUrl, application: config.application }); }) // 13. load notities data .then(function () { return notitiesBs.load(); }) // 14. load dwf data .then(function () { return dwfBs.load(); }) // 15. load pictures data .then(function () { return picturesBs.load(); }) // 11. load signalisatie .then(function () { return signalisatieBs.load(); }) // activate project .then(function () { return projectManager.activateByQuery({ id: config.userLastProjectId }); }) // hash events .then(function () { //console.log("EXECUTING HASH EVENTS", { hashParams: H.query() }); locationHashHelper.executeHashchangeEvents(H.query()); }) .then(function() { if (signalisatieConfig.submitProjectUrl) { commandBag.execute(moduleName + ".ShowSignalisatie"); } }) // 17. trigger view update .then(function () { complete('LOADED'); return $timeout(); }).catch(function (err) { complete('FAILED'); G.handleError(err); }).then(function () { $rootScope.completeAppLoaded(); }); } ]); })("signalisatie"); var sitesettings = sitesettings || {}; sitesettings.module = (function () { return angular.module("geoit.sitesettings", []) .provider("siteSettingsManager", function () { var pv = this; pv.fontSize = null; pv.$get = function () { var ssm = new sitesettings.SiteSettingsManager(); ssm.init({ fontSize: pv.fontSize }); return ssm; }; }) .controller("siteSettingsController", ["siteSettingsManager", sitesettings.SiteSettingsController]); })("sitesettings"); var vectorfeatures = vectorfeatures || {}; vectorfeatures.module = (function (moduleName) { return angular.module("geoit.vectorfeatures", ["geoit.global", "geoit.viewer", "geoit.commands"]) .service("featureHelper", function () { return new vectorfeatures.FeatureHelper(null); }) .service("olStyleManager", ["gisViewerManager", vectorfeatures.OlStyleManager]) .service("featureGisConverter", ["gisViewerManager", "olStyleManager", vectorfeatures.FeatureGisConverter]) .service("featureHtmlConverter", ["featureHelper", "gisViewerManager", "imageHelper", vectorfeatures.FeatureHtmlConverter]) .service("featureFabricConverter", ["featureHelper", "gisViewerManager", "imageHelper", vectorfeatures.FeatureFabricConverter]) //.service("vfOfflineFeatureServiceFactory", vectorfeatures.OfflineFeatureServiceFactory) .factory("featureManagerFactory", ["featureHelper", function (featureHelper) { return { create: function () { return new vectorfeatures.FeatureManager(featureHelper); } } }]) .factory("featureStyleManagerFactory", ["featureHelper", "imageHelper", "gisViewerManager", "geoHelper", function (featureHelper, imageHelper, gisViewerManager, geoHelper) { return { create: function () { return new vectorfeatures.FeatureStyleManager(featureHelper, imageHelper, gisViewerManager, geoHelper); } } }]) .factory("featureGisManagerFactory", ["featureGisConverter", "gisViewerManager", "geoHelper", function (featureGisConverter, gisViewer, geoHelper) { return { create: function () { return new vectorfeatures.FeatureGisManager(featureGisConverter, gisViewer, geoHelper); } } }]) .factory("featureHtmlManagerFactory", ["featureHtmlConverter", function (featureHtmlConverter) { return { create: function () { return new vectorfeatures.FeatureHtmlManager(featureHtmlConverter); } } }]) .factory("featureFabricManagerFactory", ["featureFabricConverter", "imageHelper", function (featureFabricConverter, imageHelper) { return { create: function (canvasEl) { return new vectorfeatures.FeatureFabricManager(canvasEl, featureFabricConverter, imageHelper); } } }]) .controller("vfFeatureController", vectorfeatures.FeatureController) //feature-toolbar .service("featuresToolbarService", commands.CommandManager) .controller("featuresToolbarController", ["commandBag", "featuresToolbarService", "$timeout", commands.CommandsController]) .directive("featuresToolbar", commands.ToolbarDirectiveFactory.create("featuresToolbarController")) //commands .run(["commandBag", "$translate", function (commandBag, $translate) { commandBag.add([{ name: moduleName + ".DrawLabel", content: '', title: function () { return $translate("global.DrawLabel"); } }, { name: moduleName + ".DrawLine", content: '', title: function () { return $translate("global.DrawLine"); } }, { name: moduleName + ".DrawPolygon", content: '', title: function () { return $translate("global.DrawPolygon"); } }, { name: moduleName + ".CopyGeometry", content: '', title: function () { return $translate("global.CopyGeometry"); } }]); }]) //toolbar .run(["featuresToolbarService", function (toolbarService) { toolbarService.buildTree("DrawLabel,DrawLine,DrawPolygon,CopyGeometry".split(",").select(function (x) { return moduleName + "." + x; })); }]) //css .run(["config", function (config) { $.loadCss(config.baseUrl + "/Content/modules/vectorfeatures/styling/styling.css?v=" + config.version); }]); })("vectorfeatures"); var viewer = viewer || {}; viewer.module = (function (moduleName) { "use strict"; return angular.module("geoit.viewer", ["geoit.messages"]) .factory("gisHandler", ["config", "$http", function (config, $http) { var url = config.baseUrl + "/Handlers/GisHandler.aspx"; return { get: function (action, o) { var params = $.extend({}, o || {}, { action: action, session: config.sessionId, map: config.mapName }); return $http.get(url + "?" + Q.toQuery(params)) .then(function (response) { return response.data; }) .catch(function (error) { console.error("ERROR in GisHandler", { error: error, url: url, params: params, o: o }); throw error; }); }, post: function (action, o) { var params = { action: action, session: config.sessionId, map: config.mapName }; return $http.post(url + "?" + Q.toQuery(params), o) .then(function (response) { return response.data; }) .catch(function (error) { console.error("ERROR in GisHandler", { error: error, url: url, params: params, o: o }); throw error; }); } } }]) .factory("layerTree", viewer.LayerTree) .service("geoHelper", GeoHelper) // path="../../js/gis/geohelper.js" .factory("geoHandler", ["config", function (config) { return new GeoHandler(config.baseUrl + "/Handlers/GeoHandler.aspx"); }]) // path="../../js/gis/geohandler.js" .service("gisStateService", StateService) .service("gisViewerManager", ["mapElement", "layerTree", "gisHandler", "geoHelper", "geoHandler", viewer.GisViewerManager]) .service("gisVectorManager", viewer.GisVectorManager) .service("gisSnappingManager", ["gisViewerManager", "layerTree", viewer.SnappingManager]) .service("gisFeatureService", viewer.GisFeatureManager) .controller("viewerController", viewer.IndexController) .controller("snappingController", ["gisSnappingManager", viewer.SnappingController]) // messages .service("infoContainerManager", messages.InfoManager) .controller("infoContainerController", ["infoContainerManager", "$timeout", messages.InfoController]) .component("infoContainer", messages.infoContainerComponent("Content/modules/" + moduleName + "/info-container/info-container.html")) .controller("viewerInfoController", ["infoContainerManager", "gisViewerManager", viewer.ViewerInfoController]) // components .component("geomSelector", viewer.geometrySelectorComponent("Content/modules/" + moduleName + "/components/geom-selector.html?")) // directives //.directive("infoContainerDirective", viewer.InfoContainerDirective) .directive("geometrySelector", viewer.GeometrySelectorDirective) .directive("zoomButton", viewer.ZoomDirective) .directive("gisProgressOverlay", global.GisProgressOverlayDirective) // gis-toolbar .service("gisToolbarManager", commands.CommandManager) .controller("gisToolbarController", ["commandBag", "gisToolbarManager", "$timeout", commands.CommandsController]) .directive("gisZoomToolbar", commands.ToolbarDirectiveFactory.create("gisToolbarController")) // bootstrapper .service("viewerNgBootstrapper", ["gisViewerManager", "infoContainerManager", "commandBag", "gisToolbarManager", "layerTree", "gisSnappingManager", "geoHelper", "$translate", "$timeout", "$compile", "$rootScope", function (gisViewerManager, infoManager, commandBag, gisToolbarManager, layerTree, gisSnappingManager, geoHelper, $translate, $timeout, $compile, $scope) { var bootstrapper; this.init = function (config) { console.log(moduleName + '.init'); bootstrapper = new viewer.Bootstrapper(config, gisViewerManager, $translate, $timeout, $compile, $scope); return Promise.resolve(bootstrapper) // css .then(function (bs) { return bs.initCss(); }) // commands .then(function (bs) { return bs.initCommands(commandBag); }) // info .then(function (bs) { return bs.initInfo(infoManager); }); }; this.load = function () { console.log(moduleName + '.load'); return Promise.resolve(bootstrapper) // toolbar .then(function (bs) { return bs.initToolbar(gisToolbarManager); }) // snapping .then(function (bs) { return bs.initSnapping(gisSnappingManager, geoHelper); }) // map-load .then(function (bs) { return bs.initMap(); }) // elements .then(function (bs) { return bs.initElements(); }) .then(function (bs) { //console.log("LOAD_VIEWER", { layers: layerTree }); return bs; }); }; }]); })("viewer");