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) {
return vm._translate('aansluitingen.ImportSuccess').then(function (translation) {
state.completed();
var msg = { type: 'validate', message: translation, status: 400};
vm.handleError(msg);
setTimeout(function () {
location.reload(); //reload page nadat gebruiker msg heeft kunne leze dat het gelukt is en de pagina gaat refreshen
}, 2000);
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,
ZoekSignalisatieVergunning: 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("', '") + "')",
"SignalisatieVergunning": "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')",
"SignalisatieVergunning": "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,
signalisatieVergunning: signalisatieConfig.layers.SIGNALISATIE_VERGUNNING
}
},
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]: "",
[signalisatieConfig.layers.SIGNALISATIE_VERGUNNING]: "",
"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'),
ZoekSignalisatieVergunningen: $('#cbSignalisatieVergunning').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("', '") + "')",
[signalisatieConfig.layers.SIGNALISATIE_VERGUNNING]: "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')",
"SignalisatieVergunning": "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($('